JavaScript Boolean Function

Anika Tabassum Era Feb 15, 2024
  1. Basic Use of Primitive Type - Boolean in JavaScript
  2. Use of the Boolean Function in JavaScript
JavaScript Boolean Function

Unlike most other programming languages, JavaScript owns the Boolean type as the primitive data type. The Boolean type mostly has true and false as the only default values.

But in cases, we also denote 0 as false and 1 as true.

In the following example sets, we will examine the Boolean type’s basic drive and the working principle of the Boolean function. Here, one thing we need to know is the difference between === and ==.

When we are mentioning the strict equality operator ===, it is certain to match the data type along with the matching format.

Supposedly, we are comparing a string "123" and a number 123 with the strict equality operator. This will result in a false value; or simpler words, it will not show a match.

Similarly, if we consider matching 0 as false and 1 as true, we will not get a match. Let’s check the instances for better understanding.

Basic Use of Primitive Type - Boolean in JavaScript

We will perform a simple mathematical drive to draw out the Boolean values. Technically, any variable that has a value will be called true.

Here, we will check the remainder of a given variable divided by 2. If the result is satisfactory, we print correct, otherwise false.

Also, we will see how the strict equality operator performs and how the general == equal operator works.

Code Snippet:

var a = 5;
var x = a % 2;
if (x == 1) {
  console.log('correct');
} else {
  console.log('incorrect');
}
if (x === true) {
  console.log('ok');
} else {
  console.log('not ok');
}

Output:

Basic Use of Primitive Type - Boolean

As it can be seen, we got a true value for the condition in the first conditional statement. And in the section where we matched 1 as the true, it was not giving the expected result.

This defines how the strict equality operator prevents if the data type doesn’t match.

Use of the Boolean Function in JavaScript

In this case, the operation of the Boolean function does not require any conditional statement to evaluate the true or false. The basic function draws out the answer taking the expression as the parameter.

The output here will always be true or false. Let’s check the code lines.

Code Snippet:

var a = 5;
var b = 4;
var x = a % 2;
var y = b % 2;
console.log(Boolean(x))
console.log(Boolean(y))

Output:

Use of Boolean Function

Anika Tabassum Era avatar Anika Tabassum Era avatar

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

LinkedIn Facebook

Related Article - JavaScript Boolean