Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular.isDefined(obj) doesn't work if "obj" is undefined

I'm used to typing the somewhat messy typeof obj !== "undefined" idiom. However, I noticed the angular.isDefined(obj) method. The documentation says it will return false if the given object is not defined. However, what it's actually doing (in Firefox, at least) is just failing, saying "obj is not defined". Am I missing something?

like image 432
David M. Karr Avatar asked Jun 12 '14 18:06

David M. Karr


2 Answers

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


Am I missing something?

I don't think so. typeof is a special operator that doesn't throw an error if obj does not exist at all. However, passing a variable to a function will result in trying to read the value of the variable and hence throw an error if it does not exist. There is no way to prevent that.

AFAIK typeof is the only operator that doesn't throw if it encounters a reference error. On the other hand, if you have to test whether a variable exists or not, then your code is probably poorly designed (unless you have to test for existence of "features" (like third-party modules)).

Examples of the 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
like image 59
Felix Kling Avatar answered Oct 03 '22 15:10

Felix Kling


Accessing a truly undefined variable in any way in Javascript, except tyepof throws an error. You can only use Angular.isDefined with properties. E.g, this would work fine:

Angular.isDefined(window.obj);

Because obj is an undefined propery of window.

like image 43
VitalyB Avatar answered Oct 03 '22 16:10

VitalyB