Monday, 9 February 2015

The difference between == and === in jQuery/JavaScript

In this post I would like to explain the difference between double (==) and triple (===) equals in JavaScript/jQuery. A quick and short explanation is that == does type coercion (conversion) before checking for equality; and === does strict equation which requires values to have the same type as well.
Here is what it means:
0 == false     // true
0 === false    // false, because they have different types (int, bool)
1 == "1"       // true
1 === "1"      // false, because they have different types (int, string)
null == undefined // true
null === undefined // false
Detailed (longer) explanation
When you use == the javascript interpreter will convert one side of the comparison according to these rules:
  • When comparing a number and a string, the string is converted to a number value.
  • When comparing a boolean, the boolean is converted to 1 if it is true and +0 if it is false.
  • When object is compared with a number or a string, the object is converted to its’ default value (.valueOf().toString()). If these methods are missing a runtime error is thrown.
  • When comparing an object and another object, no type conversion is made. They are equal only if they refer the same object.
When you use === the javascript interpreter will not convert values to primitive types and make sure that the operands have the same value as well as the same type.
"foo" === "foo"  // true, both operands are of type String
new String("foo") === new String("foo")  // false, 2 Objects refer diff object instances
Detailed comparison information can be found on Mozilla Developer Network page. Here is the summary:
  • 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 ===)


Post a Comment


ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)