Anjan Dutta

Comparing Equality Operator and Identity Operator in JavaScript

Comparing Equality Operator and Identity Operator in JavaScript

Updated On: 19/09/2021

Today I am comparing equality (==) and identity operator (===) in javascript.

Both of these operators work pretty similarly with value checks. But, there is a fundamental concept that makes these two operators very much different.

Javascript equality operator (==)

Before any comparison, the equality operator checks for type conversion between two values. If any necessary conversion required then, it converts the type first and then compares the values.

The equality operator does the hard part by itself. And this is one of the reasons why we call javascript, a loosely typed language.

Javascript identity operator (===)

The identity equality operator does not check for any type conversion. It compares the values as it is and produces the output on its basis.

Because of this attribute, it is preferable to use the identity operator whenever possible.

If any comparison results true by identity operator, it will always result true if compared using an equality operator. But vice versa is not possible.

Comparing equality and identity operator in JavaScript.

Value 1Value 2=====
undefinedundefinedtruetrue
nullnulltruetrue
truetruetruetrue
falsefalsetruetrue
‘foo’‘foo’truetrue
00truetrue
+0-0truetrue
+00truetrue
-00truetrue
0flasetruefalse
” “falseturefalse
” “falsetruefalse
‘0’0truefalse
’23’23truefalse
[4, 5]‘4, 5’truefalse
new String(‘bar’)‘bar’truefalse
nullundefinedtruefalse
let x = [10, 20];let y = [10, 20];falsefalse
let x = { id: 10 };let y = { id: 10 };falsefalse

Things to remember

  1. Equality operator (==) does type coercion
  2. Identity operator (===) does not do type coercion

Which one performs better

The identity operator is faster because of no type checking or conversion before comparing values.

Reference

http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3

Remembering these combinations are necessary. Because, value comparison is one of the top most used feature in any programming language. And doing it effectively might save a lot of time with improved code quality.

Thanks for reading.