+ 1

JavaScript Quiz Question Help

var a={value:20} var b={value:20} alert(a==b) why is this false??? a and b are equal, aren’t they?

30th May 2018, 2:48 AM
RexMayhem
RexMayhem - avatar
3 Answers
+ 3
That's because in JavaScript, objects are compared by reference. That means JavaScript looks if both objects are pointing to the same memory. They are unlike strings or numbers that are compared by value in equality operations. var a = {value:20}; var b = {value:20}; alert(a == b); // false var c = b; alert(c == b); //true
30th May 2018, 3:13 AM
Jonathan Pizarra (JS Challenger)
Jonathan Pizarra (JS Challenger) - avatar
+ 2
Hi RexMayhem Just to add to Jonathan's answer if you want to compare the contents of an Object you can use Node.js deep compare lib https://www.npmjs.com/package/deep-equal or convert object to string using JSON stringify JSON.stringify(a) === JSON.stringify(b); https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
30th May 2018, 11:25 AM
Mike Choy
Mike Choy - avatar
+ 1
Thanks for your answers! That helps. I’ll just post another reference for beginners like myself to review some elementary JS: https://www.w3schools.com/js/js_objects.asp
30th May 2018, 2:35 PM
RexMayhem
RexMayhem - avatar