One of the small hurdles we face while writing javascript code is the dreaded
Uncaught TypeError: Cannot read property 'foobar' of undefined . Listed below are two common methods which i use to overcome this error.

&&

const animal = {
    dog: null,
    cat:{
        type: 'siamese'
    },
    bird:{
        type:'parrot'
    },
}

const hasDog = animal.dog && animal.dog.type // return null
const hasCat = animal.cat && animal.cat.type // return 'siamese'

The first expression will only be used if it's a falsy value otherwise it would return the second expression. In the case above,  for hasDog , animal.dog  returns null as it is a falsy value.

Otherwise , for hasCat , animal.cat exist and it moves on to return the value of second expression animal.cat.type

Expressions will cease to move forward as soon as it reaches its first falsy value.


Maybe Monad

const favAlbum = (favourites.listen || {}).album //null

This method works by checking if the first value is falsy. If so, it will attempt to access the next property on an empty object.

This method takes advantage of the fact that an Object is never null and the value of an undefined property accessed is null.

You can read more about the 'Maybe Monad' method here on Oliver Steele's Blog.