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

前端 未结 5 1165
慢半拍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:12

    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.

提交回复
热议问题