Hidden power of || and &&
Nick K
Posted on May 24, 2021
TLDR: Logical operators actually return one of the operands, so you can refactor code using this feature.
Usually, you may see ||
and &&
logical operators in if cases.
if (case1 || case2) {
doSomething()
}
So you may expect that ||
and &&
returns a boolean value, but it is only correct if values on both sides of these operators are boolean as well.
Actually, these operators return one of their arguments. E.g. if they were functions they would be implemented like this.
function or(a, b) {
if (a) {
return a
}
return b
}
function and(a, b) {
if (a) {
return b
}
return a
}
It may sound and look a bit confusing, but letβs dive into examples.
let obj = { prop: 1 }
// boring part
true || false // -> true
false || true // -> true
true && false // -> false
false && true // -> false
// interesting part
obj || false // -> { prop: 1 }
false || obj // -> { prop: 1 }
// more interesting part
true && obj // -> { prop: 1 }
obj && true // -> true
true || obj // -> true
obj || true // -> { prop: 1 }
Ok, how do we use it?
Using the ||
operator you can set default values.
const title = props.customTitle || 'Default title'
// Same to
let title = 'Default title'
if (props.customTitle) {
title = props.customTitle
}
Using the &&
operator we can check for property presence in an object.
let name = response && response.data && response.data.name
// Same to
let name;
if (response) {
if (response.data) {
if (response.data.name) {
name = response.data.name
}
}
}
So if response
or response.data
is undefined
or null
this assignment wonβt throw any error.
Combining ||
and &&
we can get a nice construction, which checks for properties and can set a default value.
let name = response && response.data && response.data.name || 'UNKNOWN'
Btw in newer versions of TypeScript, you can use a nullish coalescing, which simplifies &&
chains even more.
let name = response?.data?.name || 'UNKOWN'
UPD: Needed to mention this can be confused with lazy evaluation, but actually it is short-circuit evaluation. Thanks to my friend Ray
UPD2: as @lukeshiru mentioned in the comments, it is better to use nullish coalescing instead of &&
and ||
.
It's because values like 0 are treated like falsy, which can introduce bugs.
let beginnerCarDriver = {
// ...
yearsOfExperience: 0
}
let getDriveExperience = (driver) =>
driver && driver.yearsOfExperience || "Not a driver"
console.log(getDriveExperience(beginnerCarDriver)) // Not a driver
let getDriveExperience1 = (driver) =>
driver?.yearsOfExperience ?? "Not a driver"
console.log(getDriveExperience1(beginnerCarDriver)) // 0
Previous posts
- JS interview in 2 minutes / pure vs impure functions
- JS interview in 2 minutes / Closure
- JS interview in 2 minutes / Currying π₯
Btw, I will post more fun stuff here and on Twitter. Let's be friends π
Posted on May 24, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.