-2

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?

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133

1 Answers1

1

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;
CoderCharmander
  • 1,862
  • 10
  • 18