Detecting an undefined object property

后端 未结 30 2857
花落未央
花落未央 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:30

    I didn't see (hope I didn't miss it) anyone checking the object before the property. So, this is the shortest and most effective (though not necessarily the most clear):

    if (obj && obj.prop) {
      // Do something;
    }
    

    If the obj or obj.prop is undefined, null, or "falsy", the if statement will not execute the code block. This is usually the desired behavior in most code block statements (in JavaScript).

提交回复
热议问题