"Every value in JavaScript has an inherent boolean value. When that value is evaluated in the context of a boolean expression, the value will be transformed into that inherent boolean value."
The paragraph above is pretty dense with information. You should probably re-read it again.
Falsy values
A value is falsy if it converts to false
when evaluated in a boolean context. For example, an empty String ""
is falsy because, ""
evaluates to false
. You already know if...else statements, so let's use them to test the truthy-ness of ""
.
Hereβs the list of all of the falsy values:
- Boolean value
false
- number
0
- number negative
-0
- BigInt
0n
- empty string
""
-
null
type -
undefined
type -
NaN
(stands for Not a Number).
There are eight
falsy values in all of JavaScript! MDN
(at the time of writing this article)
Truthy values
A value is truthy if it converts to true
when evaluated in a boolean context. For example, the number 1
is truthy because, 1
evaluates to true
. Let's use an if...else statement again to test this out:
Here are some other examples of truthy values:
- true
- 42
- "pizza"
- "0"
- "null"
- "undefined"
- {}
- []
Simply put: if it's not in the list of falsy
values, then it's truthy
.
Be a little extra careful when working with the same element value but different element type. For example, 0
is a number while "0"
is a string. Similarly null
is different(falsy) from string "null"
(truthy) and undefined
(falsy) is different from string "undefined"
(truthy)
Comparison operator
Even though as mentioned above that []
is a truthy value but behaves differently when used in conjunction with a comparison operator like ==
, it evaluates to false. Likewise null
is a falsy, but when used with a ==
operator evaluates to true. Similary for undefined
and NaN
.
That's all there is to this topic. For some people truthy & falsy values might be not of a big deal, but knowing how they behave can save you some real time instead of just scratching your head.Let me know if you guys have any questions. Happy Learning..
Top comments (0)