The Boolean type is one of the primitive types in JavaScript. This data type can only represent two states,
true(true)false(false)
Boolean values are used to handle program logic. For example, they are the result of comparison operators (like < or ==).
Consequently, they are also used with conditionals and loops. So, basically, it’s one of the types you will use most frequently.
Declaration of Boolean values
To declare a boolean variable in JavaScript, you use the keyword let or const followed by the variable name and the boolean value (true or false):
let isOfLegalAge = true;
const hasActiveAccount = false;
Conversion to Boolean
To convert another type to boolean, we can use the Boolean() function.
console.log(Boolean(1)); // true
console.log(Boolean("")); // false
console.log(Boolean(null)); // false
console.log(Boolean("Text")); // true
JavaScript also allows implicit type conversion, which means certain values are considered truthy or falsy in Boolean contexts.
Logical Operators
JavaScript provides several logical operators that allow you to combine and manipulate Boolean values:
const a = true;
const b = false;
console.log(a && b); // false
console.log(a || b); // true
console.log(!a); // false
Comparisons
Boolean values are commonly used in comparison expressions. JavaScript offers comparison operators that return Boolean values:
const x = 5;
const y = "5";
console.log(x == y); // true (due to type conversion)
console.log(x === y); // false (different types)
console.log(x < 10); // true
