Mastering Booleans in JavaScript: A Simple Guide

Anmol singhAnmol singh
2 min read

Understanding Booleans in JavaScript

In JavaScript, Boolean is a data type that represents a truth value. It can only have one of two values: true or false. This concept is often used to answer yes-or-no questions in code.

For instance, if you want to determine whether someone is an adult or not based on their age, you would use a Boolean variable to store this information.


What is a Boolean?

The Boolean type is like a switch with two states: true or false, yes or no. It is a fundamental data type used to represent logical decisions in programming.

Example:

javascriptCopy codelet isAdult = true; // or false

Here, the variable isAdult stores a Boolean value, which tells us if the person is an adult (true) or not (false).


Checking the Type of a Boolean Variable

In JavaScript, you can use the typeof operator to check the type of a variable. For Boolean variables, the output will always be boolean.

javascriptCopy codeconsole.log(typeof isAdult); // Output: "boolean"

Key Point: Boolean variables can only hold the values true or false.


Dynamic Typing in JavaScript

One of the powerful features of JavaScript is its dynamic typing. This means you can change the type of a variable by reassigning it a new value of a different type. For instance:

javascriptCopy codelet a = 5;        // Initially, 'a' is a number
a = true;         // Now, 'a' is a Boolean

In the code above, the variable a starts as a number but is later reassigned as a Boolean. This is possible in JavaScript, unlike in strongly typed languages like Java or C++, where the type of a variable is fixed once declared.


Code Example

Here's a demonstration:

javascriptCopy codelet isAdult = false; // Initially set to false
console.log(isAdult); // Output: false

isAdult = true; // Value reassigned to true
console.log(isAdult); // Output: true

// Checking the type
console.log(typeof isAdult); // Output: "boolean"

// Dynamic typing
let a = 5; // Number
console.log(typeof a); // Output: "number"

a = true; // Changed to Boolean
console.log(typeof a); // Output: "boolean"

0
Subscribe to my newsletter

Read articles from Anmol singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Anmol singh
Anmol singh