Ivan Chernykh
Ivan Chernykh

Reputation: 42166

Javascript - brackets in console.log method issue

This post inspired me. I've made some tests.

console.log( false, 5 ); prints false 5 , and it's ok.

console.log( ( false, 5 ) ); prints 5. Now we know that it's ok too because ( false, 5 ) returns 5.

But why does console.log( false, {}, 5 ); print false Object {} 5?

Also console.log( ( false, {}, 5 ) ); and even console.log( ( false, { i:0 }, 5 ) ); both prints 5. Why is 5 is preferred to {}?

You can see here: http://jsfiddle.net/3uUwY/

Upvotes: 2

Views: 2925

Answers (4)

hazzik
hazzik

Reputation: 13344

By putting brakets you make only one argument to console.log. So following

console.log( false, 5 ); // here you are using log function with 2 argumetns 

And here

console.log( ( false, { i:0 }, 5 ) ); // here is only one argument.

Inside a brakets you are using comma operator.

And the comma operator always returns last expression.

So you could rewrite your expression like this:

var x = ( false, { i:0 }, 5 ); // x is 5 here
console.log( x );

Upvotes: 1

hazzik
hazzik

Reputation: 13344

By putting brakets you make only one argument to console.log. So following

console.log( false, 5 ); // here you are using log function with 2 argumetns 

And here

console.log( ( false, { i:0 }, 5 ) ); // here is only one argument.

Inside a brakets you are using comma operator.

And the comma operator always returns last expression.

So you could rewrite your expression like this:

var x = ( false, { i:0 }, 5 ); // x is 5 here
console.log( x );

Upvotes: 1

Pedro L.
Pedro L.

Reputation: 7536

When using brackets you are forcing Javascript to evaluate that expression.

console.log(a, b, c); // 3 parameters, the function prints a, b and c

console.log((a, b, c)); // 1 parameter. It prints the result of 
                        // evaluating (a, b, c) and, as it's said 
                        // in the other answer, it returns the last element
                        // of the expression.

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382112

The comma operator always returns the last element, which is 5.

Upvotes: 6

Related Questions