What is the == Operator in JavaScript?

Introduction

The loose == operator in JavaScript is the loose equality operator. It compares two values and outputs a boolean value, true or false. It is a loosely typed equality operator, meaning it does not consider the data types of the values being compared; it only checks if the values are the same. However, we can’t rely on this for performing strict comparisons between values in JavaScript. In this tutorial, we will explore the depth of this operator: what it is, how it works, and when it should be used. Since it is an equality operator, we will explore its functionality through code examples for a clearer understanding.

Examples

JavaScript

copy

 let a = 'a';
 let b = ['a'];
 console.log(a == b);  // output: true 
                
 let a = 1;
 let b = '1';
 console.log(a == b); // output: true
                
 let a = [1];
 let b = '1';
 console.log(a == b); // output: true

Did you notice above that I used the == equality operator in three different places to make comparisons? As I mentioned earlier, it does not consider data types; it only cares about the values. Let's break it down below to give you a better understanding.

JavaScript

copy

 let a = 'a';
 let b = ['a'];
 console.log(a == b);  // output: true

Notice here, I declare two variables and then apply the == operator to check whether these two variables are the same or not. Surprisingly, the output is true. However, the output should be false because the first variable, a = ‘a’, is a string while the second variable, b = [‘a’], is an object/array. So logically, the output should be false.

Tip: You can check the type of any variable using the typeof operator in JavaScript.

Hopefully, you understood the logic behind this. Since you have understood this, let's discuss when we should use it.

As we already know how the == operator behaves, we need to keep this in mind when thinking about using it in our code. However, that doesn’t mean it's completely useless. Let's prove this. Imagine a scenario where we need to perform a comparison between a string and an array. In this case, if we want to omit data types and only directly check the values, the == operator is great for that purpose.

In JavaScript, it is recommended to use the === operator for strict comparison most of the time. If you want a full explanation of the === strict operator, you can check out this tutorial JavaScript strict operator.