Layer 1Navigate back to the homepage

Javascript tip - hasOwnProperty

Andras Helyes
May 5th, 2018 · 1 min read

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}
4
5if (cart && cart.numberOfItems) {
6 // do something if numberOfItems property exists
7}

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}
4
5if (cart && cart.numberOfItems) {
6 console.log('This will not execute as cart.numberOfItems is false');
7}
8// no output
9
10if (cart && cart.hasOwnProperty('numberOfItems')) {
11 console.log(`There are ${cart.numberOfItems} items in your cart`);
12}
13// There are 0 items in your cart
14
15cart.numberOfItems = 1;
16
17if (cart && cart.numberOfItems) {
18 console.log('This will execute as cart.numberOfItems is true');
19}
20// This will execute as cart.numberOfItems is true

More articles from CultOfNet

Hosting private repo on github pages

How to host private repo on github pages without pro account

March 5th, 2017 · 2 min read

There has to be a first...

This is going to be a beggining of a beautiful friendship

October 29th, 2016 · 1 min read
© 2019 CultOfNet
Link to $https://github.com/helyesLink to $https://www.linkedin.com/in/andras-helyes