Equality (‘=’ vs ‘==’ vs ‘===’) in JavaScript
In JavaScript, there are three types of equality operators: =, ==, and ===. Each of these operators has a different purpose and can lead to different results when used. Understanding the differences between these operators is essential for writing efficient and reliable code in JavaScript.
This post was originally posted at https://agrawalsuneet.github.io/blogs/equality-in-javascript/ and later reposted on Medium.
= Operator in JS
The = operator is used for assigning values to variables. It is called the assignment operator. When using the = operator, the value on the right side of the operator is assigned to the variable on the left side.
For example:
var x = 5;
This assigns the value of 5 to the variable x.
== Operator in JS
The == operator is used for checking equality between two values. It is called the loose equality operator. When using the == operator, JavaScript performs type coercion to compare the values. Type coercion is the process of converting one data type to another data type.
For example:
console.log(5 == '5'); // true
Here, the == operator compares the values 5 and ‘5’. Even though they are of different data types (one is a number and the other is a string), JavaScript performs type coercion and returns true.
=== Operator in JS
The === operator is used for checking strict equality between two values. It is called the strict equality operator. When using the === operator, JavaScript compares the values and their data types. If the values and data types are the same, the operator returns true. If the values or data types are different, the operator returns false.