Reputation: 423
I'm diving deep into JavaScript and came across some tricky behavior which I'm trying to understand. It's just learning purpose so please explain what's happening behind the scene if anyone knows.
Consider below outputs to understand what my concern is!
console.log(Number([])) // 0
console.log(Number([1])) // 1
The above output make sense as []
is blank it converts to 0 and if it has values then it converts to what value it holds in only first index.
console.log(Number(![])) // 0
console.log(Number(!0)) // 1 (not sure why)
console.log(Number([3,5])) // NaN (Not sure why)
The above three outputs are driving me crazy as I'm not getting what's happening there. Can anyone please explain what's happening under the hood?
Upvotes: 3
Views: 104
Reputation: 10096
This is due to type coercion, in this case both explicit and implicit.
Number([])
In the first example, the Array#toString()
method is called on []
, which results in ""
. After that the empty String is explicitly coerced to a Number, and Number("")
is 0.
Number([1])
In the second example the same is happening, just with Number("1")
in the end.
Number(![])
In the example following that, you can see that normally, converting, and empty Array to a Boolean results in true
, but since !
is inverting the coercion to boolean, this results in false
, which is then explicitly coerced to a Number, making it 0. Here, the toString()
method is never used.
Number(!0)
The next example is very straightforward, NOT 0
, or !0
is simply true
, which, when converted to a number is 1.
Number([3,5])
In the last example NaN
get's printed out, because the result of [3,5].toString()
is 3,5
, which isn't a Number.
Upvotes: 4
Reputation: 138457
When passing a non primitive to the constructor, it is coerced into a primitive and then into a number:
[3, 5] -> "3,5" -> NaN
[] -> "" -> 0
[1] -> "1" -> 1
When applying the negation operator (!) onto something that is converted into a boolean.
!0 -> !false -> true -> 1
!1 -> !true -> false -> 0
![] -> !true -> false -> 0
Upvotes: 4
Reputation: 345
If you try console logging both values, you'll see that
Upvotes: 0