Hello everyone. Happy to break a CodeNewbie!
I've been working with JavaScript lately and have hit a snag: nested loops. Can anyone explain to me how you create nested loops?
Thanks in advance!
Hello everyone. Happy to break a CodeNewbie!
I've been working with JavaScript lately and have hit a snag: nested loops. Can anyone explain to me how you create nested loops?
Thanks in advance!
For further actions, you may consider blocking this person and/or reporting abuse
Parth -
maliha56 -
ΠΠΈΠΊΠ° -
Vitarag -
Top comments (3)
Hi Collin,
I think you want to just put the "inner" loop inside the "outer" loop. For example
In this case, the outer loop runs first, setting the variable
i
to it's value, and while keeping that value constant, the inner loop runs settingj
from 0 to 2 in order. When that's done, the outer loop setsi
to its next value, and the inner loop runs again.You can see from the logged statements the sequence these variables step through.
Why would you do this? It's not uncommon if you have a nested structure (like an array of arrays, or an array of objects) to want to do the same "loop" to each item in the top level collection.
This wouldn't have to be
for
loops - you could use forEach or while or any other "loop" construct, the key idea is that a variable set during the outer loop's execution is "fixed" while the inner loop is running, and the inner loop will run once for each value in the outer loop. In every case, put the inner loop inside the body of the outer loop - any place you would have put another expression you can add a loop.Thanks very much, this helps a lot!
To create nested loops in JavaScript you can place one loop inside another. For instance using a for loop inside another for loop allows you to execute iterations for both loops simultaneously aiding in various iterations and pattern creations.
Pressure Washing Services in Fayetteville AR