-1

My code is giving me an error with jsHint. I am trying to do this:

if (data.result == 't' || task == 'show') {

But it tells me I should replace "==" with "===" can someone tell me why it gives this message?

Alan2
  • 23,493
  • 79
  • 256
  • 450
  • 1
    have a look at this one http://stackoverflow.com/questions/523643/difference-between-and-in-javascript – Qpirate Nov 19 '13 at 15:43

3 Answers3

3

=== is the strict equality operator.

== is the normal equality operator, == converts its operands to the same type if they are not already of the same type.

So there is a danger that something like "" == 0 will give you true although they are of different types.

Since there is implicit conversion involved which you might not no about because it is happening automatically, there is some danger and potential for errors or bugs that are hard to trace.

=== won't convert its operands, it will just compare them.

Ibrahim Najjar
  • 19,178
  • 4
  • 69
  • 95
1

Silent type conversion can be a source of bugs. If you avoid converting between data types at comparison time, then you avoid many of those bugs.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

=== means equality without type coercion. === operator will not do the conversion, it will only compare the operands.

The example given by sdfx here is very helpful in understanding this:

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

From MDN:

JavaScript has both strict and Type–converting (abstract) comparisons. A strict comparison (e.g., ===) is only true if the operands are the same Type. The more commonly used abstract comparison (e.g., ==) converts the operands to the same Type before making the comparison. For relational abstract comparisons (e.g., <=), the operands are first converted to primitives, then the same Type, before comparison.

Features of comparisons:

  • Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding
    positions.
  • Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
  • Two Boolean operands are strictly equal if both are true or both are false.
  • Two distinct objects are never equal for either strictly or abstract comparisons.
  • An expression comparing Objects is only true if the operands reference the same Object.
  • Null and Undefined Types are == (but not ===).
Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331