1

I don't want to ask why [] + [] gives you empty string, or so on, as we can't change it. And the reason is just a design of the language.

My question is about following inconsistency, noticed in Chrome and FF Firebug JS consoles:

{} + []; // outputs 0
console.log({} + []); // outputs [object Object]
var c = {} + [];
console.log(c); // outputs [object Object]

I understand that expression returns a value, and this is what you see in console output. But why this return value changes, when assigned to a variable or output using console.log()?

Does it mean that mentioned consoles are buggy?

Is there any better explanation then stating that this is the way it's done?

3

2 Answers 2

4

In your first example, it is just a block, so it is equivalent to running this code (the plus in front of the array literal converts it to a number):

{};
+[]; // 0

However, in your console.log code, it is considered an expression, so it is in fact an object literal. You can only pass expressions to functions, so this is the same.

function a(b) {return b;}
a({}+[]); // "[object Object]"

The addition operation converts them to a string, so that's why you get "[object Object]".

Sign up to request clarification or add additional context in comments.

2 Comments

Instead of that identity function a simple grouping operator would've been enough: ({}+[]) ;-)
@Bergi: it was to prove the point that when passing arguments to a function, they are passed as expressions - just like the console.log() example.
3

It has nothing to do with console.log().

In {} + [] the {} is parsed as a block, whereas in the second two cases, it is parsed as an object as a part of an expression.

This is made evident by the fact that, console.log() or not, var a = {} + [] sets a to an object.

You can simplify the second two cases even further by simply adding parenthesis (which makes it an expression):

({} + [])  //=> "[object Object]"

1 Comment

This code convinced me the most: ({} + []). It's indeed a block. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.