Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does javascript accept commas in if statements?

I stumbled across some javascript syntax that seemed like it should produce a parse error of some kind but doesn't:

if (true, true) {console.log('splendid')} else {console.log('horrid')} // splendid if (true, false) {console.log('splendid')} else {console.log('horrid')} // horrid 

It seems only the last expression affects the logic, though all expressions are executed:

if  (console.log('super'), true) {console.log('splendid')} // super splendid 

Anyone know why that is valid javascript syntax? Is there any practical use for it?

like image 697
Matt Avatar asked Mar 18 '11 04:03

Matt


People also ask

Are commas necessary in JavaScript?

A comma is not an option It is truly important where you put your comma. Defining an array and enumerate elements, you must separate them with a comma. What you actually can do is omitting values. If you want to have every second entry of an array, but keep the indexes of the array.

What do commas do in JavaScript?

JavaScript uses a comma ( , ) to represent the comma operator. A comma operator takes two expressions, evaluates them from left to right, and returns the value of the right expression. In this example, the 10, 10+20 returns the value of the right expression, which is 10+20. Therefore, the result value is 30.

How is comma operator useful in a for loop?

The comma operator will always yield the last value in the comma separated list. Basically it's a binary operator that evaluates the left hand value but discards it, then evaluates the right hand value and returns it. If you chain multiple of these they will eventually yield the last value in the chain.


2 Answers

The comma operator chains multiple expressions together, and the result of the operation is the value of the last operand. The only real use for it is when you need multiple side effects to occur, such as assignment or function calls.

like image 176
Ignacio Vazquez-Abrams Avatar answered Oct 01 '22 22:10

Ignacio Vazquez-Abrams


The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.

https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/Comma_Operator

https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Expressions_and_Operators#comma_operator

like image 35
Adam Ayres Avatar answered Oct 01 '22 21:10

Adam Ayres