Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between == and === in JavaScript? [duplicate]

Possible Duplicate:
Javascript === vs == : Does it matter which “equal” operator I use?
When would JavaScript == make more sense than ===?

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

like image 950
Exception Avatar asked Nov 15 '11 06:11

Exception


2 Answers

  • == 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. One common use of this is optional function arguments.

function greet(name, greeting) {
    if (name == undefined) name = 'World';
    if (greeting == undefined) greeting = 'Hello';
    alert(greeting + ' ' + name);
}

greet(); // alerts "Hello World"
greet("Bob"); // alerts "Hello Bob"
greet(null, "Goodbye"); // alerts "Goodbye World"
like image 151
Jeremy Avatar answered Oct 05 '22 04:10

Jeremy


suppose we have x=5,

== is equal to

x==8 is false x==5 is true

=== is exactly equal to (value and type)

x===5 is true x==="5" is false

Hope you understand this concept

like image 29
Hitu Bansal Avatar answered Oct 05 '22 04:10

Hitu Bansal