简体   繁体   中英

What is the difference between console.log(“Result” +vaRiable) and console.log(“Result”, vaRiable)?

Please be kind, I am a self learner. I try to find answers on my own sometimes.

```vaRiable =['2','4','6']

console.log("Result:"+vaRiable);
console.log("Result:",vaRiable);```

a particular array

vaRiable =['2','4','6']

when I console.log("Result:" +vaRiable); output = Result:2,4,6

console.log("Result :", vaRiable); output = Result: ['2','4','6']

what is the '+' doing to the string? Why is there two types of output? Can somebody quip me a one liner.It'll be great help. Thanks

"Result:"+vaRiable is a single expression. The Result: string is concatenated with the vaRiable , creating another string. When an array is coerced to a string, its elements are joined by commas. So you get 'Result:' + '2,4,6' , or Result:2,4,6 . That one string is then passed to console.log and printed to the console.

In contrast:

console.log("Result :", vaRiable);

sends two parameters to console.log . They don't get concatenated together, because they're separate parameters. When multiple parameters are passed to console.log , each is logged individually (though on the same line).

When you perform "Result:"+vaRiable the value of vaRiable is being type coerced into a string so that it can be concatenated to "Result" . What you're doing in the first example is essentially creating a new string equal to "Result:2,4,6" because that's what arrays look like when they're cast to strings, similar to calling [2, 4, 6].toString() or [2, 4, 6].join(',') .

In the second example, console.log() is doing regular console output of the array, which is why it keeps the brackets; it knows it's an array and to give it special formatting.

When you do ("Result:" + vaRiable) , what the + is doing is to concatenate your string with your array into a single whole string.

When you do ("Result:", vaRiable) you're printing two messages . In this case you're not concatenating, the first message is a string Result: and the second message is an array ['2','4','6'] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM