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?
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?
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;