- Using ‘==’ operator
- Using ‘===’ operator
- SameValueZero: used mainly in sets, maps and arrays.
- SameValue: used elsewhere
Note: Type coercion means that the two values are compared only after attempting to convert them into the same type. Let’s look at all the value in which the ‘==’ operator will return true.
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(null == undefined);
- ‘false’ // false wrapped in string.
- ” or “” // empty string
- NaN // not-a-number
So both null and undefined are false values and they represent an ’empty’ value or undefined in js, hence the comparison with ‘==’ operator returns true.
Now, let’s look at all the value in which the ‘==’ operator will return false.
console.log(21 == 32);
console.log(21 == ’32’);
console.log(true == 0);
console.log(null == false);
In the above code when we compare null with false we get false, as null being a primitive data type it can never be equal to a boolean value, even though they belong to the same falsy group.
‘===’ operator: Also known as strict equality operator, it compares both the value and the type that is why the name “strict equality”.
Let’s see some code where ‘===’ operator will return true.
console.log(‘hello world’ === ‘hello world’);
console.log(true === true);
console.log(5 === 5);
Simply checking the types and values at both the sides and then just printing out the boolean true or false.
Some example where it will return false.
console.log(true === 1);
console.log(true === ‘true’);
console.log(5 === ‘5’);
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : immukul