Detecting an undefined object property

后端 未结 30 3818
花落未央
花落未央 2020-11-21 04:43

What\'s the best way of checking if an object property in JavaScript is undefined?

30条回答
  •  庸人自扰
    2020-11-21 05:27

    ECMAScript 10 introduced a new feature - optional chaining which you can use to use a property of an object only when an object is defined like this:

    const userPhone = user?.contactDetails?.phone;
    

    It will reference to the phone property only when user and contactDetails are defined.

    Ref. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

提交回复
热议问题