This content originally appeared on DEV Community and was authored by Nikita Kozlov
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
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 ?
This content originally appeared on DEV Community and was authored by Nikita Kozlov
Nikita Kozlov | Sciencx (2021-05-24T08:36:52+00:00) Hidden power of || and &&. Retrieved from https://www.scien.cx/2021/05/24/hidden-power-of-and/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.