https://bigfrontend.dev/quiz/Implicit-Conversion-II
What does the code snippet below output by console.log
?
console.log([] + []);
console.log([] + 1);
console.log([[]] + 1);
console.log([[1]] + 1);
console.log([[[[2]]]] + 1);
console.log([] - 1);
console.log([[]] - 1);
console.log([[1]] - 1);
console.log([[[[2]]]] - 1);
console.log([] + {});
console.log({} + {});
console.log({} - {});
console.log([] + []); // ""
console.log([] + 1); // "1"
console.log([[]] + 1); // "1"
console.log([[1]] + 1); // "11"
console.log([[[[2]]]] + 1); // "21"
console.log([] - 1); // -1
console.log([[]] - 1); // -1
console.log([[1]] - 1); // 0
console.log([[[[2]]]] - 1); // 1
console.log([] + {}); // "[object Object]"
console.log({} + {}); // "[object Object][object Object]"
console.log({} - {}); // NaN
-
[] + []
returns""
, because[]
is coerced to an empty string usingArray
'stoString()
method. First,+
operator tries to convert[]
into a primitive value withArray
'svalueOf()
method, but it returns the array itself, so thevalueOf()
method is ignored. Then+
usesArray
'stoString()
as fallback and it returns an empty string. -
[] + 1
returns"1"
, because+
operator tries string concatenation before numeric addition, if one of the operands is a string.. The same logic also applies to[[]] + 1
,[[1]] + 1
and[[[[2]]]] + 1
. -
[] - 1
returns-1
, because-
operator triggers numeric conversion for[]
: first,[]
is converted to an empty string using thetoString()
method; then the empty string is converted to0
. The same logic applies to[[]] - 1
,[[1]] - 1
and[[[[2]]]] - 1
. -
[] + {}
returns"[object Object]"
, because+
operator tries to convert both[]
and{}
to primitive values. SinceObject
'svalueOf()
method returns the object itself,{}
is converted to"[object Object]"
using thetoString()
method. The same logic applies to{} + {}
. -
{} - {}
returnsNaN
, because-
operator triggers numeric conversion for{}
: first,{}
is coerced to"[object Object]"
using thetoString()
method; then"[object Object]"
is converted toNaN
.