I was looking at the first table on /, and wanted to understand why, for example, 0 == []
and 0 != {}
. I'm assuming it's because Number([]) == 0
and Number({}) == NaN
. However, that part seems arbitrary. Why is an empty list 0
and empty object a NaN
?
I was looking at the first table on http://zero.milosz.ca/, and wanted to understand why, for example, 0 == []
and 0 != {}
. I'm assuming it's because Number([]) == 0
and Number({}) == NaN
. However, that part seems arbitrary. Why is an empty list 0
and empty object a NaN
?
3 Answers
Reset to default 16Using Number(some_object)
will use the string representation of the given object. For your examples the string representations are:
js> ({}).toString();
[object Object]
js> [].toString();
js>
The string '[object Object]'
cannot be converted to a number but the empty string ''
can.
To elaborate a bit on ThiefMaster's answer, I've taken a look into ECMAScript's specifications:
When converting a string into a number, a grammar is used for the conversion. In particular, the mathematical value of StringNumericLiteral ::: [empty]
is defined as 0. In fact, it's 0 for any whitespace.
When one value is an object ([],{}) and the other is a number or string, operator == converts the object to a primitive value (a number in this case) using the built-in conversion methods which all objects in Javascript inherit: toString() and valueOf().
For generic objects like {}, valueOf is used, and by default it returns the object itself, which is != 0.
For built-in arrays, toString is used. This method applied to an array returns a string containing all the elements joined by commas. For the empty array, it returns an empty string, ''.
Then the interpreter applies valueOf to that string; the return value of this method for an empty string is 0, so [] == 0.
[[[[[[[[123]]]]]]]] == 123
. – Niet the Dark Absol Commented Jun 21, 2012 at 18:42==
, not found in===
, is being applied?) – user166390 Commented Jun 21, 2012 at 18:44(![]+[])[+[]]+(![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]] === 'fail'
– ThiefMaster Commented Jun 21, 2012 at 18:48==
will convert both operands to numbers in this case. – Felix Kling Commented Jun 21, 2012 at 18:56===
but the body use==
? Which one(s) is the question actually asking about? – Redwood Commented Jun 22, 2012 at 18:24