-1
const array=[{title:'Name',body:'My name is Hacker'},{title:'Age', body:'My age is 2020'}]

Given the above code, what is the difference between the following lines of code?

console.log('Items',array);
console.log('Items'+array);

Why is different output being printed to console?

Image link for reference: https://i.sstatic.net/GhRQc.png

1

3 Answers 3

1

This happen because when you use the + operator, you're converting the array to a string, concatenating 'Items' with it and passing the resulting string to the first parameter. The array converts to [object Object],[object Object], so the output is Items[object Object],[object Object].

If you put the array in the second parameter, since the first parameter doesn't contain any format specifiers (%s, %o, etc...), most browsers will try to format the array with "optimally useful formatting" and print it after the string. Note that the spec does not require that behavior, as the Printer function is implementation-defined.

Sign up to request clarification or add additional context in comments.

Comments

0

The best way is to use console.table, BTW the console.log("Items" +array) prints out "Items [object object], on the other hand console.log("Items", array) prints out the array content

Comments

0

When you use concatenate any variable with string the result will be printed in the format of the string.

'Items',array

in the above statement, there is no concatenation, so they print normally. but when you use "Items"+array entire statement will be print in the form of string.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.