The type Boolean 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 make the logic of the program. For example, they are the result of comparison operators *(such as <
or ==
).
Consequently, they are also used alongside conditionals and loops. Therefore, it is basically one of the types you will use most frequently.
Declaration of boolean values
To declare a boolean variable in JavaScript, the keyword let
or const
is used 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 that certain values are considered truthy or falsy in Boolean contexts.
We see it in the articles
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
We see it in the article
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
We see it in the article