Using throw in a Javascript expression

Andres Riofrio picture Andres Riofrio · Mar 3, 2012 · Viewed 11.2k times · Source

Here is what I want to do:

var setting = process.env.SETTING || throw new Error("please set the SETTING environmental variable");
                                     ^^^^^

But the interpreter complains about "Syntax Error: Unexpected token throw".

Is there any way to throw an exception in the same line that we compare whether a value is falsey or not?

Answer

KooiInc picture KooiInc · Mar 3, 2012

You can make use of the functional nature of javascript:

var setting = process.env.SETTING || 
               function(){ 
                 throw "please set the SETTING environmental variable";
               }();
// es201x
var setting = process.env.SETTING || 
              (() => {throw `SETTING environmental variable not set`})();

or more generic create a function to throw errors and use that:

function throwErr(mssg){
    throw new Error(mssg);
}

var setting = process.env.SETTING || 
               throwErr("please set the SETTING environmental variable");

A snippet I use:

const throwIf = (
  assertion = false, 
  message = `An error occurred`, 
  ErrorType = Error) => 
      assertion && (() => { throw new ErrorType(message); })();

throwIf(!window.SOMESETTING, `window.SOMESETTING not defined`, TypeError);