Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript console.log(object) vs. concatenating string

I'm running this in node.js:

> x = { 'foo' : 'bar' } { foo: 'bar' } > console.log(x) { foo: 'bar' } undefined > console.log("hmm: " + x) hmm: [object Object] undefined 

What I don't understand is why console.log(x) "pretty-prints" the object, whereas string concatenation "ugly-prints" it. And more importantly, what's the best way to make it print hmm: { foo: 'bar' }?

like image 492
John Zwinck Avatar asked Jan 30 '13 05:01

John Zwinck


People also ask

What is the best way to concatenate strings in JavaScript?

The + Operator The same + operator you use for adding two numbers can be used to concatenate two strings. You can also use += , where a += b is a shorthand for a = a + b . If the left hand side of the + operator is a string, JavaScript will coerce the right hand side to a string.

Can you concatenate strings in JavaScript?

The concat() method joins two or more strings. The concat() method does not change the existing strings. The concat() method returns a new string.

What does .LOG do in JavaScript?

The console. log() is a function in JavaScript which is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user. Syntax: console.


1 Answers

The + x coerces the object x into a string, which is just [object Object]:

http://jsfiddle.net/Ze32g/

The pretty printing is a very nice and probably very complex underlying code that someone implemented as part of the console object and the log method.

Try this:

console.log("hmm: ", x); 
like image 164
Explosion Pills Avatar answered Sep 24 '22 09:09

Explosion Pills