Angular.isDefined (obj) does not work if "obj" is undefined

I'm used to typing some dirty typeof obj !== "undefined" idioms. However, I noticed the angular.isDefined(obj) method. The documentation says that it will return false if the given object is not defined. However, what it actually does (at least in Firefox) just fails, stating that "obj is undefined". Did I miss something?

+6
source share
3 answers

tl; dr; : angular.isDefined(obj) not a complete replacement for typeof .


Did I miss something?

I do not think so. typeof is a special operator that does not throw an error if obj does not exist at all. However, passing a variable to a function will result in an attempt to read the value of the variable and, therefore, throw an error if it does not exist. There is no way to prevent this.

AFAIK typeof is the only statement that does not throw if it encounters a reference error. On the other hand, if you need to check whether a variable exists or not, your code is probably poorly designed (unless you need to check for the presence of "functions" (for example, third-party modules)).

Examples of expected behavior:

 var foo; var bar = 42; typeof foo !== 'undefined'; // false typeof bar !== 'undefined'; // true typeof baz !== 'undefined'; // false isDefined(foo); // false isDefined(bar); // true isDefined(baz); // ReferenceError 
+9
source

Accessing a truly undefined variable in any way in Javascript other than tyepof throws an error. You can use Angular.isDefined with properties . For example, this will work fine:

 Angular.isDefined(window.obj); 

Since obj is an undefined property of a window .

+3
source

I am trying something like this:

 try { if (angular.isDefined (obj.ab)) { // do something with obj.ab } } catch (e) { // handle cases if any of (obj, obj.a, obj.ab) is not defined } 

This way, I get no exception if any reference property in the object hierarchy is not defined.

0
source

Source: https://habr.com/ru/post/970769/


All Articles