In our starter files, open the index.html page from this lessons folder:
06.Loops-and-conditionals > 09.Truthy-falsy
In many examples and JavaScript coding in general, we check if a value is true or false. If true, do something, if false, do something else.
But it is not just the Boolean values of true and false which we can use. As we have seen previously, other values can also evaluate to be true or false. Such as 0 evaluating to be false, and 1 to be true.
There are also many more examples, such as a string of text is true and an empty string is false. This is referred to as truthy and falsy. Truthy is when a value is evaluated to be true, such as our string of text. And falsy is when a value evaluates to false, such as our empty string, or our number zero.
Let’s go into our starter project and look at some examples. If statements will run for not only a Boolean value of true, but also a truthy value:
if () {
console.log('truthy');
} else {
console.log('falsy');
}
Give this a try, pass to the if
statement the values of 0
, 1
, "anystring"
, and ""
. You will see the following results:
Value | Result |
---|---|
0 | falsy |
1 | truthy |
"anystring" | truthy |
"" | falsy |
The coercion we talked about is happening behind the scenes. Values are being converted to have a Boolean value, so we can determine if things like if
statements are to run or not.
Falsy values, as you may expect, are generally empty values such as:
We can consider most other values to be truthy, such as:
if (Array) {}
if (Object) {}
if (Function) {}
Or, when we write them literally:
if (['1'])
if ({ name: 'chris' })
Coercion, combined with understanding how values are converted to be truthy and falsy is really useful to understand. Since it can really help you out to both avoid problems in the future, and also to help you debug issues too.