no-loop-func

omnoms

Marko V

Posted on February 24, 2020

no-loop-func

Continuing the eslint path, this was also a query I got earlier today.

The problem...

function myFunc(complexObject) {
    // Checking validity of complexObject
    // checking in a nested property
    for(var i=0;i<complexObject.subArray.length;i++) {
        var item = complexObject.subArray[i];
        var subItemToWorkWith = item.lines.filter(function(line) {
            return line.header_id === complexObject.header.id;
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

ESlint will complain about filter having a function definition inside a for-loop which is dependent on a variable outside of the scope of the loop itself. To solve this you have to pass a pre-defined function as a callback-parameter to filter-function.

For this particular example it would be to define a function that takes a parameter for the header id of the complexobject, and then return the function that does the actual filtering.

function myFuncHeaderFilter(headerid) {
    return function(line) {
        return line.header_id === headerid;
    };
}
function myFunc(complexObject) {
    // Checking validity of complexObject
    // checking in a nested property
    for(var i=0;i<complexObject.subArray.length;i++) {
        var item = complexObject.subArray[i];
        var subItemToWorkWith = item.lines.filter(
            myFuncHeaderFilter(complexObject.header.id)
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

Again, this makes the code cleaner, easier to read, as long as you group these things in the file or sort them out in a logical structure. It also increases the possibility of code-reuse as well as making it more testable and therefore maintainable.

References that mention the same thing;
https://github.com/eslint/eslint/issues/5044
http://linterrors.com/js/dont-make-functions-within-a-loop

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
omnoms
Marko V

Posted on February 24, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About