user133688
user133688

Reputation: 7064

Why does Angular have isDefined and isUndefined functions?

I just brushing up on AngularJS and I came across angular.isDefined and angular.isUndefined, why would you use these? Why not just do

if (!obj) or if (obj === undefined)

I get why you might not want not want to do !var because you'll get other falsey obj as well as undefined. But why bother creating a method to take care of this?

Upvotes: 2

Views: 910

Answers (2)

Guffa
Guffa

Reputation: 700472

In older browsers the undefined constant is not a constant, so you can break it by accidentally assigning a value to it:

if (undefined = obj) // oops, now undefined isn't undefined any more...

The method to check for undefined values that is safe from the non-constant undefined is a bit lengthier and is to check the type:

if (typeof obj === "undefined")

Library methods like isUndefined uses this safe method, so it allows you to write code that is compatible with more browsers without having to know every quirk of every version of every browser.

Upvotes: 2

harishr
harishr

Reputation: 18065

the two are not same: consider var obj = false, then if (!obj) would be truthy but if (obj === undefined) would be falsy

Upvotes: 0

Related Questions