re: Debugging: "Cannot read property 'length' of undefined." VIEW POST


Thank you, Todd, for this retrospect. Experience is an invaluable resource.

I believe your source of the issue is lacking a step. The error Cannot read property 'length' of undefined can only be invoked when you specifically call property length of a variable which has been declared but not given a value or has an explicit pointer to undefined.

Any existing and non existing property of an object is query-able and will result in undefined if no value was assigned to it (({}).nothing === undefined). The property length is no different - it would simply return undefined.

Furthermore, since you referenced MDN, you should follow to the Parameters Section to see that on top of a USVString, you can pass a Request instance.

You can also follow the specifications and use browser's URL constructor as first argument.

To conclude, I recommend a different defensive approach when wrapping (AKA monkey-patching) native behaviour. Because of the risks of built in behaviour changing and updating (or just missing some coverage) - a more responsible approach would suggest a fall-back to the original behaviour.

const { fetch: originalFetch } = window;
window.fetch = function(...args) {
    try {
        // ... your reckless logic
    } catch (error) {
        // ... Optionally report this

        // Calling original behaviour ensures the flow does not break
        return originalFetch.apply(window, args);

Again. Thank you for sharing from your experience

code of conduct - report abuse