If you open a JS Console in your browser (in my case Chrome) and type:
{} + []
you will get 0, but when you type
console.lo
Empty object as {}
returns "[object Object]"
when you call its toString()
method. Empty array returns ""
when you call its toString()
method. Thus, console.log({} + [])
will output "[object Object]"
it's because {} is an object notation so whatever you concatenate with {} it will give you an [object Object]. I your case [] is an empty so it just shows an [object Object]. so if you could try the following you will got what you want.
console.log({} + 5);
[object Object]5 ///console shows
//And
console.log({} + "test");
VM65:1 [object Object]test //console shows
{}
can either be an empty block or a empty object literal depending on context.
+
can either be the unary plus operator or the concatination operator depending on context.
The first code example is an empty block it might as well not be there, making the expression the same as +[]
, meaning "An empty array converted to a number".
You can't have a block as a function argument, so the second code example {}
is an object and the code means "Concatinate an object with an array" (implicitly converting both object and array to strings).
When you see {}
character at the beginning it is interpreted as a empty block
or empty
object literal(when you're creating objects).
When you're using an expression
or statement, +
represent the plus operator, which coerces
its operand(in this case it will be []
) to a number.
So +[]
is the same as Number([])
, which evaluates to 0.
The unary
plus
operator internally use the ToNumber
abstract operation.
Read more about Type Conversions and operators.
console.log(Number([]));
With the other words, {} + []
expression is an empty
code block followed by an array
which will be constraint to a number(Number[]
).
In the second example you're providing you just concat
an object literal(empty object) to an array. That't why you're receiving [object Object]
.