Prevent Object Retrieval TypeError with &&

Samantha Ming
DailyJS
Published in
3 min readMar 11, 2019

--

Code Tidbit by SamanthaMing.com

When you retrieve an object value that’s undefined, it will crash due to a TypeError! So make sure you do an initial check with an if statement. Better yet, refactor this using && 👍

Using && in this way is sometimes called the Guard Operator because the 1st expression safeguards the 2nd expression. In other words, only if the 1st expression is truthy, then will the 2nd expression be evaluated.

const forest = {}forest.tree // undefined
forest.tree.seed // TypeError 😱
// This will prevent the TypeError but...
if(forest.tree) {
forest.tree.seed
}
// ✅Much better using &&
forest.tree && forest.tree.seed // undefined

Understanding the && Operator

I always thought the && was just used for boolean checks like this:

if(a && b) {
// do something
}

I never thought you can use && to evaluate to something or produce some sort of value. So when I first learned of this Guard Operator, I was super confused. So don't worry if you are too. It will take some time to understand this. The resource that helped me finally understand this is Kyle Simpson's "You Don't Know JavaScript" book.

--

--

Samantha Ming
DailyJS

Frontend Developer sharing weekly JS, HTML, CSS code tidbits🔥 Discover them all on samanthaming.com 💛