Step back for a moment and think about what we use non-nested loops for. We use for loops for single-dimensional data structures, like the following list of integers in the fibonacci sequence:
[1, 1, 2, 3, 5]
Notice that the data is sequential, linear, ordered. If we use a for loop, we can step through the indeces of this array one by one.
Now let’s imagine our data structure is two-dimensional. When I think two-dimensional, I think of a square or rectangle, something with a width and height. Let’s imagine a tic-tac-toe board. It could be represented with a two-dimensional array in JavaScript (in this case an array of arrays of strings).
[
["X", "O", "X"],
[" ", "X", " "],
["O", " ", "X"]
]
With this data structure, we can use a for loop to step through each row sequentially, and a nested for loop to step through each item in said row.
const board = [
["X", "O", "X"],
[" ", "X", " "],
["O", " ", "X"]
];
for (let y = 0; y < board.length; y++) {
const row = board[y];
for (let x = 0; x < row.length; x++) {
const item = row[x];
console.log(item);
}
}
/* outputs:
X
O
X
X
O
X
*/
Another example of a two-dimensional data structure could be an English sentence. Let’s take the sentence “I am not Greg”. We can use the split method on strings to separate the words into an array (the outer loop), and then loop through each character in each word.
const sentence = "I am not Greg";
const words = sentence.split(" "); // ["I", "am", "not", "Greg"];
for (let i = 0; i < words.length; i++) {
const word = words[i];
for (let j = 0; j < word.length; j++) {
const char = word[j];
console.log(char);
}
}
/* outputs:
I
a
m
n
o
t
G
r
e
g
*/
Does this help?