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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


Output:

true
false

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


Output:



true
false

Example 3:

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


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.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.