Truthy and Falsy

  • These are used on how non-boolean data types, like strings or numbers, are evaluated when checked inside a condition.

  • Sometimes you'll want to check if a variable exists and you won't necessarily want it to equal to a specific value.

Example:

let myVariable = 'I Exist';

if (myVariable) {
    console.log(myVaribale);
} else {
    console.log('The variable does not exist.')
}

// Output: I Exist

In the above example the if statement block runs because it has a truthy value; even though the value of myVaribale is not explicitly the value true.

When used in a boolean or conditional context, it evaluates to true because it has been assigned a non-falsy value.

The list of falsy values includes:

  1. 0

  2. Empty strings like "" or ''

  3. undefined which represent when a declared variable lack a value

  4. NaN, or Not a Number

Example:

let numberOfApples = 0;

if (numberOfApples) {
    console.log('Let us eat apples!');
} else {
    console.log('No apples left!')
}

// Output: No apples left!

In the above example the if condition evaluates to false because numberOfApples has a falsy value which is 0.

Example:

let wordCount = 50;

if (wordCount) {
  console.log("Great! You've started your work!");
} else {
  console.log('Better get to work!');
}

// Output: Great! You've started your work!

let favoritePhrase = '';

if (favoritePhrase) {
  console.log("This string doesn't seem to be empty.");
} else {
  console.log('This string is definitely empty.');
}

// Output: This string is definitely empty.

Last updated