Js Booleans in JavaScript
? JavaScript Booleans
What is a Boolean?
A Boolean represents a logical entity and can have two values:
truefalse
Creating Boolean Values
let isActive = true;let isLoggedIn = false;Boolean in Expressions
Results from comparisons or logical operations.
console.log(5 > 3); // trueconsole.log(10 === "10"); // falseBoolean Conversion (Truthy and Falsy)
Values convert to Boolean automatically in conditions:
| Falsy Values | All Other Values Are Truthy |
|---|---|
false | "hello" (non-empty string) |
0 | 42 |
"" (empty string) | {} (object) |
null | [] (array) |
undefined | function() {} |
NaN | Any non-zero number |
Example:
if ("") { console.log("This won't run"); // Because "" is falsy}if ("hello") { console.log("This will run"); // Because non-empty string is truthy}Boolean Object vs Boolean Primitive
Avoid using
new Boolean(). It creates an object, which is always truthy, even if false is stored inside.
const b1 = new Boolean(false);console.log(b1); // [Boolean: false]if (b1) { console.log("Runs"); // This runs, because objects are truthy!}Use boolean primitives (true or false) instead.
Logical Operators with Booleans
&&(AND)||(OR)!(NOT)
console.log(true && false); // falseconsole.log(true || false); // trueconsole.log(!true); // falseWant examples on truthy/falsy in conditions or logical operator tricks?