-2

What's the difference between this:

if(!foo) {
  ...
}

And this:

if(typeof foo === "undefined") {
  ...
}

I've seen some code which attempts to treat these two statements as though they're identical, but I've run into problems when doing so. I've been doing something like this with AngularJS:

var property = {
  value: $scope.foo //$scope.foo may or may not have been defined above, depending on contexts
  ...
};

func(property);

function func (property) {
  if(!property.value) {
  //This doesn't get executed, even if $scope.foo was never defined
  }
}

It seems to me that (!foo) !== (typeof foo === "undefined")

Is this correct?

A. Duff
  • 4,097
  • 7
  • 38
  • 69
  • Here is a post that can be useful to understand usage of === http://stackoverflow.com/questions/523643/difference-between-and-in-javascript – osmanraifgunes Dec 30 '14 at 17:31

1 Answers1

1

Here's an example where they are not identical:

var foo = false;

if(!foo) {
    alert('!foo');
}

if(typeof foo === "undefined") {
    alert('undefined');
}

Only the first condition will be satisfied.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928