Language: EN

javascript-tipo-boolean

The Boolean Type in JavaScript

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 perform the logic of the program. For example, they are the result of comparison operators *(such as < or ==).

Consequently, they are also used along with 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, use the keyword let or const followed by the variable name and the boolean value (true or false):

let isAdult = 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.

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