The comma operator in Javascript

Comma operator in Javascript can be used to evaluate expressions from left to right and return the result of last statement.


The statement above means that

  • Execute statement1
  • Execute statement2
  • Execute statement3
  • Return result of statement3

The following example illustrates the concept:

var a=1;
var b = (a++,a++,a++,a);  

b is 4, which means the 3 statements has been executed and last statement is returned.

When you combine comma operator with ternary operator, the number of lines can be reduced:

(isStringValidated?(processString(),showMessage()) : showError())

The example above checks if the string is validated, if it is validated 2 methods are called from left to write. If it is not validated, then another method is called.


[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator
[2] http://stackoverflow.com/questions/9579546/when-is-the-comma-operator-useful

No comments:

Post a Comment