Home > Blockchain >  Can I use another loop inside forEach in Javascript? or is it best i use to separate loops?
Can I use another loop inside forEach in Javascript? or is it best i use to separate loops?

Time:12-01

I am tasked to write a function that returns the missing uniform pieces of Company A or Company B. The function should look thru the array to determine which Company is the one with the missing piece. Can I use another loop inside forEach in Javascript? or is it best i use to separate loops? Any hints are appreciated.

function findCompanyName(uniformSet, uniformPieces) {
  uniformPieces.forEach((element) => {
    const splitedArrayUniPcs = element.split("_");
  });

  //return "example";
}

findCompanyName(
  ["shirt", "pants"],
  ["companyA_shirt", "companyA_pants", "companyB_shirt"]
); //return companyB
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Can I use another loop inside forEach in Javascript?

Yes! There is nothing wrong with nested loops in Javascript.

CodePudding user response:

Technically there's nothing wrong with it but you'll quickly find yourself confused. Instead, use named functions instead of in-line anonymous functions. That way you can debug and maintain your code much more easily in the future because the looping code will read nicely as long as your function names make sense, and you can reason through each function without having to keep the entire Jenga tower in your head.

CodePudding user response:

Can I use another loop inside forEach in Javascript?

Yes, you can use another loop inside a forEach loop in Javascript.

As @rowan-freeman stated, nested loops (loops inside a loop) are completely allowed in Javascript, as in most other programming languages.

Or is it best I use separate loops?

This depends on the nature of the problem. If you want/need to perform the same loop-logic on all elements of forEach, then nesting the loop is a clean solution.

If you need to run a single pass on all the elements as a post-processing step, for example, that would be a case when a second loop would make sense.

  • Related