Equals Operator ( == ) vs Strict Equals Operator ( === )

In TypeScript (or JavaScript), we can compare the two variables with either equality operator ('==') or strict equality operator ('==='). Both comparison operators seems almost similar; but the way, they compare two given variables, is very different.

The equality operator compares only the value after applying the type coercion, if applicable. The strict equality operator compares both, the value and the type, of two operands.

1. Equals Operator ( == )

The comparison x == y with equals operator, where x and y are operands, can produce boolean result which is either true or false.

The important thing to know is that while comparing both values, the JavaScript runtime will perform type coercion to make both values of the same type.

For example, if we try to compare a string value to a number value, then string value will be converted to first into the number type, and then the comparison will happen.

"10" == 10		


parseInt("10") == 10

Read More: Complete Equality Comparison Algorithm

Let’s understand the comparison with one more example.

let a = 10;

a == 10					//true
a == '10'				//true

Look at the last two statement in above example. How variable 'a' is equal to number 10 and string '10' both.

2. Strict Equals Operator ( === )

The strict comparison x === y with equals operator, where x and y are values, produces true or false only when –

  1. x and y are of the same type
  2. x and y are have the same value

Let’s understand with an example.

let a = 10;

a === 10					//true
a === '10'					//false

In avove example, comparing a variable storing number 10 is not equal to string 10.

3. Which Operator to Use?

As a recommendation, It is advised to use strict equals operator, always. It is helpful because –

  1. we do not need to remember type conversion rules while checking for equality.
  2. comparing different data-types should be false, as expected.
  3. due to above fact, source code will be less error prone.

Happy Learning !!

Leave a Reply

Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial