8

Possible Duplicate:
Javascript === vs == : Does it matter which “equal” operator I use?

As the title states; when should you use the === operator check when using JavaScript, and when not to.

Edit: more complete answer found here. Thanks to Mark Byers for pointing it out.

_L

Community
  • 1
  • 1
ptrn
  • 4,902
  • 6
  • 28
  • 30

3 Answers3

13

It is strict type equality operator. It not only checks whether two are equal in value but also of the same type.

Consider a situation when you compare numbers or strings:

if (4 === 4) // same value and type
{
  // true
}

but

if (4 == "4") // same value and different type but == used
{
  // true
}

and

if (4 === "4") // same value but different type
{
  // false
}

This applies to objects as well as arrays.

So in above cases, you have to make sensible choice whether to use == or ===

It is good idea to use === when you are sure about the type as well

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • thanks for fast and thorough answer- will set as answer after the 15 minutes have passed – ptrn May 22 '10 at 06:32
2

When you wish to inhibit implied typecasts. For example:

3 == '3'

is true, whereas this is not:

3 === '3'

Douglas Crockford recommends always using strict comparison.

Delan Azabani
  • 79,602
  • 28
  • 170
  • 210
  • To be honest, I'm always a bit dubious when someone says "ALWAYS" do xxx. I can see situations where it is desiderable to compare a number to a string. Obviously you could manually cast the string to a number but if JS can do it for you why bother? :) – nico May 22 '10 at 06:41
  • 2
    @nico, agree, there are cases where you simply don't need it, a common case is when you want to compare against `null` and `undefined` in one step, `if (foo == null)` does the job, or when using the `typeof` operator, you also don't need it because it will *always* return a string... `if (typeof foo == "undefined")` is enough... – Christian C. Salvadó May 22 '10 at 06:47
1

You use it to check if a variable's containing value and type is same as the compared one.

Abdel Raoof Olakara
  • 19,223
  • 11
  • 88
  • 133