今日已更新 287 条资讯 | 累计 20259 条内容
关于我们

Learning about Truthy and Falsy Values in JavaScript

Annapoorani Kadhiravan 2026年06月09日 02:46 5 次阅读 来源:Dev.to

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

本文内容来源于互联网,版权归原作者所有
查看原文