Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Hint - don't make functions within a loop

I can not get around JSHint's error message. Here is the loop I am 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],             };         })     }); } 
like image 464
myTD Avatar asked Oct 26 '12 07:10

myTD


People also ask

Can you put a function inside a loop?

Accepted Answer "function" as a keyword is only used for defining functions, and cannot be used inside a loop (or inside an "if" or "switch" or other control statement.) The only kinds of functions that can be defined within loops are anonymous functions.

Can you put a function inside a for loop JavaScript?

A function is just a set of instructions, so you could, theoretically, take any function's instructions and put them directly inside the loop, and you have essentially the same thing.


1 Answers

You can just move the function outside the loop and pass a reference to it to map:

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 a JSHint directive to ignore function expressions inside loops. Just put this at the top of the file in question:

/*jshint loopfunc: true */ 
like image 114
James Allardice Avatar answered Oct 06 '22 02:10

James Allardice