There are at least three ways to do this; which one you use is largely up to you and sometimes even a matter of style, though there are some substantive differences:
if..in
You can use if..in
:
if ("_test" in config.UI.opacity)
...because when used in a test (as opposed to the special for..in
loop), in
tests to see if the object or its prototype (or its prototype's prototype, etc.) has a property by that name.
hasOwnProperty
If you want to exclude properties from prototypes (it doesn't much matter in your example), you can use hasOwnProperty
, which is a function all objects inherit from Object.prototype
:
if (config.UI.opacity.hasOwnProperty("_test"))
Just retrieve it and check the result
Finally, you can just retrieve the property (even if it doesn't exist) and the decide what to do with the result by looking at the result; if you ask an object for the value of a property it doesn't have, you'll get back undefined
:
var c = config.UI.opacity._test;
if (c) {
// It's there and has a value other than undefined, "", 0, false, or null
}
or
var c = config.UI.opacity._test;
if (typeof c !== "undefined") {
// It's there and has a value other than undefined
}
Being defensive
If it's possible that config.UI
won't have an opacity
property at all, you can make all of those more defensive:
// The if..in version:
if (config.UI.opacity && "_test" in config.UI.opacity)
// The hasOwnProperty version
if (config.UI.opacity && config.UI.opacity.hasOwnProperty("_test"))
// The "just get it and then deal with the result" version:
var c = config.UI.opacity && config.UI.opacity._test;
if (c) { // Or if (typeof c !== "undefined") {
That last one works because the &&
operator is particularly powerful in JavaScript compared with some other languages; it's the corollary of the curiously-powerful ||
operator.