JS Hint - do not perform functions inside a loop

I cannot get around the JSHint error message. Here is the loop I'm using:

for (i = 0; i < Collection.length; i += 4) { data.push({ items : Collection.slice(i, i + 4).map(function(item) { return { id: item[0], title: item[1], }; }) }); } 
+51
javascript jshint
Oct 26
source share
3 answers

You can simply move the function outside the loop and pass the map link to it:

 function mapCallback(item) { return { id : item[0], title : item[1], }; } for (i = 0; i < Collection.length; i += 4) { data.push({ items: Collection.slice(i, i + 4).map(mapCallback) }); } 

Alternatively, you can use the JSHint directive to ignore function expressions inside loops. Just put this at the top of the file in question:

 /*jshint loopfunc: true */ 
+103
Oct 26 '12 at 7:08
source share

A function declaration in a loop is erratic and potentially error prone. Instead, define the function once, and then enter the loop.

 var objMaker = function(item) { return { id : item[0], title : item[1], }; }; for (i = 0; i < Collection.length; i += 4) { data.push({ items : Collection.slice(i, i + 4).map(objMaker) }); } 
+6
Oct 26 '12 at 7:10
source share

People say: “Declaring a function in a loop is dirty and potentially error-prone,” but functions inside loops are what are explicitly specified, for example, in the Array.prototype.forEach method. Just because the word “function” should theoretically mean its new definition in every forEach call does not mean that it is actually defined every time by the Javascript engine .

The same applies to external loops, since the engines are "lazy" processing instructions. They are not going to redefine the entire forEach / Map / etc construction statement again, if nothing really has changed, they will simply pass new arguments to it.

The days of the ancient JS engines that did not know anything about such simple things, as well as about the context of the code, are long gone. And yet we get this ancient warning, which was conceived when functions could not yet be passed as arguments, as in the cases forEach or Map.

0
Feb 03 '19 at 11:10
source share



All Articles