We have often seen developers using == and === on codes. In this tutorial we will clear all the doubts that you have regarding these two operators. In JavaScript we have 4 ways of comparing two equals, out of which two are widely used. We will be discussing those two exclusively in this tutorial. ‘==’ is also called abstract equality comparison and ‘===’ is called strict equality comparison.
Table of Contents
Strict equality (=== / Triple Equals)
When you use triple equals === in JavaScript, you are checking and testing for the strict equality. This means both the type and the value we are comparing have to be the same.
Let’s suppose, we have two values a and b , here’s how JavaScript checks if a===b:
- If the types of a and b are different then the code returns false.
- If a and b are numbers and if any of the values is NaN , then the output will be false.
- If both the values are null, then the output is true.
- If a and b are objects, the code returns true only if they refer to the same object.
Code 1
const obj1 = { answer: 42 };
const obj2 = { answer: 42 };
obj1 === obj2 // false
Code 2
'hello world' === 'hello world'
// true (Both Strings, equal values)
true === true
// true (Both Booleans, equal values)
Abstract equality (== / Double Equals)
When using double equals in JavaScript we are testing for loose equality. Double equals also performs type coercion. Type coercion means that two values are compared only after attempting to convert them into a common type.
The == operator, let’s see it details with a brief overview:
- If a and b are the same type, check if a === b.
- If a and b are both either undefined or null, return true.
- If a is a number and b is a string, convert b to a number and then compare using ===. Similarly, if a is a boolean or string, and b is a number, convert a to a number.
- If a or b is a boolean, convert the other value of a number and compare them.
- If a is an object and b is a symbol, string, or number, try to convert a to primitive using valueOf() and then compare using ===.
Code 1
' ' == 0; // true
' ' == false; // true
({ valueOf: () => 42 }) == 42; // true
({ valueOf: () => 0 }) == false; // true
Code 2
77 == '77'
Result : true
Hope you have understood the difference between double and triple equal operator in JavaScript. Comment below with your doubts and queries.