Why throwing exception in comma operator does not stop the evaluation of other operands?

Viewed 63

I've noticed very interesting behavior in JavaScript.
Look at these two lines and tell me how their behavior will differ:

(() => { throw Error('err'), console.log('ok') })()
(() => { throw Error('err'); console.log('ok') })()

The only difference is that the first line is comma expression, second's not.
But in the first case, "ok" is printed to the console before the error!

How is this possible? Based on the docs, those expressions should be evaluated from left to right. So I would expect the exception to stop evaluation.

Snippets:

(() => { throw Error('err'), console.log('ok') })()

(() => { throw Error('err'); console.log('ok') })()

1 Answers

throw is a statement that cannot be used to attain a value (e.g. const x = throw "foo"; will not work). Your first example is actually being parsed as throw (Error("err"), console.log("ok")), which means it creates a new error, does not throw that error, logs "ok", returns undefined, then throws that undefined after the log.

Related