DEV Community


Comma operator in JS

sasscrafter profile image Dima Prohorenko ・1 min read

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
Enter fullscreen mode Exit fullscreen mode

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());


// Output c
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

Forem Open with the Forem app