`throw` as an expression?

# Axel Rauschmayer (11 years ago)

Use case: With promises, the expression body form of arrow functions is so convenient. Alas, throw being a statement, you can’t use it there. For example, the following code is not syntactically legal:

asyncFunc()
.then(count => count >= 0 ? count : throw new Error(...))
.then(...)
.catch(...);

Could throw be turned into an expression?

# Andrea Giammarchi (11 years ago)

probably not exactly the fat arrow usage you were looking for ... but it makes it trivial to inline any sort of block

asyncFunc()
.then(count => count >= 0 ? count : ()=>{throw new Error(...)}())
.then(...)
.catch(...);
# John Lenz (11 years ago)

or a simple utility method

# Brendan Eich (11 years ago)

John Lenz wrote:

or a simple utility method

Current keyword-anchored statement form does not require parens around expression to evaluate and throw.

# Nathan Wall (11 years ago)

On Thu, Oct 9, 2014 at 4:57 PM, John Lenz <concavelenz at gmail.com> wrote:

or a simple utility method

Promise.reject could be used.

asyncFunc()
.then(count => count >= 0 ? count : Promise.reject(new Error(...)))
.then(...)
.catch(...)

Nathan

# Isiah Meadows (11 years ago)

It would be convenient for throw to be one. Maybe an idea would be to treat it similar to void or delete? If it were an expression, it could be parsed very similarly. Here's a potential use case even without all the other ES6 additions.

function foo(bar) {
  bar == null && throw new TypeError();
  // do stuff with required parameter `bar`
}

// Currently, it requires this:
function foo(bar) {
  if (bar == null) {
    throw new TypeError();
  }
  // do stuff with required parameter `bar`
}

// Or, this: (totally stealing your hack, Andrea... :-P)
const foo = bar => bar == null ?
    ()=>{throw new TypeError()} :
    undefined; /* do something */

It wouldn't surprise me if this becomes included eventually in, say, Underscore/Lodash/etc. if not made an expression. It would just end up easier to type _.throw(new TypeError()).

To clarify, here's what I mean by treating it like void and delete:

void foo(); //=> returns undefined

delete bar[0]; //=> returns if the entry/property no longer exists

throw baz; //=> returns nothing/undefined (for sake of spec)?
# John Lenz (11 years ago)

Sure, but there is no pressing need here, "return" as an expression would be more interesting. Not that I'm asking for that.