Falsy
May 20, 2023
In computer programming, Falsy is a term used to describe a value that is considered false when encountered in a boolean context. A boolean context is any situation or operation that involves the evaluation of a logical expression, such as a conditional statement, a loop or a logical operator. In a boolean context, a value can be either true or false, and any value that is not explicitly true is considered false.
Purpose
The purpose of Falsy values is to provide a simple and consistent way to test for the absence or invalidity of a value in a boolean context. This is particularly useful in programming languages that support dynamic typing, where the type of a variable can change at runtime, and where a value may not have a well-defined boolean interpretation.
For example, in JavaScript, a language that supports dynamic typing, the following values are considered Falsy:
false
null
undefined
0
-0
NaN
''
(empty string)
Any other value, including non-empty strings, objects, arrays, functions and even the boolean value true
, is considered truthy.
if (null) {
// this code will not execute
}
if ('') {
// this code will not execute
}
if ({}) {
// this code will execute
}
if ([]) {
// this code will execute
}
if (function() {}) {
// this code will execute
}
if (true) {
// this code will execute
}
Usage
The most common use case for Falsy values is in conditional statements, where a block of code is executed only if a certain condition is met. In such cases, a Falsy value can be used to test for the absence or invalidity of a value.
let value;
if (!value) {
console.log('value is falsy');
}
This code will log 'value is falsy'
if the variable value
has any of the Falsy values mentioned above. If value
has any other value, the expression !value
will evaluate to false
, and the code will not execute.
Another common use case for Falsy values is in default values for function parameters. In JavaScript, a function can have default values for its parameters, which are used if the function is called with fewer arguments than expected. A common pattern is to use Falsy values as default values, since they are guaranteed to be replaced with a real value if the caller provides one.
function greet(name = 'stranger') {
console.log(`Hello, ${name}!`);
}
greet(); // logs "Hello, stranger!"
greet('John'); // logs "Hello, John!"
greet(null); // logs "Hello, null!"
greet(undefined); // logs "Hello, stranger!"
In this example, the greet function has a default value of ‘stranger’ for its name parameter. This default value is used if the function is called with no arguments, or with the Falsy values null
or undefined
.