JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to use boolean data type in JavaScript?

In JavaScript, boolean is a primitive data type. true and false are the two reserved words that represent boolean values. You can assign true or false directly to the variable and constant.

let x = true;
const y = false;

Boolean values are used in control structures such as if/else. JavaScript executes a set of statements if a condition is true and run another set of statements if the condition is false.

let age = 20;
  console.log('You can vote.');
  console.log('You cannot vote.');

In this code, a person's age is above 18, so the condition evaluates to true and the statement mentioned in the if block executes.

For boolean values, the typeof operator returns "boolean".

let isLeapYear = false;
console.log(typeof isLeapYear); //"boolean"

It is important to note that, apart from false, six other values are considered as falsy values. Those values are:

  • null
  • undefined
  • NaN
  • "" //the empty string
  • 0
  • -0

All these six values work as false when used with comparison, logical and other operators.

let x;
  console.log(`The value of variable x is ${x}`);
  console.log('Variable x is not initialized');

In this code, variable x is not initialized, so it has an undefined value. From the text, you know that in JavaScript, undefined works as false. Therefore, a statement written inside the else block is executed.