Truthy and falsy values in JavaScript

Introduction Link to heading

In JavaScript, truthy and false values are a fundamental concept for understanding how conditions are evaluated in code.

What are truthy and falsy values? Link to heading

  • Truthy: These are values that are considered “true” in a Boolean context.
  • Falsy: These are values that are considered “false” in a Boolean context.

List of falsy values Link to heading

  • false
  • 0 (zero)
  • -0 (negative zero)
  • NaN (Not a Number)
  • null
  • undefined
  • The empty string ""

##List of truthy values

  • Any value that is not falsy

Example Link to heading


if ("") {
    console.log("Empty string is truthy");
} else {
    console.log("Empty string is false");
}

// Empty string is falsy

Boolean() function Link to heading

  • The Boolean() function is used to convert a value to a boolean value.
  • If the value is truthy, the function returns true.
  • If the value is false, the function returns false.

Example Link to heading

console.log(Boolean(0)); // false
console.log(Boolean("a")); // true

Recommendations Link to heading

  • It is important to understand the difference between truthy and false values to write accurate conditions in the code.
  • The Boolean() function can be used to check if a value is truthy or false.

Keep learning about truthy and falsy values to write more robust JavaScript code!

<< Coercion in JavaScript Operators in JavaScript >>