Difference between == and === operator in JavaScript
The ‘==’ operator tests for abstract equality i.e. it does the necessary type conversions before doing the equality comparison.
But the ‘===’ operator tests for strict equality i.e it will not do the type conversion hence if the two values are not of the same type, when compared, it will return false.
Example 1:
<script> // In R.H.S. string "3" is converted into // number 3, hence returns true. document.write(9 == "9"); // used for next line document.write('<br>') // Here no type conversion takes place, // hence returns false document.write(9 === "9"); </script> |
Output:
true false
Example 2:
<script> // Here L.H.S. is a string literal whereas // R.H.S. is a string object, // due to type conversion of string object into // a string literal, it returns true. document.write("GeeksforGeeks" == new String("GeeksforGeeks")); // used for next line document.write('<br>') // No type conversion takes place document.write("GeeksforGeeks" === new String("GeeksforGeeks")); </script> |
Output:
true false
Example 3:
<script> // Here number 1 is converted into true(boolean type) // as in javascript true is referred as 1 and false is // referred as 0, hence it returns true. document.write(true == '1'); // used for next line document.write('<br>') // No type conversion so it returns false document.write(true === '1'); </script> |
Output:
true false
In general “===” operator is recommended since it never does type conversion we are doing an exact comparison thus it always produces correct results.
Recommended Posts:
- Difference between != and !== operator in JavaScript
- JavaScript Course | Conditional Operator in JavaScript
- What is the !! (not not) operator in JavaScript?
- JavaScript | ‘===’ vs ‘==’Comparison Operator
- Instanceof operator in JavaScript
- JavaScript | typeof operator
- Arrow operator in ES6 of JavaScript
- JavaScript | Spread Operator
- How to get negative result using modulo operator in JavaScript ?
- Ternary operator / Question mark and colon in JavaScript
- Difference between var and let in JavaScript
- Difference between JavaScript and Php
- Difference between Java and JavaScript
- Difference between TypeScript and JavaScript
- Difference between substr() and substring() in JavaScript
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.


