Skip to content Skip to sidebar Skip to footer

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 ex

Solution 1:

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

Solution 2:

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

Post a Comment for "Why Comma ' , ' And Plus ' + ' Log The Console Output In Different Pattern?"