Convert a Boolean value to Yes/No in JavaScript

avatar

Borislav Hadzhiev

Thu Nov 04 20212 min read

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 parenthesis 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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee