Understanding the Strict Equality Operator ('===') in JavaScript

Introduction

The strict equality operator (===) in JavaScript ensures that both the values and data types are the same before returning true. Unlike the loose operator ==, it cares about data types, which is useful when working with complex codes and conditions. It is widely used in code due to its accurate output. Today, we will explore it in depth by putting it under the microscope. We'll also discuss why it's so useful and how you, as a developer, can take advantage of it. Let’s start coding for a better understanding.

Tip: If you want a well-explained tutorial about the '==' operator, you are recommended to check out this article for a better understanding

Examples

JavaScript

copy

 let a = [1];
 let b = '1';
 console.log(a === b); 
 // output: false because the data types (array vs string) differ.
                
 let a = '1';
 let b = 1;
 console.log(a === b);
 // output: false because the data types (string vs number) differ.
                
 let a = [1];
 let b = [1];
 console.log(a === b); 
 // output: false because the arrays are stored in different memory locations.

Great! All the outputs are correct as expected. Have you noticed? JavaScript compares values strictly using the strict equality operator (===). It first checks whether the data types are the same. If they are not, it immediately returns false, without considering whether the values are the same. This behavior is what makes it known as the strict equality operator.

You might have a question in your mind: why is the output false in the last examples where a = [1] and b = [1]? The answer is that this is the correct output because, even though the values and data types are the same, the arrays we created are stored in different memory locations.

Hopefully, your doubt has been cleared. Now, let's check out another example to see when it outputs true

JavaScript

copy

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

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

Hopefully, there is no need to provide further explanation about this, as both examples above have the same data type and values, so the output is true.

let's move on to the last step: where should you use this? The answer is quite straightforward. It is recommended to use it for accurate output when you need to consider data types. On the other hand, you can use the loosely typed equality operator when you don’t need to consider data types.