Home / javascript / What are truthy and falsy values in JavaScript?

What are truthy and falsy values in JavaScript?

In JavaScript, a value is considered “truthy” if it evaluates to true when evaluated in a boolean context. Conversely, a value is considered “falsy” if it evaluates to false when evaluated in a boolean context.

Here’s a breakdown of truthy and falsy values in JavaScript:

Truthy values:

  1. Non-empty strings: Any string with at least one character.
  2. Non-zero numbers: Any number except 0, including negative numbers and decimals.
  3. true: The boolean value true.
  4. Objects: Any non-null object or array, including empty objects and arrays.
  5. Functions: Any non-null function.

Falsy values:

  1. Empty strings: A string with no characters, represented as '' or "".
  2. 0: The number zero.
  3. NaN: Not-a-Number, a special value resulting from invalid operations.
  4. false: The boolean value false.
  5. null: The absence of any value or object.
  6. undefined: A variable that has not been assigned a value, or a function with no return value.
  7. Document.all: A legacy property that evaluates to false in modern browsers.

Here’s a simple illustration:

if ('hello') {
    console.log('Truthy'); // This will be printed
}

if (0) {
    console.log('Falsy');
} else {
    console.log('Falsy'); // This will be printed
}

Understanding truthy and falsy values is important in JavaScript, especially when working with conditional statements or type coercion.

About admin

Check Also

What are the differences between var, let and const in JavaScript?

var, let, and const are all used for variable declaration in JavaScript, but they have …

Leave a Reply

Your email address will not be published. Required fields are marked *