Learn what is the difference between == and === operator in javascript.
Javascript being a loosely typed language never fails to surprise us. It can convert a value from one data type to another.
Thus to check equality of two different values there are two different operators which can be used according to our need.
The major difference between == and === is about type conversion.
== or loose equality operator in javascript.
==
operator is used to check equality of two different values. It tests the abstract equality. It does the necessary type conversion before checking the equality.
This operator checks equality only after converting both the values to a common type i.e type coercion.
Input: // ‘==’ operator console.log(21 == 21); console.log(21 == '21'); console.log('food is love'=='food is love'); console.log(true == 1); console.log(false == 0); console.log(false == 1); console.log(null == undefined); Output: true true true true true false true
=== or strict equality operator in javascript.
===
operator is used to check strict equality of two different values. It does not do the type conversion before checking the equality.
This operator checks equality only after without doing the type coercion.
Input: // ‘==’ operator console.log(21 === 21); console.log(21 === '21'); console.log('food is love' === 'food is love'); console.log(true === 1); console.log(false === 0); console.log(false === 1); console.log(null === undefined); Output: true false true false false false false
There are two types of values in the javascript true
and false
.
List of true values in javascript
'0' 'false' // false wrapped in string. [] {} function(){}
List of false values in javascript
'' or "" // empty string false 0 null undefined NaN // not-a-number
On type conversion during loose checking the boolean values and other values are converted like this and thus equality is checked. But in 90% you should avoid loose equality checking.