34

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

What are the differences between === vs == and !== vs !=?

When should you use each one?

Asons
  • 84,923
  • 12
  • 110
  • 165
Matt
  • 5,547
  • 23
  • 82
  • 121
  • 4
    This is a dupe of about 1000 questions – Paolo Bergantino Jul 07 '09 at 20:07
  • 1
    Can you post a link to those other questions? I always make sure I look first, obviously the titles weren't clear enough to be found easily. Maybe having this question in as well will help point people in the right direction in case they haven't searched for the exact thing. – Matt Jul 07 '09 at 20:12
  • 1
    My thoughts exactly. Here's one: http://stackoverflow.com/questions/359494/javascript-vs – GManNickG Jul 07 '09 at 20:13
  • 2
    I think the problem is you can't search for `===`. – GManNickG Jul 07 '09 at 20:18
  • Thanks, much more helpful! Looks as though Matthew vines' answer is pretty clear and straight to the point, but if you want a more detailed look at this you should check out Bill the Lizard's answer at the link above. – Matt Jul 07 '09 at 20:20
  • oh... yeah that would make sense. I wonder if the guys at SO could change the search to accommodate for that? – Matt Jul 07 '09 at 20:21
  • 1
    I updated the title of http://stackoverflow.com/questions/359494 so hopefully it will be a little easier to find. You can't search === but you can search "equal." – Patrick McElhaney Jul 07 '09 at 20:31

3 Answers3

40

=== is the Identity operator, and is used to test that value and type are equal.

so..

"3" == 3 // true
"3" === 3 // false
1 == true // true
1 === true // false
"1" == true // true
"1" === true // false

so when you care that value and type are equal, or not equal use Identity operators === or !==

Matthew Vines
  • 27,253
  • 7
  • 76
  • 97
  • "1" == true.. what? I thought I knew these rules thanks for highlighting – Kiss Koppány May 06 '15 at 07:25
  • @KissKoppány if you're confused, it's because 1 and 0 are boolean operators. == does type conversion, so '1' == 1 == true, '0' == 0 == false. === does NOT do type conversion. Generally it's better to go with === unless you expect your vars to typechange frequently which is bizarre (to me at least) – tdc Oct 27 '15 at 18:32
9

The "normal" == operators in javascript perform type coercion, and try their best to do things like treat a string as number or an object as a string where required. The longer === operators will not do type coercion, but rather a strict comparison within the type.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
5

=== and !== are the same as == and !=, but additionally do checks for the variable types.

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
schnaader
  • 49,103
  • 10
  • 104
  • 136