Object dot notation
Dot notation should not be used for property null / exists checking on objects due to javascript’s weird falseness.
Consider
1const cart = {2 numberOfItems: 0,3}45if (cart && cart.numberOfItems) {6 // do something if numberOfItems property exists7}
This particular if clause will execute only if cart
exists and cart.numberOfItems
is not falsy.
Given the cart object above, it’ll be falsy, even though numberOfItems
exists.
The hasOwnProperty function
foo.hasOwnProperty(‘bar’) returns true if foo
object has bar
property as it’s own property, not inherited.
1const cart = {2 numberOfItems: 0,3}45if (cart && cart.numberOfItems) {6 console.log('This will not execute as cart.numberOfItems is false');7}8// no output910if (cart && cart.hasOwnProperty('numberOfItems')) {11 console.log(`There are ${cart.numberOfItems} items in your cart`);12}13// There are 0 items in your cart1415cart.numberOfItems = 1;1617if (cart && cart.numberOfItems) {18 console.log('This will execute as cart.numberOfItems is true');19}20// This will execute as cart.numberOfItems is true