SoFunction
Updated on 2025-03-03

Introduction and usage examples of comma operators in JavaScript

There is a js interview question, the question is as follows: What is the execution result of the following code and why?

Copy the codeThe code is as follows:

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:

Copy the codeThe code is as follows:

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

Copy the codeThe code is as follows:

var a = "a", b = "b";

//Method 1
a = [b][b = a, 0];

//Method 2
a = [b, b = a][0];

2. Simplify the code

Copy the codeThe code is as follows:

if(x){
  foo();
  return bar();
}
else{
  return 1;
}

Can be abbreviated as:

Copy the codeThe code is as follows:

return x ? (foo(), bar()) : 1;