Short-circuit evaluation is a strategy most programming languages (including JavaScript) use to avoid unnecessary work. For example, say we had a conditional like this:
Let's say itIsFriday is false. Because JavaScript short-circuits evaluation, it wouldn't bother checking the value of itIsRaining—it knows that either way the condition is false and we won't print the invitation to board game night.
We can use this to our advantage. For example, say we have a check like this:
What happens if 'Becky' isn't in our friends object? Since friends['Becky'] is undefined, when we try to call isFreeThisFriday we'll get a TypeError.
Instead, we could first confirm that Becky and I are still on good terms:
This way, if 'Becky' isn't in friends, JavaScript will ignore the rest of the conditional and avoid throwing the TypeError.
This is all hypothetical, of course. It's not like things with Becky are weird or anything. We're totally cool. She's still in my friends object for sure and I hope I'm still in hers and Becky if you're reading this I just want you to know you're still in my friends object.
Interview coming up?
Get the free 7-day email crash course. You'll learn how to think algorithmically, so you can break down tricky coding interview questions.
No prior computer science training necessary—we'll get you up to speed quickly, skipping all the overly academic stuff.
No spam. One-click unsubscribe whenever.
You're in! Head over to your email inbox right now to read day one!