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

  • A+

This is a pretty common and useful practice:

// default via value var un = undefined var v1 = un || 1  // default via a function call var myval = () => 1 var v2 = un || myval() 

But it doesn't work (SyntaxError) when throwing an error:

var v3 = un || throw new Error('un is not set!') 

Is there a way how to achieve the same effect in a similarly elegant way? This is IMHO a lot of boilerplate code:

if (!un) {     throw new Error('un is not set!') } var v3 = un 

Or is there any theoretical obstruction, why this is not, and never will be, possible?


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 if - throw.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: