Dynamically Pluralize Like(s)

• 1 min read

I just wanted to share a snippet we use at ForkJoy for pluralizing the various “like” counters on the website. Every menu item has one of these counters and the text can read “no likes”, “1 like”, “2 likes”, etc. Originally we were using an if statement to do this until we realized it can be fit on one line instead.

var str;

// Prepend with "no" if 0 likes and add
// an "s" if number of likes is not 1
str = (item.likes || 'no') + ' like' + ((item.likes === 1) ? '' : 's');

// The way we first wrote it
if (item.likes === 0) {
  str = item.likes + 'likes'
} else if (item.likes === 1) {
  str = item.likes + 'like'
} else {
  str = 'no likes';
}

In the first snippet we take advantage of the fact that the word “like” only appears when there is only one. We also know that the word “no” only prepends the number when there aren’t any likes so we can get away with putting this all on one line without having it look messy.

If you enjoyed this tutorial, please consider sponsoring my work on GitHub 🤗

Be the first to cheers
Now look what you've done 🌋
Stop clicking and run for your life! 😱
Uh oh, I don't think the system can't handle it! 🔥
Stop it, you're too kind 😄
Thanks for the love! ❤️
Thanks, glad you enjoyed it! Care to share?
Hacker News Reddit

×

Recommended Posts ✍🏻

See All »
• 3 min read
✨ HTML Share Buttons
Read Post »
• 3 min read
🚅 Next Stop, Yaak
Read Post »
• 4 min read
💻 Wait for User to Stop Typing, in JavaScript
Read Post »