Truthy and Falsy Values¶
The rendering system often performs automatic type conversions, especially when evaluating conditional expressions. For instance, a string with the value "0" is considered truthy, whereas the numeric value 0 is evaluated as falsy. In a boolean context, values such as null, undefined, false, 0, or an empty string are treated as falsy and will evaluate to false, regardless of their original data type. Recognizing these implicit conversions is essential to prevent logical errors and ensure consistent and reliable application behavior.
Types of Evaluation¶
Truthy
- Non-zero Numbers: Any number that isn't zero.
- Non-empty Strings: Any string that isn’t empty or only whitespace.
- Non-empty Arrays: Arrays containing one or more items.
- Non-empty Dictionaries: Dictionaries with one or more key-value pairs.
- Boolean
true: Explicitly the boolean value true. - Non-blank Objects: Objects which are not
nil,empty, orblank.
Falsey
- The Number Zero: The integer 0.
- Empty Strings: Strings that are empty or contain only whitespace.
- Empty Arrays: Arrays with no items.
- Empty Dictionaries: Dictionaries with no key-value pairs.
- Boolean
false: Explicitly the boolean value false. - Nil Values: A value representing null or absence (
nil). - Blank Values: Values representing "nothing".
Use Cases¶
Non-zero Number¶
Output:Non-empty String¶
Output:Non-empty Array¶
{% assign items = "item1, item2, item3" | split: ", " %}
{% if items %}
Array length > 0
{% endif %}
Non-empty Dictionary¶
{% assign user = {"name": "John Doe", "age": 30} %}
{% if user %}
Dictionary length > 0.
{% endif %}
Boolean true¶
Output:
Zero Number¶
Output:Empty String¶
Output:Empty Array¶
{% assign items = "" | split: ", " %}
{% if items %}
Array is not empty
{% else %}
Array is empty
{% endif %}
Empty Dictionary¶
{% assign user = {} %}
{% if user %}
Dictionary is not empty
{% else %}
Dictionary is empty
{% endif %}
Boolean false¶
{% assign condition = false %}
{% if condition %}
Boolean is true
{% else %}
Boolean is false
{% endif %}
Nil Value¶
Output:Blank Value¶
{% assign value = blank %}
{% if value %}
Blank value is true
{% else %}
Blank value is false
{% endif %}
Default Operator¶
Using the default operator allows for elegant handling of false value checks by providing a fallback value when the original value is considered falsy, such as null, undefined, false, or 0. This simplifies code by ensuring that variables always have a valid value, reducing the need for verbose conditional statements and improving readability.
Example:
Output: