JavaScript - Nuances of myArray.forEach vs for loop

后端 未结 3 1510
梦谈多话
梦谈多话 2020-11-29 17:58

I\'ve seen plenty of questions that suggest using:

for (var i = 0; i < myArray.length; i++){ /* ... */ }

instead of:

for         


        
3条回答
  •  不知归路
    2020-11-29 18:27

    It is suggested by many developers (e.g. Kyle Simpson) to use .forEach to indicate that the array will have a side effect and .map for pure functions. for loops fit well as a general-purpose solution for known number of loops or any other case that doesn't fit as it is easier to communicate because of its broad support across the majority of programming languages.

    e.g.

    /* For Loop known number of iterations */
    const numberOfSeasons = 4;
    for (let i = 0; i < numberOfSeasons; i++) {
      //Do Something
    }
    
    /* Pure transformation */
    const arrayToBeUppercased = ['www', 'html', 'js', 'us'];
    const acronyms = arrayToBeUppercased.map((el) => el.toUpperCase));
    
    /* Impure, side-effects with .forEach */
    const acronymsHolder = [];
    ['www', 'html', 'js', 'us'].forEach((el) => acronymsHolder.push(el.toUpperCase()));
    
    

    Convention wise, this seems best, however the community hasn't really settled on a convention on the newer iteration protocol for in loops. Generally, I think it's a good idea to follow the FP concepts that the JS community seems to be open to adopting.

提交回复
热议问题