I was playing around with arrays in Javascript today and noticed this little gem:
alert([1, 2, 3] == [1, 2, 3]); //alerts false
It strikes me as rather odd that the array is not equal to itself.
But then I noticed this, which was even weirder:
alert([1, 2, 3] == "1,2,3"); //alerts true
?!?!?!?!!!?
Why in the world is [1, 2, 3] not == to itself but is == to the string?
I realize that == is not the same as ===. Even so, what evilness could cause Mr. Javascript do such weird things?
Ok, so first you need to understand how javascript treats values in your program. All of your variables that you create are going to merely be references to a location in memory where that object is stored. Therefore, when you do this:
…it does three things:
You can check for some sane behavior by running this code:
Now for your question about the string
When you use the
==operator tries to convert the two operands to the same type (evil behavior…I know…)When it does this, it decides to convert both to a string before it does the compare (thus the result is really
"1,2,3" === "1,2,3", which evaluates to true.I can’t give you a complete picture, as there are few people who understand every nuance of the madness that is JavaScript, but hopefully this clears some of the fog.