The Purpose Of The Comma Operator In Javascript (x, X1, X2, …, Xn)
Solution 1:
The comma operator evaluates every operand but only returns the result of the last evaluation. It can be used to initialize multiple variable in a for loop.
var str = "Hello, World!";
for(var i = 0, len = str.length; i < len; i++)
console.log(str.charAt(i));
Edit: As pointed out in the comments, this isn't a true example of the comma operator, this is just the var
. You can see this page for actual examples.
Solution 2:
http://en.wikipedia.org/wiki/Comma_operator
Like in C and C++, the comma operator evaluates both the left and right operands, returning the right operand. In terms of practical uses, a, b
can be used in place of a ? b : b
, as well as used as a limited way to fit multiple 'statements' into one statement, such as in the first or third parts of a for
loop.
Note that declaring and/or defining multiple variables with var
, separated by commas, is not a use of the comma operator, even though it uses the comma symbol. The comma operator evaluates to and forms an expression, which can be used as a value as part of a larger expression or statement. var
is a complete statement type that takes the form
var name1 [= value1][, name2 [= value2][, ...]];
Solution 3:
The MDC docs has a good example of a practical use for the comma operator:
If a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to increment two variables at once. The code prints the values of the diagonal elements in the array:
for (var i = 0, j = 9; i <= 9; i++, j--)
document.writeln("a[" + i + "][" + j + "] = " + a[i][j]);
Post a Comment for "The Purpose Of The Comma Operator In Javascript (x, X1, X2, …, Xn)"