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

前端 未结 2 427
温柔的废话
温柔的废话 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().

提交回复
热议问题