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

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

    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!');

提交回复
热议问题