11

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

I can understand why === is necessary when comparing numbers, booleans, empty strings, etc, due to unexpected type conversions e.g.

var foo = 1; 
var bar = true; 
// bar == foo => true
// bar === foo => false

But can == ever introduce a bug when comparing a variable to a non-empty string literal? Is it more efficient to use == over === in this case?

Community
  • 1
  • 1
AlexMA
  • 9,842
  • 7
  • 42
  • 64
  • http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/ – xkeshav Aug 08 '12 at 13:15
  • Type equality should be the same or faster: http://stackoverflow.com/a/359509/453277 – Tim M. Aug 08 '12 at 13:16
  • equality operator (`===`). It checks that values are the same value and the same type. Rememeber this. – xkeshav Aug 08 '12 at 13:17
  • If both operands are guaranteed to be string values (and not `String` objects) then there is precisely no difference between the two operators (per spec). – Tim Down Aug 08 '12 at 13:46

4 Answers4

11

This has been asked here a lot so I'll just let a better poster then myself answer.

Take a look here: http://longgoldenears.blogspot.com/2007/09/triple-equals-in-javascript.html

The 3 equal signs mean "equality without type coercion". Using the triple equals, the values must be equal in type as well.

0==false   // true
0===false  // false, because they are of a different type
1=="1"     // true, auto type coercion
1==="1"    // false, because they are of a different type

source Difference between == and === in JavaScript

Community
  • 1
  • 1
Eric Robinson
  • 2,025
  • 14
  • 22
5

It is a good practice to always use the identity operators (!== and ===) and perform type coercion manually only when you need to (e.g. Boolean(someVar) or Number(someVar)).

A fun fiddle.

jbabey
  • 45,965
  • 12
  • 71
  • 94
1

Well, I sort of answered it myself... 5 == "5", but 5 !== "5", which might be unexpected. I'll give credit to anyone who has a deeper insight though.

AlexMA
  • 9,842
  • 7
  • 42
  • 64
0

the "==" does a type conversion before the comparing is done. That's the reason why 5 == "5" is true and not false.

The "===" instead does not this conversion so that 5 === "5" is not the same as long as the type is not the same.

tuxtimo
  • 2,730
  • 20
  • 29