Composing functions to run in sequence
We can chain many functions together into a single function. That new function takes one input and runs it through its individual functions one by one.
Read full articleThe ternary operator can reduce the lines of code we need to switch behavior based on a condition. Its usefulness isn’t limited to variable assignment either. It also lets us reduce the code needed to switch between two near identical function calls.
// Regardless of which function we pick, we always pass "martini" to it.
if (isJamesBond) {
shake("martini")
} else {
stir("martini")
}
// We can use a ternary operator instead of the if-else branch here.
isJamesBond ? shake("martini") : stir("martini")
// Because the parameter stays the same, we can select the function with a
// ternary operator instead.
(isJamesBond ? shake : stir)("martini")
// Regardless of which function we pick, we always pass "martini" to it.
if (isJamesBond) {
shake("martini")
} else {
stir("martini")
}
// We can use a ternary operator instead of the if-else branch here.
isJamesBond ? shake("martini") : stir("martini")
// Because the parameter stays the same, we can select the function with a
// ternary operator instead.
(isJamesBond ? shake : stir)("martini")
// Regardless of which function we pick, we always pass "martini" to it.
if (isJamesBond) {
shake("martini")
} else {
stir("martini")
}
// We can use a ternary operator instead of the if-else branch here.
isJamesBond ? shake("martini") : stir("martini")
// Because the parameter stays the same, we can select the function with a
// ternary operator instead.
(isJamesBond ? shake : stir)("martini")
// Regardless of which function we pick, we always pass "martini" to it.
if (isJamesBond) {
shake("martini")
} else {
stir("martini")
}
// We can use a ternary operator instead of the if-else branch here.
isJamesBond ? shake("martini") : stir("martini")
// Because the parameter stays the same, we can select the function with a
// ternary operator instead.
(isJamesBond ? shake : stir)("martini")
We can chain many functions together into a single function. That new function takes one input and runs it through its individual functions one by one.
Read full articleWe can create a helper function that makes functions return their Boolean opposite. This can be useful in the shorthand syntax for array methods.
Read full articleAs soon as a concatenation of conditions is clear, JavaScript stops the evaluation. It does not do work that does not change the result.
Read full articleSince array methods like filter and map return an array themselves, we can chain them one after the other.
Read full articleWith JavaScript’s built-in formatter for relative timestamps, we can build strings like “2 months from now” without third party libraries.
Read full articleWe can skip the return keyword if arrow functions immediately return a value. If that value is an object, we need to also wrap it in parentheses.
Read full article