Search code examples
javascriptvariable-assignmentparentheses

Why does this JavaScript assignment not raise an error: const a = (1, 2, 3, 4);


const a = (1, 2, 3, 4);
console.log(a);

const b = 1, 2, 3, 4;
console.log(b);

In the above example, a will be assigned the value 4, while the second line will raise an error. Why does the first assignment "succeed". Why is it valid JS syntax?


Solution

  • The comma operator returns the last expression listed. It works in the first case because it is parenthesized and parsed as a single expression. However, once a valid expression is finished after a = - in the second case, 1 - and the next token is a comma, JavaScripts expects another identifier to declare, so you can declare multiple variables like this:

    let a = 1, b = 2;