I am currently available for freelance/contract work. Book a meeting so we can talk about your project.

Removing duplication with ternary operators

Posted on

The ternary operator can help us reduce duplication. We can even place it inside of a function call if we’d switch the parameters based on a condition.

Watch out for readability: the shortest version isn’t always the best option.

// we want to wish people a happy weekend/workweek depending on the day
const isWeekend = day === "Saturday" || day === "Sunday"
 
// we can call `console.log` with the respective message like this
isWeekend ? console.log("Happy weekend!") : console.log("Happy workweek!")
 
// `console.log` happens in any case, so we can move the ternary inside it
console.log(isWeekend ? "Happy weekend!" : "Happy workweek!")
 
// we can extract the duplicate “Happy ” and “!” to only write them once
console.log(`Happy ${isWeekend ? "weekend" : "workweek"}!`)
 
// don’t go crazy and extract EVERY duplication; the code becomes shorter
// if we extract the duplicate “w”, but also much harder to read
console.log(`Happy w${isWeekend ? "eekend" : "orkweek"}!`)
// we want to wish people a happy weekend/workweek depending on the day
const isWeekend = day === "Saturday" || day === "Sunday"
 
// we can call `console.log` with the respective message like this
isWeekend ? console.log("Happy weekend!") : console.log("Happy workweek!")
 
// `console.log` happens in any case, so we can move the ternary inside it
console.log(isWeekend ? "Happy weekend!" : "Happy workweek!")
 
// we can extract the duplicate “Happy ” and “!” to only write them once
console.log(`Happy ${isWeekend ? "weekend" : "workweek"}!`)
 
// don’t go crazy and extract EVERY duplication; the code becomes shorter
// if we extract the duplicate “w”, but also much harder to read
console.log(`Happy w${isWeekend ? "eekend" : "orkweek"}!`)
Debug
none
Grid overlay