There is a js interview question, the question is as follows: What is the execution result of the following code and why?
var i, j, k;
for (i=0, j=0; i<10, j<6; i++, j++) {
k = i+j;
}
(k);
The answer is to show 10. This question mainly examines the comma operator of JavaScript.
Below isMDNDefinition of comma operator:
The comma operator calculates two operands (from left to right) and returns the value of the second operand.
According to this definition, you can extend it:
The comma operator calculates two or more operands from left to right and returns the value of the last operand.
You can feel the following code:
alert((0, 9));
alert((9, 0));
if (0,9) alert("ok");
if (9,0) alert("ok");
What is the role of comma operators in actual code?
1. Exchange variables without a third variable
var a = "a", b = "b";
//Method 1
a = [b][b = a, 0];
//Method 2
a = [b, b = a][0];
2. Simplify the code
if(x){
foo();
return bar();
}
else{
return 1;
}
Can be abbreviated as:
return x ? (foo(), bar()) : 1;