Is there a standard function to check for null, undefined, or blank variables in JavaScript?

前端 未结 30 3575
眼角桃花
眼角桃花 2020-11-21 23:37

Is there a universal JavaScript function that checks that a variable has a value and ensures that it\'s not undefined or null? I\'ve got this code,

30条回答
  •  旧巷少年郎
    2020-11-22 00:04

    Take a look at the new ECMAScript Nullish coalescing operator

    You can think of this feature - the ?? operator - as a way to “fall back” to a default value when dealing with null or undefined.

    let x = foo ?? bar();
    

    Again, the above code is equivalent to the following.

    let x = (foo !== null && foo !== undefined) ? foo : bar();
    

提交回复
热议问题