I am using the console.log statement for debugging , but came across a scenario where using ',' or '+' with console.log statement is logging the output in different pattern.For example
(function() { var x = []; x.push({ a: 1, b: 2, }, { a: 4, b: 3, }, { a: 5, b: 6 }, { a: 7, b: 8, }) console.log('Logging with , ', x); console.log('Logging with + ' + x); }())
When I am using ',' with console.log I am seeing output as
Logging with , [Object, Object, Object, Object]
and each of this object is expandable.But with '+' I am seeing output as
Logging with + [object Object],[object Object],[object Object],[object Object]
For demonstration I have created this jsfiddle.
Can you please help me understanding why we see this difference.
The comma operator ( , ) evaluates each of its operands (from left to right) and returns the value of the last operand. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions.
You need to use the + operator instead of the comma as in the example below. console. log("foo was born on the day: " + maydate.
log() The console. log() method outputs a message to the web console. The message may be a single string (with optional substitution values), or it may be any one or more JavaScript objects.
console. log specifically is a method for developers to write code to inconspicuously inform the developers what the code is doing. It can be used to alert you that there's an issue, but shouldn't take the place of an interactive debugger when it comes time to debug the code.
+
(string concatenation operator) with object will call the toString
method on the object and a string will be returned. So, '' + object
is equivalent to object.toString()
. And toString
on object returns "[object Object]"
.
With ,
the object is passed as separate argument to the log method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With