= does not == === | Learn about === alias The Triple Equals

lady_with_computer

I think this just may be the most important piece of information for any software developer today.  Whatever you do, don’t forget it.

Although many software developers have been using PHP and Javascript for years, many do not know about ===, also called “The Triple Equals”. In the simplest terms, it means equality without type coercion. In other words, if using the triple equals, the values must be equal in type as well as value.

  • 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

Many developers will first encounter === when using JSLint to test their Javascript. JSLint was written by Douglas Crockford, one of the more outspoken proponents of Javascript and JSON.

JavaScript has both strict and type-converting equality comparison. For strict equality the objects being compared must have the same type and:

  • 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 objects are strictly equal if they refer to the same Object.
  • Null and Undefined types are == (but not ===).
Many experienced JavaScript and PHP developers will advocate ALWAYS using === and !=== instead of == and !=.  The reasons are obvious, you will never find yourself finding out that:
  • 0 == ” is true
  • false == ‘false’ is false
  • false == ‘0’ is true

and the non-transitive demonstration is as follows:

  • false == undefined is false
  • false == null is false
  • null == undefined is somehow true?

Leave a Reply and Let me know what you think...