In this section, we will learn what the ToBoolean operation is and how it works in JavaScript.
What is ToBoolean Operation in JavaScript?
In places where we need a value of type `Boolean` but the involved value is a non-Boolean type, the JavaScript engine will use the `ToBoolean` operation to coerce the target value into a `Boolean` type.
For example, in the parentheses of the `if` condition, we need either a value `false` or `true` or an expression that results in these values. So if we put a value of type String or a value of type Number, then the engine will invoke the `ToBoolean` operation on the target value.
The work of the operation `ToBoolean` is simple. Basically in the operation, the execution engine will check a table that is called Falsy-Table. If the target value was one of the items in that table, the execution engine will replace the target value with the value `false`. But if the target value was not in the `Falsy-Table` then it will be replaced with the value `true`.
List of Primitive Values and the Result of Applying ToBoolean Operation
Here’s the Falsy-table:
Falsy-Table |
“” |
0, -0 |
null |
NaN |
false |
undefined |
We call values in the table above a falsy-table, because if the execution engine sees any of these values in an operation where a boolean value was needed, it will automatically replace the value with the boolean value `false`.
Now any value that is not in this table will be considered as a `true` value.
Example: converting Number to Boolean in JavaScript
if (10){ console.log("The body is executed"); }
Output:
The body is executed
Take a look at the condition of the `if` statement:
if (10){}
Is the value 10 in the Falsy-Table? No!
So because this value is not in the table, then the result is true and the body of this `if` statement runs.
From the execution engine’s perspective: the value in the condition is a non-Boolean value. So the engine will run the `ToBoolean` operation on that value and check the table then. Now because in the table there’s no value `10`, the engine will replace this value with the value `true`.
Example: converting String to Boolean in JavaScript
const empty = ""; if (empty){ console.log("The body is executed"); }
Output:
Here, the condition of the `if` statement is an empty string. Basically, it’s a non-Boolean value. So the execution engine will run the `ToBoolean` operation and look up into the `Falsy-Table`. Now, because this empty string is one of the items on the table, the engine will replace the value with the value `false`.
The final result of the condition in the `if` statement is `false` and so its body is skipped.
Example: converting Object to Boolean in JavaScript
const obj = {} if (obj){ console.log("An empty object is equal to true!"); }else{ console.log("An empty object is equal to false!"); }
Output:
An empty object is equal to true