Borislav Hadzhiev
Thu Nov 04 2021·2 min read
Photo by Angelina Litvin
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'
.
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.
?
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:
if
blockelse
blockHere's the same example, but with a false
value.
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.
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.