generaly, if I want to check if obj.foo.bar
exits, I will do this:
if(
typeof obj != "undefined" &&
typeof obj.foo !== "undefined" &&
typeof obj.foo.bar !== "undefined"
){ action() }
this is quite ugly and repetitious, and sadly I have to use it a lot.
I believe there won't be any function isDefined()
available to do so, because even empty function (function isDefined(){}
) will throw an error when if(isDefined(obj.foo.bar)){action()}
So, is there any smart way to check that obj.foo.bar
exits?
EDIT:
- Approaches using string parsing (or just passing variables as string) are extremely problematic - since minifier might be in use.
typeof obj != "undefined"
could be replaced withobj
. This solution still doesn't satisfy me.
EDIT 2 - Solution:
as proposed here
var a = {
b: {
c: 'd'
}
};
function isDefined(fn) {
var value;
try {
value = fn();
} catch (e) {
value = undefined;
} finally {
return value !== undefined;
}
};
// ES5
console.log(
isDefined(function () { return a.b.c; }), //return true
isDefined(function () { return a.b.c.d.e.f; }) //returns false
);
// ES6 using the arrow function
console.log(
isset(() => a.b.c),
isset(() => a.b.c.d.e.f)
);
I have approved @T.J. Crowder's solution and not @somethinghere's one because at the end the regular solution is shorter, and because try
catch
statements have other purpose and can cause problems