Truthy and Falsy Assignment

Truthy

A truthy value is a value that is considered true when encountered in a boolean context. All values are truthy unless they are defined as falsey (.i.e except false, 0, -0, 0n, NaN, undefined)

Example:

let tool = 'marker';

let writingUtensil = tool || 'pen';

console.log(`The ${writingUtensil} is mighter than the sword.`);

// Output: The marker is mighter than the sword.

Falsey

A falsey value is a value that is considered false when encountered in a boolean context.

Example:

let username = '';
let defaultName;

if (username) {
    defaultName = username;
} else {
    defaultName = 'Stranger';
}

console.log(defaultName);

// Output: Stranger

Combining logical operators with Truthy and Falsey concept

Example:

let username = '';
let defaultName = username || 'Stranger';

console.log(defaultName);

// Output: Stranger

Because || or statements check the left-hand condition first, the variable defaultName will be assigned the actual value of username if it is truthy, and it will be assigned the value of 'Stranger' if username is falsy. This concept is also referred to as short-circuit evaluation.

Last updated