2

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

Why do I see lots of javascript code lately with expressions that look like this:

if(val === "something")

Why "===" instead of just "=="? What's the difference? When should I use one or the other?

Community
  • 1
  • 1
Matthew
  • 2,210
  • 1
  • 19
  • 30
  • 1
    Duplicate: http://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use – Brandon Nov 18 '09 at 22:13
  • @mjv, did you mean recursion? :P – Brandon Nov 18 '09 at 22:14
  • My.. I guess it's a duplicate of a duplicate... Mathew, remember do check SO (and elsewhere) before posting a new question. Thanks! – mjv Nov 18 '09 at 22:15
  • @Brandon! LOL... must have cut/pasted the wrong url ;-) – mjv Nov 18 '09 at 22:17
  • 2
    I was wondering if there were duplicates. What's interesting is i searched SO on "===" and didn't get any results. – Matthew Nov 18 '09 at 22:24
  • In fairness to you, Matthew, finding tokens with non-letter/digit characters, such as "===" is not easy to do on most search engines, including on SO. – mjv Nov 18 '09 at 22:49

4 Answers4

9

The === does not allow type coercion, so something like this would return false:

if (2 === '2') // false

The "normal" javascript == operator does allow type coercion, and so this would return true:

if (2 == '2') // true
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
2
var a = 3;
var b = "3";

if (a == b) {
  // this is true.
}

if (a === b) {
  // this is false.
}
i_am_jorf
  • 53,608
  • 15
  • 131
  • 222
1

=== is typically referred to as the identity operator. Values being compared must be of the same type and value to be considered equal. == is typically referred to as the equality operator and performs type coercion to check equality.

An example

1 == '1' // returns true even though one is a number, the other a string

1 === '1' // returns false. different datatypes

Doug Crockford touches briefly on this in JavaScript the Good Parts google tech talk video. Worth spending an hour to watch.

Russ Cam
  • 124,184
  • 33
  • 204
  • 266
0

Checks that the type as well as the values match. This is important since (0 == false) is true but (0 === false) is not true.

Aaron
  • 2,659
  • 2
  • 22
  • 23