0

Consider the code snippet below from this AngularJS tutorial:

app.factory('Auth',
  function ($firebaseSimpleLogin, FIREBASE_URL, $rootScope) {
    var ref = new Firebase(FIREBASE_URL);

    var auth = $firebaseSimpleLogin(ref);

    var Auth = {
      register: function (user) {
        return auth.$createUser(user.email, user.password);
      },
      signedIn: function () {
        return auth.user !== null;
      },
      logout: function () {
        auth.$logout();
      }
    };

    $rootScope.signedIn = function () {
      return Auth.signedIn();
    };

    return Auth;
  });

I understand the difference between != and !== is the first compares by reference and the second compares by value. Since the comparison here is to null, then why has the developer chosen to use !== instead of !=? Is my understanding correct that both would work here?

dromodel
  • 9,581
  • 12
  • 47
  • 65
  • 3
    "*the first compares by reference and the second compares by value*" Not really. They'll both compare references when comparing objects. The difference is that `!=` perform type coercion when comparing primitives. `auth.user !== null` means that anything other than *strictly* `null`, including `undefined`, results in `true`. – Jonathan Lonowski May 22 '14 at 17:53
  • 2
    For in depth answer about what's going on, including commentary on performance differences: http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons – cnick May 22 '14 at 17:54

3 Answers3

5

== / != operator only compares the value of the variables, not the type

=== / !== operator compares the type and the value of the variables

Some examples:

var varA = 5; // int
var varB = '5'; // string
var varC = 5; // int

if(varA == varB) // true (only value compared)
if(varA === varB) // false: because varB is of type string and varA of type int

if(varA == varC) // true
if(varA === varC) // true: because varA and varC are of the same type and have the same value
sjkm
  • 3,887
  • 2
  • 25
  • 43
1

I often use "if(x != null)" to check if x is either null or undefined. It's safer than just saying "if(x)" since there are other falsey values besides null and undefined.

Ben Dilts
  • 10,535
  • 16
  • 54
  • 85
1

Here's an overview table, for your convenience: http://jsfiddle.net/QQcVw/1/

            0   ""  false   null    undefined
0           Y   Y   Y       n       n
""          Y   Y   Y       n       n
false       Y   Y   Y       n       n
null        n   n   n       Y       Y
undefined   n   n   n       Y       Y    

As you can see, == considers equal three empty "values" (0, "" and false) and two "non-values" (null and undefined). See javascript standard for the exact algorithm.

In most cases, it's a good idea to avoid == and always stick to ===.

gog
  • 10,367
  • 2
  • 24
  • 38