2

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?

Matsemann
  • 21,083
  • 19
  • 56
  • 89
user133688
  • 6,864
  • 3
  • 20
  • 36
  • Those are utility functions, every library has them for a good reason (_I haven't used that library._) – Ram Aug 02 '14 at 08:23
  • Many people would disagree with me, but I do feel angularJs make programming less fun. But, you can shoose which part of angularJs to use, which not, its core concept is good. – Eric Aug 02 '14 at 08:24
  • 1
    Please check http://stackoverflow.com/questions/3390396/how-to-check-for-undefined-in-javascript – Ram Aug 02 '14 at 08:32

2 Answers2

2

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.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

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

harishr
  • 17,807
  • 9
  • 78
  • 125