superzamp
superzamp

Reputation: 511

Checking object property of potentially undefined

Say I have the following object

var book = {
    title: "Javascript Secrets",
    author: "Dummy Mc Dumm",
}

I want to test book.collection.name, knowing that book.collection can be undefined.

How can I avoid nesting tests like this ?

if(book.collection){
    if(book.collection.name == "foo")
        // success
}

Withouth raising a TypeError: Cannot read property 'name' of undefined

Upvotes: 0

Views: 40

Answers (1)

hansmaad
hansmaad

Reputation: 18905

The logical AND operator (&&) is short-circuiting and will skip the second expression if the first is false

if(book.collection && book.collection.name == "foo"){
    // success
}

See Logical Operators.

Upvotes: 3

Related Questions