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

前端 未结 5 1085
慢半拍i
慢半拍i 2021-02-06 20:41

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          


        
5条回答
  •  情书的邮戳
    2021-02-06 21:05

    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).

提交回复
热议问题