November 6, 2023
Understanding falsy values
false when encountered in a Boolean context. JS has a small, fixed number of falsy values:
NaN(Not a Number)
The nature of truthy values
- All objects (
) and non-empty strings
- All numbers (positive or negative) except
- The string
"false"(because it's non-empty)
Conditional statements and logical operations
Conditionals with falsy values
When a falsy value is used in a conditional, the condition is evaluated as
Conditionals with truthy values
Any truthy value in a conditional statement will cause the condition to evaluate as
Logical operators and falsy values
Logical operators (
!) also rely on truthy and falsy values:
||(OR) returns the first truthy value it encounters or the last value if all are falsy.
&&(AND) returns the first falsy value it encounters or the last value if all are truthy.
!(NOT) converts the value to its Boolean opposite.
Strict vs. loose equality
When using equality operators, it's important to understand how they interact with truthy and falsy values.
Type coercion in arithmetic and logical operations
Function and arrow function behavior
Functions and arrow functions with implicit return values can be influenced by truthy and falsy evaluations.
Short-circuit evaluation in expressions
Coercion to boolean
You can explicitly coerce any value to a boolean using the Boolean function or a double NOT operator
Understanding truthy and falsy values is critical in JS to write concise and effective code, for instance, when setting default values.
It also helps in simplifying conditions and checks within the code:
The Boolean object vs. primitive boolean values
Boolean object can be a source of confusion when dealing with truthy and falsy values.
Falsy values in array methods
Array methods like
reduce react to falsy values in predictable ways.
Advanced examples and edge cases
When working with default parameters, destructuring, and complex logical conditions, truthy and falsy values can lead to unexpected behaviors.
Testing for truthy and falsy
Methods to test for truthy and falsy values can help in validating arrays and other structures.
How to Truncate Date in MySQL