-1

How can I avoid such long if conditions?

if (typeof window.checkoutConfig.shipping !== "undefined") {
    if (typeof window.checkoutConfig.shipping.rules !== "undefined") {
        if (typeof window.checkoutConfig.shipping.rules.express !== "undefined") {
            if (typeof window.checkoutConfig.shipping.rules.express.express_note !== "undefined") {
                this.expressNote(window.checkoutConfig.shipping.rules.express.express_note || "");
            }
        }
    }
}

Is there a method which I can use instead, for example (pseudo code): isset(window.checkoutConfig.shipping.rules.express.express_note).

Black
  • 18,150
  • 39
  • 158
  • 271

3 Answers3

1

Take a look at the optional chaining operator.

It will allow you to write:

window.checkoutConfig.shipping?.rules?.express?.express_note

As mentionned in the comments, you may want to use babel to make it compatible with older browsers.

var a = {};
a?.b?.c

will be compiled as:

var _a$b;
var a = {};
a == null ? void 0 : (_a$b = a.b) == null ? void 0 : _a$b.c;
Gaetan C.
  • 1,742
  • 13
  • 21
1

You could just try.

try {
  this.expressNote(window.checkoutConfig.shipping.rules.express.express_note || "");
} catch (e) {
  // meh
}
php_nub_qq
  • 15,199
  • 21
  • 74
  • 144
0

ES2020 introduced optional chaining, to prevent errors like Cannot read property of undefined. Just add a ? before each optional property: window.checkOutConfig.shipping?.rules?.express?.express_note will return undefined if the property does not exist but the property's value if it does.