Saturday, November 9, 2024

JavaScript Truthy and Falsy Values

In JavaScript, truthy and falsy values determine how a value is evaluated in a Boolean context, like in an if statement.

Falsy Values

A falsy value is a value that is considered false when evaluated in a Boolean context. JavaScript has exactly six falsy values:
  1. false - the Boolean false
  2. 0 - the number zero
  3. "" - an empty string (both '' and "")
  4. null - represents the absence of any value
  5. undefined - a variable that has been declared but not assigned a value
  6. NaN - "Not-a-Number," a result of an invalid number operation
These values are treated as false in Boolean contexts, like in conditional statements:

if (0) {
  console.log("This will not run");
}

Truthy Values

A truthy value is any value that is not falsy. This means all values other than the six falsy ones are truthy, such as:

  • Non-zero numbers (e.g., 1, -42)
  • Non-empty strings (e.g., "Hello", " ")
  • Objects and arrays (e.g., {}, [])
  • Functions

These values are treated as true in Boolean contexts:

if ("Hello") {
  console.log("This will run because 'Hello' is truthy");
}

Examples
  • console.log(Boolean(0));       // false
  • console.log(Boolean("Hello")); // true
  • console.log(Boolean(null));    // false
  • console.log(Boolean([]));      // true
In JavaScript, truthy and falsy values are often used to simplify conditional checks.

Summary of Truthy/Falsy Values:

Falsy values in JavaScript include:
  1. false
  2. 0
  3. -0
  4. "" (empty string)
  5. null
  6. undefined
  7. NaN
Truthy values include everything else (e.g., objects, arrays, non-zero numbers, non-empty strings).

More Examples

Negation operation

In JavaScript, the ! operator is used to negate a value, meaning it converts the operand into a boolean and then negates it. Here’s how it works for each operand:
  1. !null: null is considered falsy, so !null is true because negating a falsy value turns it into true.
  2. !undefined: undefined is also falsy, so !undefined is true.
  3. !"" (empty string): An empty string "" is falsy, so !"" is true.
  4. !0 (zero): The number 0 is falsy, so !0 is true.
  5. !NaN (Not-a-Number): NaN is falsy, so !NaN is true.
  6. !{} (empty object): An empty object {} is truthy (all objects are considered truthy in JavaScript), so !{} is false because negating a truthy value turns it into false.

No comments:

Post a Comment

Hot Topics