Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why comma ' , ' and plus ' + ' log the console output in different pattern?

Tags:

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.

like image 481
brk Avatar asked Oct 26 '15 06:10

brk


People also ask

What is comma in console log?

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.

How do you put a comma in console log?

You need to use the + operator instead of the comma as in the example below. console. log("foo was born on the day: " + maydate.

What is the purpose of console log method?

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.

Why do we log things to the console?

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.


1 Answers

+(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.

like image 126
Tushar Avatar answered Sep 30 '22 05:09

Tushar