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

Is there anything wrong with passing the number of sides into the anonymous function?

I was playing with my code and wrote this:

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

What is the disadvantage (if any) of doing this rather than setting the number of sides as a value to a key called sides? I though it would make the code more portable.

1 Answer

Casey Ydenberg
Casey Ydenberg
15,622 Points

The only problem is that you have to remember how many sides your dice has each time you call roll. It's better to be able to create a dice with a certain number of sides and then roll it as many times as you like.

function createDice(sides) {
  dice = {
    sides: sides,
    roll: function() {
      var randomNumber = Math.floor(Math.random() * this.sides) + 1;
      console.log(randomNumber);
    }
  }
  return dice;
}