How to rewrite the following function so it doesn’t use for loops?

I’m not 100% sure what you expect the code to do, because your existing code and your description differ.

Your description is, rephrased, that this function checks whether object.web or any object.XXX.web are undefined. Your code however assumes that all members are arrays and checks whether object.web or object.XXX[YYY].web are undefined. (Note that it also doesn’t do it correctly and accesses .length even though the member in question might be undefined.)

Since I’m not sure which of those is right, I’m providing two answers.

Functionality as per your textual description:

function hasNoCategories(object) {
    if(!object.web) return false;
    return Object.keys(object).every(function(key) {
        if(typeof object[key] !== 'object') return true;
        return !!object[key].web;
    });
}

Functionality as per your existing code: (but with the length property access fixed)

function hasNoCategories(object) {
    if(!object.web) return false;
    return Object.keys(object).every(function(key) {
        if(!Array.isArray(object[key])) return true;
        return object[key].every(function(el) {
            if(typeof object[key] !== 'object') return true;
            return !!el.web;
        });
    });
}

To understand how this works, check out the documentation on Object.keys (which returns an array with the names of all keys in your object) and Array.prototype.every (which runs a callback function for every element in an array and returns true only if the callback returned true for every element).

Note that I’m assuming that your “empty or undefined” should reject all kinds of falsy values including null and the number (not string) zero. If not, then all the checks like if(!something) and return !!something would need to be changed to if(typeof something === "undefined" || something === '') and return typeof something !== "undefined" && something !== '', respectively.

Side note to prevent nitpicking: Of course there are still loops going on. But it was specifically asked “without for loop” and there is no for in this code.

Leave a Comment