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 trialjohn larson
16,594 Pointsdice.roll === dice10.roll evaluates to false, but were not comparing values. Curious about that.
function Dice(sides){
this.sides = sides;
this.roll = function(){
var randomNumber = Math.floor(Math.random() * this.sides) + 1;
}
}
var dice = new Dice(6);
var dice10 = new Dice(10);
console.log(dice.roll === dice10.roll); //evaluates to false
console.log(dice.roll);
console.log(dice10.roll);
//in the console, these log out the function not the value
//they appear to be the same
//why do they NOT evaluate to === true?
2 Answers
Simon McKeon
15,517 PointsTaken from a StackOverflow answer:
Because "equality" of object references, in terms of the == and === operators, is purely based on whether the references refer to the same object.
Stephan L
17,821 PointsSomeone more knowledgeable than me may take issue with this explanation, but the '===' operator proves true only when referring to the same instance of an object. In the above example, it's not accurate to say dice and dice10 are the same object, rather, they are separate instances of the Dice object. The separate methods Dice.roll() may perform the same task, but they are separate methods of two separate instances of the Dice object.
Because these separate instances of the Dice object take up different spaces in memory, so they are not strictly equal. A simpler example from the documentation:
var obj = new String("0");
var str = "0";
var a = str;
obj===str returns false. Just because they hold the same value doesn't mean they are of the same type. obj is a new instance of the String Object with a value of '0' and str is a separate instance of String. a===str returns true, because they are the same type and value (just like a===a would return true).
I think this is one of the harder concepts in Javascript to understand, so I hope that makes a little more sense.
john larson
16,594 PointsStephan, thank you. It's becoming a little clearer.
john larson
16,594 Pointsjohn larson
16,594 PointsSo in existential terms, because the object is printed out twice, even though it is the same object...it is not the same? Like I am the same person today and yesterday but I'm different because that's two separate instances of me?
ywang04
6,762 Pointsywang04
6,762 PointsIt's clear to me. Thx a lot.