🔘 Boolean in JavaScript
🧠 What is a Boolean?
In JavaScript, a Boolean represents a logical value and can be either true or false. Booleans are often used in conditional statements to control the program flow.
✅ Boolean Literals
You can directly use the Boolean literals:
Code Snippet
const isAvailable = true;
const isAdmin = false;🔁 Booleans in Conditionals
Booleans are commonly used with if statements:
Code Snippet
const loggedIn = true;
if (loggedIn) {
console.log("Welcome back!");
} else {
console.log("Please log in.");
}📦 The Boolean Function
You can convert any value to a Boolean using the Boolean() function.
Code Snippet
console.log(Boolean(0)); // false
console.log(Boolean("hello")); // true
console.log(Boolean(null)); // false
console.log(Boolean([])); // trueNote
You can also use the double NOT operator !! for conversion.
Code Snippet
console.log(!!"text"); // true
console.log(!!0); // false⚠️ Truthy and Falsy Values
JavaScript considers some values as falsy, which means they evaluate to false in a Boolean context. All other values are considered truthy.
Falsy Values:
- false
- 0
- -0
- 0n (BigInt zero)
- "" (empty string)
- null
- undefined
- NaN
Everything else is truthy, including:
- " " (non-empty string)
- [] (empty array)
- (empty object)
- function()
🚫 Avoid Using Boolean Objects
Avoid creating Boolean values using the new Boolean() constructor. It creates an object, not a primitive, which can lead to unexpected results.
Code Snippet
const boolObj = new Boolean(false);
if (boolObj) {
console.log("This runs! 😱");
}Note
Even though boolObj contains false, it's an object and therefore truthy.
🧾 Summary
- Booleans represent true or false.
- Use Booleans in conditions to control program logic.
- Use Boolean() or !! to convert values.
- Know the difference between truthy and falsy values.
- Don’t use new Boolean().
>>“In JavaScript, even ‘false’ can be misleading if it’s wrapped in an object.”