Home >Web Front-end >JS Tutorial >Introduction and usage examples of comma operator in JavaScript_javascript skills
There is a js interview question, the question is this: What is the execution result of the following code and why?
The answer is 10. This question mainly examines JavaScript’s comma operator.
The following 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, it can be expanded:
The comma operator evaluates two or more operands from left to right and returns the value of the last operand.
You can feel the code below:
if (0,9) alert("ok");
if (9,0) alert("ok");
What role does the comma operator play in actual code?
1. Exchange variables, no third variable is needed
//Method 1
a = [b][b = a, 0];
//Method 2
a = [b, b = a][0];
2. Simplified code
can be abbreviated as: