Introduction and usage examples of comma operators in JavaScript
- 2020-05-16 06:23:00
- OfStack
There is an js interview question. The question is: what is the result of the execution of the following code and why?
var i, j, k;
for (i=0, j=0; i<10, j<6; i++, j++) {
k = i+j;
}
document.write(k);
The answer is to display 10, which focuses on the comma operator JavaScript.
Here is MDN's definition of the comma operator:
The comma operator evaluates two operands (from left to right) and returns the value of the second operand.
According to this definition, you can extend 1:
The comma operator evaluates two or more operands from left to right and returns the value of the last operand.
You can feel 1 in the following code:
alert((0, 9));
alert((9, 0));
if (0,9) alert("ok");
if (9,0) alert("ok");
What role does the comma operator play in actual code?
1. Exchange variables without the third variable
var a = "a", b = "b";
// methods 1
a = [b][b = a, 0];
// methods 2
a = [b, b = a][0];
2. Simplify your code
if(x){
foo();
return bar();
}
else{
return 1;
}
It can be abbreviated as:
return x ? (foo(), bar()) : 1;