Let's assume that we want to display the number of comments on our website differentiating between singular or plural:
javascript// Defining random comments let comments = ['first comment', 'your blog is nice', 'nice colors']; // Displaying the word depending on singular or plural let res = comments.length === 1 ? `${comments.length} comment` : `${comments.length} comments`; console.log(res); // 3 comments
We are repeating ourselves a bit.
Let's improve the solution:
javascript// Defining random comments let comments = ['first comment', 'your blog is nice', 'nice colors']; // Displaying the word depending on singular or plural let res = `${comments.length} comment${comments.length === 1 ? '' : 's'}`; console.log(res); // 3 comments
Could we do it another way?
Let's do it using an object:
javascript// Defining random comments let comments = ['first comment', 'your blog is nice', 'nice colors']; // Displaying the word depending on singular or plural let res = `${comments.length} comment${{1: ''}[comments.length] || 's'}`; // 3 comments
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.