1.0.1 • Published 7 years ago

@temowemo/get-safe v1.0.1

Weekly downloads
-
License
ISC
Repository
github
Last release
7 years ago

get-safe

Summary:

Avoid "Cannot read property 'name' of undefined" in JavaScript.

Inspired by this article: How to avoid "Cannot read property 'name' of undefined" in JavaScript

Usage:

Without "get-safe"

const obj = {
    a: {
        b: {
            c: {}
        }
    }
}


console.log(obj.a.b.c.d.e) // TypeError: Cannot read property 'e' of undefined

With "get-safe"

const getSafe = require("@temowemo/get-safe")

const obj = {
    a: {
        b: {
            c: "Hey!"
        }
    }
}

// If the property doesn't exist, you get "undefined"
console.log( getSafe(() => obj.a.b.c.d.e) ) // undefined

// If the property DOES exist, you get that property value
console.log( getSafe(() => obj.a.b.c) ) // "Hey!"

Installation:

With NPM:

npm install @temowemo/get-safe --save

Or you can look inside index.js and copy the code.

That's it! :grin: