...
/Tip 19: Maximize Efficiency with Short Circuiting
Tip 19: Maximize Efficiency with Short Circuiting
In this tip, you’ll learn to reduce conditionals to the smallest possible expression with short circuiting.
Short circuiting
You’ve been simplifying conditional expressions a lot in the last few tips. But there’s one more level of simplification you can use: short circuiting.
As the name implies, the goal of short circuiting is to bypass information checks by placing the most relevant information first.
Example 1: Cleaning ternary code using short circuiting
Consider the following ternary, which would fit in well with the discussion from the previous chapter.
const image = {path: 'foo/bar.png',};function getIconPath(icon) {const path = icon.path ? icon.path : 'uploads/default.png';return `https://assets.foo.com/${path}`;}console.log(getIconPath(image));
The goal here is fairly clear. If an icon has a truthy path (in this case, that
means it’s defined and isn’t an empty string), then you want to use the path.
If it’s falsy, undefined, or ''
, then you want to use the default.
const icon = {path: 'acme/bar.png'}function getIconPath(icon) {const path = icon.path ? icon.path : 'uploads/default.png';return `https://assets.foo.com/${path}`;}console.log(getIconPath(icon));
Did you see any clues that suggest you can clean up this code a bit?
You probably noticed that you’re writing the information check, icon.path
, twice.
Let’s assume that data is always going to be valid, which means there’s no
difference between the information we’re checking and the information we
want. If it’s truthy, we’re going to use it.
Before updating the code, take a moment to think about how logical ...