== vs === What's the difference?
What is the difference between “==” and “===” in JavaScript? These operators are both used to check for equality between two variables.
What exactly does JavaScript check for when comparing two variables for equality? JavaScript checks variables for equality by comparing the variable types for equality AND by comparing the variable values. If both the variable types and the variable values are equal, then JavaScript considers these variables equal.
== (Loose Equality)
‘==’ is the loose equality operator which compares two values by first converting the values to a common type and then checks for equality of the values. Since the loose equality operator automatically converts the values to a common type, the only thing JavaScript has to worry about is if the raw values are equal.
For example, let’s say we want to compare the number 2
with the string "2"
using loose equality:
console.log(2 == "2"); // true
Even though these two values are of different types, JavaScript’s loose equality will convert these values to a common type (probably a number) and then it will perform a comparison. JavaScript’s loose equality will only care if the raw values are equal. So ultimately, JavaScript’s loose equality does something like this:
console.log(2 == "2"); // original
// console.log(2 == 2); behind the scenes, JavaScript's loose equality converts all values to a common type and THEN compares values.
=== (Strict Equality)
=== is the strict equality operator and it compares two or more values by checking both the equality of the values as well as their types BUT without doing any conversions before comparison. This is the main difference between “==” (loose equality) and “=== “(strict equality). Strict equality does not perform any conversions before trying to compare values like loose equality does.
Let’s say that we wanted to compare the number 2
with the string "2"
, but this time using strict equality:
console.log(2 === "2"); // FALSE. Types are not equal. JavaScript strict equality does NOT convert values to common types before trying to compare.
== (Loose Equality) Examples
// Initialize a number 0, a String using String constructor with value '0', and a string literal with value '0'
const num = 0;
const obj = new String('0');
const str = '0';
console.log(num == num); // true
console.log(obj == obj); // true
console.log(str == str); // true
console.log(num == obj); // true
console.log(num == str); // true
console.log(obj == str); // true
=== (Strict Equality) Examples
// Initialize a number 0, a String using String constructor with value '0', and a string literal with value '0'
const num = 0;
const obj = new String('0');
const str = '0';
console.log(num === num); // true
console.log(obj === obj); // true
console.log(str === str); // true
console.log(num === obj); // false
console.log(num === str); // false
console.log(obj === str); // false