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:
- false - the Boolean false
- 0 - the number zero
- "" - an empty string (both '' and "")
- null - represents the absence of any value
- undefined - a variable that has been declared but not assigned a value
- 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:
- false
- 0
- -0
- "" (empty string)
- null
- undefined
- 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:
- !null: null is considered falsy, so !null is true because negating a falsy value turns it into true.
- !undefined: undefined is also falsy, so !undefined is true.
- !"" (empty string): An empty string "" is falsy, so !"" is true.
- !0 (zero): The number 0 is falsy, so !0 is true.
- !NaN (Not-a-Number): NaN is falsy, so !NaN is true.
- !{} (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