-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.stack.imgur.com/GhRQc.png

D. Pardal
  • 6,173
  • 1
  • 17
  • 37
Madhavi
  • 1
  • 1
  • Does this answer your question? [How to print object array in JavaScript?](https://stackoverflow.com/questions/14895287/how-to-print-object-array-in-javascript) – Aman Srivastava May 17 '20 at 10:20

3 Answers3

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.

D. Pardal
  • 6,173
  • 1
  • 17
  • 37
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

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.

shaik shajahan
  • 199
  • 1
  • 1
  • 9