By ttulka


2019-02-11 07:52:57 8 Comments

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?

5 comments

@Patrick Hollweck 2019-02-11 08:06:27

Your problem is that an assignment expects an expression but you give it a statement

The Syntax for initializing/assigning a variable is:

var|let|const <variableName> = <expression>

but you use

var|let|const <variableName> = <statement>

which is invalid Syntax.

Expressions

An expression is something that produces a value.

What is a "value"?

A value is anything that is a type in Javascript

  • Numbers
  • Strings
  • Booleans
  • Objects
  • Arrays
  • Symbols

Examples for Expressions:

Literals

var x = 5;

x is assigned the value "5"

A function call

var x = myFunc();

myFunc() produces a value that is assigned to x

The produced value of a function is its return value - A function always returns, and if it doesn't explicitly, it returns undefined.

Functions have the added benefit of being able to contain statements in their body - Which will be the solution to your question - But more on that later.

Statements

A statement is something that performs an action. For Example:

A loop

for (var i = 0; i < 10; i++) { /* loop body */ }

This loop performs the action of executing the loop body 10 times

Throwing an error

throw new Error()

Unwinds the stack and stops the execution of the current frame

So why can't we mix both?

When you want to assign to a variable, you want an expression because you want the variable to have a value.

If you think about it, it should be clear that it will never work with a statement. Giving a variable an "action" is nonsense. What is that even supposed to mean?

Therefore you cannot use the throw statement since it does not produce a value.

You can only have one or the other. Either you are (expression) something or you do (statement) something.

A fix

You can convert any statement into an expression by wrapping it in a function, I suggest using an IIFE (Immediately invoked function expression) - basically a function that invokes itself - to do just that

var x = 5 || (() => throw new Error())()

This works because the right side is now a function and a function is an expression which produces a value.

Future Possibilities

Technically there is nothing that prevents this from working.

Many languages (c++, ...) actually already treat throw as an expression. Some (kotlin, ...) even leave out statements completely and treat everything as an expression.

Others (c#, php, ...) provide workarounds like the ?? null-concealing or ?. elvis operator to solve this very use case.

Maybe in the future we get one of those features into the ecmascript standard (there is even an open proposal to include this) until then your best bet is to use a function like:

function assertPresent(value, message)
{
  if(!value) {
    throw new Error(message);
  } else {
    return value;
  }
}

@TheHansinator 2019-02-11 13:54:51

As an aside, C# 6 allowed "throw" to be an expression precisely to enable scenarios like this - the return type of the expression was inferred from context. I imagine that something like this would be even easier to conceptually add to JavaScript, since it doesn't check return types at compile time.

@jcaron 2019-02-11 17:37:26

Nitpicking, it's the || operator which is expecting two expressions here, not the assignment.

@The Vee 2019-02-11 18:13:53

It's also an expression (of type void) in C++.

@6502 2019-02-13 09:16:23

Like others have said the problem is that throw is a statement and not an expression.

There is however really no need for this dichotomy. There are languages where everything is an expression (no statements) and they're not "inferior" because of this; it simplifies both syntax and semantic (e.g. you don't need separate if statements and the ternary operator ?:).

Actually this is just one of the many reasons for which Javascript (the language) kind of sucks, despite Javascript (the runtime environment) being amazing.

A simple work-around (that can be used also in other languages with a similar limitation like Python) is:

function error(x) { throw Error(x); }

then you can simply write

let x = y.parent || error("No parent");

There is some complexity in having throw as an expression for statically typed languages: what should be the static type of x() ? y() : throw(z)?; for example C++ has a very special rule for handling a throw expression in the ternary operator (the type is taken from the other branch, even if formally throw x is considered an expression of type void).

@Cristik 2019-02-14 00:30:42

Just a note that your work-around was already provided in stackoverflow.com/a/54626116/1974224.

@Beefster 2019-02-12 00:38:02

As other answers have stated, it is because throw is a statement, which can't be used in contexts which expect expressions, such as on the right side of a ||. As stated by others, you can get around that by wrapping the exception in a function and immediately calling it, but I'm going to make the case that doing so is a bad idea because it makes your intent less clear. Three extra lines of code is not a big deal for making the intent of your code very clear and explicit. I personally think that throw being statement-only is a good thing because it encourages writing more straightforward code that is less likely to cause other developers to scratch their heads when encountering your code.

The || defaulting idiom is useful when you want to provide default or alternative values for undefined, null, and other falsy values, but I think it loses a lot of its clarity when used in a branching sense. By "branching sense", I mean that if your intent is to do something if a condition holds (the doing something in this case being throwing an exception), then condition || do_something() is really not a clear way to express that intent even though it is functionally identical to if (!condition) {do_something()}. Short-circuit evaluation isn't immediately obvious to every developer and || defaulting is only understood because it's a commonly-used idiom in Javascript.

My general rule of thumb is that if a function has side effects (and yes, exceptions count as side effects, especially since they're basically non-local goto statements), you should use an if statement for its condition rather than || or &&. You're not golfing.

Bottom line: which is going to cause less confusion?

return value || (() => {throw new Error('an error occurred')})()

or

if (!value) {
    throw new Error('an error occurred')
}
return value

It's usually worth it to sacrifice terseness for clarity.

@ttulka 2019-02-12 06:55:05

An exception is a side effect indeed, but - if not used for flow control - it's just an exception (can lead to a system crash, and that's fine), not a flow control. Using if statement attracts the eye of the reader and mentally makes from an exception to a flow control, which is wrong, because exceptions should not be used in that manner. Written as I proposed makes an exception to an assertion, which is better (could be easily ignored by the reader). But maybe the best would be not to use such checks at all and let the runtime itself deal with wrong parameters...

@Beefster 2019-02-12 07:57:39

@ttulka If your intent is to have an assertion, you would be far better off having an assert function defined somewhere that wraps this intention. Something like function assert(value, message) { if (value) {return value} else {throw new Error(message || 'assertion failed')}} will do just fine. Or you could use an assertion library. You can even remove the assertion for release builds with assert = () => {}

@Beefster 2019-02-12 08:04:12

And even if an exception isn't used for flow control, it still effectively acts as a goto somewhere with catch statements effectively being comefroms. Now this can be reasonable in many cases, especially when in JS they're used more like panics and caught at the top of some sort of dispatcher, but exceptions can often lead to surprises when not caught at the API boundaries.

@ttulka 2019-02-12 08:46:18

I don't think it is same. If I don't do the explicit check, an exception will be thrown anyway, I just want to "customize" it. The idea with assert is okay, but it's not different from proposals in other answers. My motivation is to use language constructs directly without any boilerplate code.

@Beefster 2019-02-12 08:51:56

An if statement isn't boilerplate. You don't even have to include the braces if all you're doing is throwing an exception. Then you can keep it on the same line.

@ttulka 2019-02-12 08:54:28

if statement isn't boilerplate in general, but it is in this case, because un || throw new Error('fail') is much simpler. But this is a taste thing, so no need to discuss it on here.

@Nina Scholz 2019-02-11 07:56:40

You could move the throwing of the exception into a function, because throw is a statement of control flow, and not an expression:

An expression is any valid unit of code that resolves to a value.

const throwError = function (e) { throw new Error(e); };

var un = undefined,
    v3 = un || throwError('un is not set!');

@Dan Robertson 2019-02-11 10:09:09

Why not just have const throwf = function(err) { throw err } and then it can be used anywhere.

@T.J. Crowder 2019-02-12 10:14:00

Of note: throw expressions are at Stage 2 of the process for being added to the language. :-) Until/unless that happens, a function wrapper like the (updated) one above is the simple workaround.

@CertainPerformance 2019-02-11 07:57:03

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.

@usr 2019-02-11 19:47:46

It's worth pointing out that throw could have been made an expression. Maybe a future language version will enable this pattern.

@Ben Blank 2019-02-11 20:08:32

In fact, there's already a stage 2 proposal to add throw expressions to the language. Alas, it'll still be a while before it's available for use.

@KRyan 2019-02-12 04:57:25

Our project—in Typescript, so the pattern is perhaps more transparent—we have a core utility module that includes export function crash(message: string): never { throw new Error(message); } and all throws are done via this function. Useful because now it’s an expression (and the never return annotation indicates it won’t return because it throws), and because we can put a breakpoint in it (we have a high-level catch block to produce a custom error message rather than it merely being sent to the console, but this can prevent the debugger from breaking on the throw).

Related Questions

Sponsored Content

5 Answered Questions

[SOLVED] What is TypeScript and why would I use it in place of JavaScript?

  • 2012-10-02 16:37:58
  • Mohammed Thabet
  • 473407 View
  • 1569 Score
  • 5 Answer
  • Tags:   javascript typescript

25 Answered Questions

[SOLVED] How does JavaScript .prototype work?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

11 Answered Questions

[SOLVED] Why don't self-closing script elements work?

12 Answered Questions

14 Answered Questions

[SOLVED] .trim() in JavaScript not working in IE

4 Answered Questions

16 Answered Questions

[SOLVED] Why would a JavaScript variable start with a dollar sign?

7 Answered Questions

2 Answered Questions

[SOLVED] Possible to throw new errors from Ajax success event?

Sponsored Content