Why is console.log("x:", x) better than console.log("x:" + x)? I have a category object that contains categoryId and name. When I write console.log("x:", x), the console gives me
Data: (5) [{…}, {…}, {…}, {…}, {…}]
However, if I use console.log("x:" + x), the console gives me
Data: [object, object][object, object][object, object][object, object][object, object]
I wonder what is the reason and why there is a difference?
The reason why using console.log("Data:"+x) does not output the desired result when console.log("Data:",x) does (x is the variable name of your object) is because of the way that JavaScript works. In the first example, Javascript will first evaluate the string passed as a parameter (the "Data:"+x).
Since JavaScript can only convert an object to a string when it is passed as an argument to a JSON.stringify() function, the object will not be preserved within the evaluation of the string, and it will instead be replaced with "[object Object]".
Javascript will interpret console.log("Data:",x) differently. The first parameter, "Data:", is passed and logged into the console first. In the same line, the data object is logged as an object datatype, as the object is not next to a string and therefore will not be evaluated as a string before being logged into the console.