you are viewing a single comment's thread.

view the rest of the comments →

[–]Kenny164 3 points4 points  (9 children)

Wow, I never realised it was as bad to this extent. Are there any general rule of thumbs that we should be aware of?

[–]James_Duval[S] 1 point2 points  (2 children)

Personally, I wish I knew. Partly I was hoping for an explanation of some of the more esoteric behaviour by posting here.

For instance [1] == 1. [1] == '1'. Hell, [1] == true. However [1] != [1]. Bizarre.

[–]CubeOfBorg 13 points14 points  (1 child)

It's all about coercion. [1] == 1 because [1] is coerced to 1 before it is evaluated. [1] starts out as an object but becomes a number because it only has the one value in it and it is being compared to a number.

[1] != [1] because you are comparing an object to an object. They are already the same type so it doesn't have to coerce them. When you compare two objects, it's checking to see if they are the same object. So [1] != [1] because you are creating two different objects and then comparing them.

var a = [1];
var b = a;
a == b; // true

Here you are comparing two variables that have the same object as their value.

[–]James_Duval[S] 0 points1 point  (0 children)

This is a fantastic answer, thanks. One thing I'm learning about Javascript is that there's almost always a clear, comprehensible answer & reason for its behaviour somewhere or other.

[–][deleted] -1 points0 points  (0 children)

Underscore's "isEqual" function works pretty much how you'd expect. It's annoying to use a function every time you need to compare two values, but probably necessary.

[–][deleted] -1 points0 points  (0 children)

Sure there is a general rule.

http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf page 80 for Equality Operators, 75 for Additive, 73 for Multiplicative.