0

I would like to know which way to check if a variable is nullor undefined in AngularJS is the best way.

First way:

if(!myVar){...}

Second way:

if(myVar === null || myVar === undefined){...}

Third way:

if(angular.isUndefined(myVar) || myVar === null){...}

I prefere the first one but I want to be sure if it's the best way.

The problem with the last one is that I use an angular's function to test if it's undefined and a native JavaScript way to check if it's null.

Cœur
  • 32,421
  • 21
  • 173
  • 232

2 Answers2

0

The best way to do it, which is the route that Coffeescript too goes, is:

if (typeof MyVariable === "undefined" || MyVariable === null){ ... }
Community
  • 1
  • 1
musically_ut
  • 33,232
  • 8
  • 87
  • 102
  • What is it about this approach that makes it _the best_? I wonder what it was about this that led the makers of Coffeescript to choose this method. – Anil Natha Apr 26 '16 at 15:43
  • Did a little more research and found [this post](http://stackoverflow.com/questions/2703102/typeof-undefined-vs-null) that talks about a little bit about why this method is better. Has to do with reference errors. But I still wonder if this truly is the best way. – Anil Natha Apr 26 '16 at 15:50
0

I think which depend of the situation, usually i use the first way since usually I validate when the variable is 0, empty array, undefined or null,if you goal is validate only the values null and undefined i think wich the second way is the ideally, and the third way is good but force to denpend of the angular.

NopalByte
  • 159
  • 5