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

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().


+(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.

Tags:

Javascript