-2

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

In some JavaScript if statements I've seen the use of === as opposed to the standard ==.

What is the difference between these? and should I be using either one of them over the other?

e.g.

if (variable == 'string') {
 return;
}

compared to:

if (variable === 'string') {
 return;
}
Community
  • 1
  • 1
Dave Haigh
  • 4,369
  • 5
  • 34
  • 56
  • The "===" operator doesn't imply automatic conversion. – Adriano Repetti May 17 '12 at 14:17
  • why does anyone want to downvote this question? often people face this in early stages of js learning. – Parth Thakkar May 17 '12 at 14:24
  • thanks, now that i've seen the duplicate question I understand the difference. I tried searching the site before posting the question, for '==' and '===', but nothing came up. – Dave Haigh May 17 '12 at 14:26
  • why do people keep down voting this question? you try searching for === in the search box at the top of this site and see what comes up. – Dave Haigh May 18 '12 at 08:54
  • Can I suggest buying a copy of this: http://www.amazon.co.uk/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/ref=sr_1_1?ie=UTF8&qid=1337476385&sr=8-1 – Kev May 20 '12 at 01:13

2 Answers2

8

=== also checks to be equal by type

For instance 1=="1" is true but 1==="1" is false

narek.gevorgyan
  • 4,165
  • 5
  • 32
  • 52
3

The === is a strict comparison (also checks type), whereas the == does a more relaxed comparison.

For instance:

var a = 'test';
if (a == true) {
   // this will be true
}

if ( a === true) {
   // this will not be true
}

Another example:

var b = '0';
if ( b == 0){
    // this will be true
}

if ( b === 0 ){
    // this will not be true
}

In particular it is very important when comparing falsy values. In Javascript all the following will be treated as false with relaxed comparison:

* false
* null
* undefined
* empty string ''
* number 0
* NaN
Mike Dinescu
  • 54,171
  • 16
  • 118
  • 151
  • 2
    Strict being, matching the value and type, rather than just value :-) For example, '136' == 136 would return true, but '136' === 136 wouldn't – Alex May 17 '12 at 14:18
  • Good explanation thanks, the documentation on this site http://bonsaiden.github.com/JavaScript-Garden/#types.equality is very useful too. – Dave Haigh May 17 '12 at 16:03