console.log(+(1, 2, 3, 4))
// returns undefined
// expected 10😩
- why is this valid?
- why is the result undefined?
- what's happening here?
console.log(+(1, 2, 3, 4))
// returns undefined
// expected 10😩
1, 2, 3, 4
is the comma operator - it evaluates to 4, and +4
also evaluates to 4
.
console.log()
itself always returns undefined
, it just prints its argument to the console (4, in this case).
If you want to get 10 from 1, 2, 3, and 4, you can do [1, 2, 3, 4].reduce((a, b) => a + b)
, for example.
See this MDN article on the comma operator.
super weird behaviour!