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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With