Boolean in JavaScript
🧠 What is a Boolean?
A Boolean in JavaScript is a data type that can only have one of two values: true or false. These values are commonly used to control flow, make decisions, and perform logic in programs.
>>“Boolean logic is the heart of decision-making in code.” 💡
📌 Declaring Boolean Values
You can assign a boolean directly using true or false literals:
Boolean Variables
let isOnline = true;
let isLoggedIn = false;
console.log(isOnline); // true
console.log(isLoggedIn); // false🔁 Boolean from Comparisons
Most commonly, booleans are the result of comparison expressions:
Boolean from Comparison
let age = 20;
let isAdult = age >= 18; // true
console.log(isAdult);Note
💡 Comparison operators always return a Boolean value.
🧪 Boolean Type Conversion
JavaScript automatically converts values to true or false when needed, such as in if statements.
Truthy & Falsy Example
if ("hello") {
console.log("This is truthy");
}
if (0) {
console.log("This won't run");
}⚖️ Truthy vs Falsy
Some values are treated as false (falsy), while everything else is treated as true (truthy).
| Falsy Values | Explanation |
|---|---|
| false | Literal false |
| 0 | Zero |
| "" | Empty string |
| null | Null value |
| undefined | Undefined value |
| NaN | Not-a-Number |
Note
✅ Any value not in this list is considered truthy.
💡 Boolean Function
You can explicitly convert a value to Boolean using the Boolean() function or the double NOT operator !!.
Boolean Conversion
Boolean("hello"); // true
Boolean(""); // false
Boolean(0); // false
Boolean(123); // true
!!"hello"; // true
!!""; // false🧠 Use Cases of Boolean
- 🔁 Control conditional logic with if/else
- 🎯 Track binary states like isOpen, isComplete
- ✅ Validate inputs or conditions
- ⚙️ Loop control and break conditions
📚 Resources
🧾 Summary
- ✅ Booleans are true or false
- ✅ Returned from comparisons and logical operations
- ✅ Type coercion happens automatically in conditionals
- ✅ Falsy values include 0, "", null, undefined, NaN, and false
>>“Booleans are the switches of logic — flip wisely.” 🔀