In JavaScript, a Boolean is a primitive data type that represents one of two values: true or false. Booleans are often used in conditional testing to control the flow of a program.
1. Boolean Values
- The two possible values of a Boolean type are:
truefalselet isJavaScriptFun = true; let isItRaining = false;
2. Boolean as a Result of Comparisons
Boolean values are often returned as a result of comparison operations.
console.log(5 > 3); // true console.log(5 === 3); // false
3. Using Boolean in Conditional Statements
Booleans are used in conditional statements like if and else.
let age = 20;
if (age >= 18) {
console.log('You are an adult.');
} else {
console.log('You are not an adult.');
}
4. Boolean Functions
JavaScript provides the Boolean() function to convert other types to Boolean.
console.log(Boolean(1)); // true
console.log(Boolean(0)); // false
console.log(Boolean('')); // false
console.log(Boolean('Hi')); // true
5. Truthy and Falsy Values
In JavaScript, certain values are considered truthy or falsy. A truthy value evaluates to true in a Boolean context, while a falsy value evaluates to false.
Falsy Values:
false0-00n(BigInt zero)""(empty string)nullundefinedNaN
Truthy Values:
- Any value that is not falsy.
- Examples:
true, any non-zero number, non-empty string, arrays, objects.
if (1) {
console.log('This is truthy'); // This will execute
}
if (0) {
console.log('This is falsy'); // This will not execute
}
6. Boolean Object
The Boolean object is a wrapper around the Boolean primitive. It is rarely used in practice, as it behaves differently from Boolean primitives.
let x = new Boolean(false); console.log(typeof x); // "object"
Using Boolean as an object is generally discouraged as it can lead to unexpected results.
let y = new Boolean(false);
if (y) {
console.log('This will run because objects are truthy');
}
7. Boolean in Logical Operations
Booleans are commonly used in logical operations, such as && (AND), || (OR), and ! (NOT).
- AND (
&&): Returnstrueif both operands are truthy. - OR (
||): Returnstrueif at least one operand is truthy. - NOT (
!): Inverts the truthiness of a value.
console.log(true && false); // false console.log(true || false); // true console.log(!true); // false
Summary
- Booleans are essential in controlling the flow of programs through conditions and loops.
- Use the
Boolean()function to convert values to Boolean. - Be aware of truthy and falsy values when writing conditional logic.
- Prefer using Boolean primitives over Boolean objects to avoid unexpected behavior.