When we use most of the programming languages or scripting languages we have some values that isn't a boolean value but it works as so.
We mostly call it truthy & falsy values.
Truthy Values
Personally, I like to think of truthy values as a variable that has an actual value in them.
Sort of messy? Think of it like that:
- A value that isn't empty is a valuable value, but when it's empty it's not.
Let's see some examples
We'll use the !!
keyword to turn the value into a boolean value to check is the output.
String
console.log(!!"Hello"); // true
let text = "Hi there";
console.log(!!text); // true
Number
console.log(!!18); // true
let num = 88;
console.log(!!num);
Other
Any object ({}
) or Array ([]
) are truthy values, even if they were empty!!
So be aware if you want to use an object or array for storing, you have to get the values inside of the array or object.
Falsy Values
A falsy value is the opposite of the truthy values.
String
console.log(!!""); // false
Number
console.log(!!0); // false
console.log(!!NaN); // false
To know more about NaN check out the article about numbers
Other
The null
object is also a falsy value.
console.log(!!null); // false
Use Cases
There are of cause some amazing use cases of knowing this, you can stop a process if the value wasn't a number like so, as if you turned a text into a number it turns into NaN
and it's a falsy value.
if (inputValue) {
... // Actions
}