2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Difference between == and ===?

What is the difference between below methods in comparing a string with undefined value.

var x;

  if(x==undefined) 

 {  

 alert(x);

  }

and

if(x===undefined)

 {

   alert(x); 

 }

Why should i prefer second method in this case.. Please let me know advantages..

userimage
  • == attempts to convert the values to the same type before testing if they're the same. "5" == 5
  • === does not do this; it requires objects to be of the same type to be equal. "5" !== 5

In this case, the result is:

  • x == undefined will be true if x is undefined or null.
  • x === undefined will only be true if x is undefined.

You should prefer the first method if you'd like undefined and null to be treated equivalently. 

Answer is