Learning about Truthy and Falsy Values in JavaScript
In JavaScript, truthy and falsy values are concepts related to boolean evaluation. Every value in JavaScript has an inherent boolean "truthiness" or "falsiness," which means they can be implicitly evaluated to true or false in boolean contexts, such as in conditional statements or logical operations. What Are Truthy Values? Truthy values are values that are evaluated to be true when used in a Boolean context. Simply put, any value that is not explicitly falsy is considered truthy. These are some truthy values Non-zero numbers: 42, -1, 3.14 Non-empty strings: "hello", "0", " " Objects and arrays: {}, [] Functions: function() {} Dates: new Date() Symbols: Symbol() BigInt values other than 0n: 10n if ( 42 ) console . log ( " This is truthy! " ); if ( " hello " ) console . log ( " Non-empty strings are truthy! " ); if ({}) console . log ( " Objects are truthy! " ); Output This is truthy ! Non - empty strings are truthy ! Objects are truthy ! What Are Falsy Values? Falsy values are values that evaluate to false when used in a Boolean. JavaScript has a fixed list of falsy values false 0 (and -0) 0n (BigInt zero) "" (empty string) null undefined NaN document.all (used for backward compatibility) if (0) console.log("This won't run because 0 is falsy."); if ("") console.log("This won't run because an empty string is falsy."); if (null) console.log("This won't run because null is falsy."); Truthy vs. Falsy Evaluation in JavaScript Whenever JavaScript evaluates an expression in a Boolean (e.g., in an if statement, a logical operator, or a loop condition), it implicitly converts the value into true or false based on whether it is truthy or falsy. With if Statement let s = " JavaScript " ; if ( s ) { console . log ( " Truthy! " ); } else { console . log ( " Falsy! " ); } Output Truthy ! Logical Operators with Truthy and Falsy Logical operators like && (AND) and || (OR) work with truthy and falsy values && (AND): Returns the first falsy operand or the last operand if all are tr