0

While checking if there is a value for a property in an object, I was using if(prop in object) return object[prop] else object[prop] = x (x is some variable outside of this question) to determine if an entry has been made into the object. Should I just use if(object[prop]), because if the property doesn't exist, it will return undefined? Is using the in operator just as fast? The only pitfall caused by changing to check the value is if the value if null, 0, -0, false, or NaN, it will return false when I want a falsy value, is there anything else I should watch out for?

  • The value could also be `undefined`. If you're sure that, if it'll exist, it'll be truthy, feel free to use `if(object[prop])` – CertainPerformance Mar 30 '20 at 22:42
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty – Phil Mar 30 '20 at 22:43
  • @Phil Oh, I totally forgot about that, is there any difference between the `in` operator and `hasOwnProperty()`? –  Mar 30 '20 at 22:44
  • @Red yes http://adripofjavascript.com/blog/drips/the-uses-of-in-vs-hasownproperty.html – Phil Mar 30 '20 at 22:44
  • 1
    Okay, immediate I found the prototype chain difference –  Mar 30 '20 at 22:45
  • @Phil It appears hasOwn... is exactly what I need, I tried this and `in` failed `let test = { [[1,2,3]]:5 } test.hasOwnProperty([1,2,3])` –  Mar 30 '20 at 22:47
  • Well, you've got some implicit array-to-string conversion going on there which is rarely a good thing – Phil Mar 30 '20 at 22:49

0 Answers0