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,
        type: 'siamese'

const hasDog = && // return null
const hasCat = && // 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 ,  returns null as it is a falsy value.

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

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.