Why doesn’t logical OR work with error throwing in JavaScript?

throw is a statement only; it may not exist in a position where an expression is required. For similar reasons, you can’t put an if statement there, for example

var something = false || if (cond) { /* something */ }

is invalid syntax as well.

Only expressions (things that evaluate to a value) are permitted to be assigned to variables. If you want to throw, you have to throw as a statement, which means you can’t put it on the right-hand side of an assignment.

I suppose one way would be to use an IIFE on the right-hand side of the ||, allowing you to use a statement on the first line of that function:

var un = undefined
var v2 = un || (() => { throw new Error('nope') })();

But that’s pretty weird. I’d prefer the explicit ifthrow.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)