I try to understand nested for loops in javascript but it's very confusing.
I have this code and I can't understand how it works:
let n = 5;
for (let i = 0; i < n; i++) {
for (let j = 0; j < i; j++) {
console.log(j);
}}
In console I have : 0 1 0 1 2 0 1 2 3
And I'm trying to figure out which loop represent each number.
Run this code:
let n = 5;
let str = '';
for (let i = 0; i < n; i++) {
for (let j = 0; j < i; j++)
str += j;
console.log("Outer: "+i+" Inner: "+str);
str = '';
}
Output is:
Outer: 0 Inner:
Outer: 1 Inner: 0
Outer: 2 Inner: 01
Outer: 3 Inner: 012
Outer: 4 Inner: 0123
As you can see, in the output above, inner loop (the one with variable j
) doesn't run, because if you replace the variables with numbers it would be
0 < 0
(i < 0), which isn't true.
The best way for you to understand how nested loops work is to write each step and variable values on the paper, like so:
n = 5
STEP 1:
"Outer: 0 Inner:"
STEP 2:
"Outer: 1 Inner: 0"
And so on... Keep repeating this until the argument in the outer loop is false (i < n).
You must remember, in for loop the sequence of orders executed:
for(let i = 0; i < 5; i++) {
console.log('It works');
}
let i = 0; (this executes only once)
i < 5 (if true run 3 and 4)
run the code in loop
i ++
i < 5 (if true run 6 and 7)
run the code in loop
i++
etc.