Student-friendly HTML, CSS, and JavaScript reference with examples
Nested loops are loops inside loops. Use them for arrays inside arrays (2D arrays).
const grid = [[1, 2], [3, 4], [5, 6]];
for (const innerArray of grid) {
// innerArray is each sub-array
}
The outer loop goes through each sub-array.
for (const innerArray of grid) {
for (const num of innerArray) {
// num is each number in the sub-array
}
}
The inner loop goes through each element in the current sub-array.
let total = 0;
for (const subArray of [[1, 2], [3, 4]]) {
for (const value of subArray) {
total = total + value;
}
}
// total is 10 (1 + 2 + 3 + 4)
[1, 2] [3, 4]