Why comma ' , ' and plus ' + ' log the console output in different pattern?

I am using the console.log statement for debugging , but came across a scenario where using ',' or '+' with console.log statement is logging the output in different pattern.For example

(function() {
  var x = [];
    a: 1,
    b: 2,
  }, {
    a: 4,
    b: 3,
  }, {
    a: 5,
    b: 6
  }, {
    a: 7,
    b: 8,
  console.log('Logging with , ', x);
  console.log('Logging with + ' + x);

When I am using ',' with console.log I am seeing output as

Logging with ,  [Object, Object, Object, Object]

and each of this object is expandable.But with '+' I am seeing output as

Logging with + [object Object],[object Object],[object Object],[object Object]

For demonstration I have created this jsfiddle.

Can you please help me understanding why we see this difference.



+(string concatenation operator) with object will call the toString method on the object and a string will be returned. So, '' + object is equivalent to object.toString(). And toString on object returns "[object Object]".

With , the object is passed as separate argument to the log method.


To add possibly a little more clarity (or verbosity) with examples to Tushar's response:

With respect to concatenation (excluding console.log() stuff) use the + operator. The reason why you use comma in console.log() is because of the parameters that function takes is a variable amount of arguments.

So, if you do console.log('a' + 'b'), you get ab

but, if you do console.log('a' , 'b') you get a b

Now, if you do console.log('a' + {a : 'a'}) you get a[object Object] which isn't very useful,

whereas if you do console.log('a' , {a : 'a'}) you get a {a: 'a'}

So, the comma passes the object as a parameter, which uses the toString() of that object, which is preferable for console.log().


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.