Difference Between == and === in  javascript

Difference Between == and === in javascript

·

2 min read

But lets first understand what does = , == and === do in javascript

The "=" is an assignment operator, It assigns a value to a variable.

let a = 5
//Here we have assigned the value 5 to variable a.

let a = "This is the best blog you have ever read"
//Here we have assigned a string to variable a.

The "===" is called a Strict equality operator, It is used to test if two values are equal.

let a = 5
let b = 5
console.log(a === b)
//true

let a = 5
let b = 4
console.log(a === b)
//false

//As you can see we have used the strict equality operator to check whether a is equal to b.

But there is also a "==" operator, Which is called the equality operator.

This is also used to test if two values are equal.

let a = 5
let b = 5
console.log(a == 5)
//true

Now you may ask if it does the same thing then why have different names!!

Don't worry I'll explain

As you must have noticed the "===" operator is called the strict equality operator which means it will strictly compare the values of both variables and only if they are exactly equal will it return true otherwise it will return false.

BUT

The '"==" operator does what we call a type conversion

Okay let us first understand what that means.

When comparing two variables the "==" operator tends to transfer data from one type to another.

0 == "0" // true, because the string "0" is being converted to the number 0.
0 == "" // true, because empty string is converting to 0
2 * "3"// 6, because the string "3" is being converted to number 3.

Let us see the difference

let a  = 5
let b = "5"
//As we can see a is assigned a number and b is assigned a string 
//lets see if they are equal

console.log(a==b)
//true
console.log(a===b)
//false

As you can see in the above example the strict equality operator compares the value and if they are not equal it returns false.

but

the loose equality operator converts the string of "5" into a number and then compares them and returns true.

Conclusion -

" === " will check the type, if that matches then will check the value and show the result. if the type is not the same it will show false.

'' == '' will check the type and if they are not the same it will perform a type conversion and then show the result.