Convert a Boolean value to Yes/No in JavaScript

avatar

Borislav Hadzhiev

Last updated: Nov 4, 2021

banner

Photo from Unsplash

Convert a Boolean value to Yes/No #

To convert a boolean value to Yes/No, use a ternary operator and conditionally check if the boolean value is equal to true, if it is, return yes, otherwise return no, e.g. bool === true ? 'yes' : 'no'.

index.js
const bool = true; const str = bool === true ? 'Yes' : 'No'; console.log(str); // 👉️ "Yes"

We used a ternary operator which is very similar to an if/else statement.

The part before the question mark ? is a condition, just like a condition between the parentheses of an if statement.

If the condition gets evaluated to a truthy value, the value before the colon : gets returned, otherwise the value after the colon gets returned.

Truthy values in JavaScript are all values that are not falsy.

The falsy values are: false, null, undefined, 0, "" (empty string), NaN (not a number).

If the condition evaluates to any other value, the value before the colon gets returned from the ternary operator.

An easy way to think about it is:

  • the value before the colon is your if block
  • the value after the colon is your else block

Here's the same example, but with a false value.

index.js
const bool = false; const str = bool === true ? 'Yes' : 'No'; console.log(str); // 👉️ "No"

Because false is a falsy value, the ternary operator returned the value after the colon.

Here are some more examples of using a ternary operator.

index.js
const result1 = 100 > 1 ? 'yes' : 'no'; console.log(result1); // 👉️ 'yes' const result2 = 1 > 100 ? 'yes' : 'no'; console.log(result2); // 👉️ 'no'

In the first example, the condition evaluates to true, so the part before the colon gets returned from the ternary.

In the second example the condition evaluates to false, so the part after the colon gets returned.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.