Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Number([]) === 0 and Number({}) === NaN in Javascript?

Tags:

javascript

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?

like image 407
Ivan Avatar asked Jun 21 '12 18:06

Ivan


2 Answers

Using 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.

like image 144
ThiefMaster Avatar answered Sep 29 '22 12:09

ThiefMaster


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.

like image 22
tskuzzy Avatar answered Sep 29 '22 13:09

tskuzzy