twitch
Streaming on Twitch twice a week

Switching between functions with a ternary operator

JavaScript

If we use a condition to choose which of two functions to call with the same parameters, we can use a ternary operator to remove some repetition.

// Regardless of which function we pick, we always pass 'martini' to it.
if (isJamesBond) {
  shake('martini')
} else {
  stir('martini')
}

// Because the parameter stays the same, we can select the function with a
// ternary operator instead.
(isJamesBond ? shake : stir)('martini')

More fire tips

Splitting arrays into chunks

By combining map and slice, we can write a helper function to split large arrays into many similarly sized blocks. This is useful for features like pagination.

JavaScript
Read fire tip

Read all fire tips →