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

getting error when trying to call new instance...why?

this is part of a code:

function dice(sides){

  this.sides = sides;

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

  }

}

// this is where the instance is called
var dice6 = new Dice(6);

dice6.roll();

the above instance is called for new Dice because you are suppose to call instances with the uppercase letter at the beginner (per proper syntax), HOWEVER, when I do I get the following error in the console:

dice.js:35 Uncaught ReferenceError: Dice is not defined

but when I change the Dice to lowercase dice the error vanishes. WHY? I thought this was the correct syntax for calling a new instance?

First line, function name, d vs D, maybe?

2 Answers

Steven Parker
Steven Parker
243,656 Points

The convention is to define constructors with a capital letter. But whether you follow that convention or not, you must always call it using the same spelling that it was defined with or you will see that error.

Oh jeeze, that was frustrating the crap out of me. Thank you!