Skip to content Skip to sidebar Skip to footer

{} + [] - Why It Is 0 Or [object Object]?

If you open a JS Console in your browser (in my case Chrome) and type: {} + [] you will get 0, but when you type console.log({} + []) you get [object Object]... any ideas why the

Solution 1:

{} 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).

Solution 2:

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 unaryplus 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].

Solution 3:

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]"

Solution 4:

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);
 [objectObject]5///console shows //Andconsole.log({} + "test");
VM65:1 [objectObject]test //console shows

Post a Comment for "{} + [] - Why It Is 0 Or [object Object]?"