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

前端 未结 2 410
温柔的废话
温柔的废话 2020-12-09 04:01

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 pat

相关标签:
2条回答
  • 2020-12-09 04:27

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

    0 讨论(0)
  • 2020-12-09 04:37

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

    0 讨论(0)
提交回复
热议问题