Switching between functions with a ternary operator

Posted on

The 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")
Debug
none
Grid overlay