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 Make a Constructor Challenge

Why does this work and not the other?

Why does this code return undefined when dice10.roll() is called?

function dice(sides){ this.sides = sides; this.roll = function (){ console.log( Math.floor(Math.random() * this.sides) + 1); };
}

var dice10 = new dice(10);

dice10.roll();

but this one actually works

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

var dice10 = new dice(10);

dice10.roll();

1 Answer

Paul Cox
Paul Cox
12,671 Points

The accepted answer is incorrect. The first example doesn't return the roll value in the roll function, it logs it to the console. A function returns undefined if a value was not returned. Therefore, when running the code in the console, the 1st example will display the roll value then undefined in the console, whereas the 2nd example will only display the roll value.