![]() |
VOOZH | about |
In JavaScript, truthy and falsy values are concepts related to boolean evaluation. Every value in JavaScript has an inherent boolean "truthiness" or "falsiness," which means they can be implicitly evaluated to true or false in boolean contexts, such as in conditional statements or logical operations.
Truthy values are values that are evaluated to be true when used in a Boolean context. Simply put, any value that is not explicitly falsy is considered truthy.
These are some truthy values
This is truthy! Non-empty strings are truthy! Objects are truthy!
Falsy values are values that evaluate to false when used in a Boolean. JavaScript has a fixed list of falsy values
Whenever JavaScript evaluates an expression in a Boolean (e.g., in an if statement, a logical operator, or a loop condition), it implicitly converts the value into true or false based on whether it is truthy or falsy.
Truthy!
Logical operators like && (AND) and || (OR) work with truthy and falsy values
JavaScript Hello! null
You can explicitly check whether a value is truthy or falsy using the Boolean() function or the double negation operator (!!).
true false true false true false
Truthy
0 is falsy, but -1, 3.14, and other numbers are truthy.
Truthy
Unlike Python, where empty containers are falsy, empty objects {} and arrays [] are truthy in JavaScript.
Empty arrays are truthy! Empty objects are truthy!
The || operator is commonly used to assign default values when a variable is falsy.
Guest
Truthy and falsy checks can be used to avoid errors when accessing object properties:
Truthy and falsy values allow concise conditions without explicit equality checks:
| Aspect | Truthy Values | Falsy Values |
|---|---|---|
| Definition | Values that evaluate to true in Boolean contexts. | Values that evaluate to false in Boolean contexts. |
| Examples | 42, "hello", {}, [], function() {} | false, 0, -0, "", null, undefined, NaN |
| Empty Structures | Empty objects {} and arrays [] are truthy. | Not applicable (empty structures are not falsy). |
| Strings | Non-empty strings (e.g., "hello", " ") are truthy. | Empty strings ("") are falsy. |
| Numbers | Non-zero numbers (e.g., 42, -3.14) are truthy. | Zero (0, -0) is falsy. |
| BigInt | Any non-zero BigInt value (e.g., 10n) is truthy. | Zero BigInt (0n) is falsy. |
| Usage in Logical Operators | Can short-circuit ` |