Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Object-Oriented JavaScript (2015) Constructor Functions and Prototypes Challenge Solution

Francis N
Francis N
10,376 Points

Getting [object Object] after click 'Roll Dice'

I am looking over my code and it matches the solution yet I am getting different results. I think I need to change the result variable to something in ui.js but I am not sure what to change it to.

Here is my code:

function Dice(sides) {
  this.sides = sides;
  this.roll = function() {
    var randomNumber = Math.floor(Math.random() * this.sides) + 1;
    return randomNumber;
  }
}

var dice = new Dice(6);

inside ui.js:

function printNumber(number) {
  var placeholder = document.getElementById("placeholder");
  placeholder.innerHTML = number;
}

var button = document.getElementById("button");

button.onclick = function() {
  var result = dice.roll();
  printNumber(result);
};

//Fixed Code Presentation

2 Answers

the variable dice is calling the Dice function with an argument of 6 Dice(6). When you click the button, It prints out the dice variable but because its an object. It prints out the object and not the results.

In order to get the result you would need to print the roll method dice.roll()

button.onclick = function() {
  var result = dice.roll();
  printNumber(result);
};

I hope this helps.

Francis N
Francis N
10,376 Points

thanks that did help. i dont recall that being part of the challenge solution video.

It's possible it might not be. haha! I completed the JavaScript track a few months ago. I gave my feedback based on the provided code.