Comma operator in JS
Dima Prohorenko
Posted on March 12, 2021
Comma operator allows you to put multiple statements, where one is expected.
for (let i = 0, j = 0; i < 5; i++, j += 2) {
console.log(`i=${i}, j=${j}`);
}
// Output
// i:0, j:0
// i:1, j:2
// i:2, j:4
// i:3, j:6
// i:4, j:8
When placed in an expression, it evaluates every expression from left to right and returns the right most expression.
const a = () => 'a';
const b = () => 'b';
const c = () => 'c';
const x = (a(), b(), c());
console.log(x);
// Output c
Also ,
operator has the lowest priority, so without parenthesis the expression would look like const (x = a()), b(), c();
.
Note that the ,
operators in assignments may appear not to have the normal effect of ,
operators because they don't exist within an expression. In the following example, a is set to the value of b = 3 (which is 3) and c = 4
is evaluated and its result is returned to the console(4).
let a, b;
a = b = 3, c = 4; // Returns 4
console.log(a); // Output 3
π πͺ π
π©
Dima Prohorenko
Posted on March 12, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript How to convert html to pdf (something like a generated invoice) and send it to an email
July 16, 2022