Why for loops behave this way if it have another one inside it!

hey guys , can someone please explain me why if we have 2 loops like this , the loop for (i) keep repeating every number again and again

function dosomething(n) {

for (var i= 0 ; i < n ; i ++ ){

console.log(i) // 0 1 2 3 4

}

for (var i= 0 ; i < n ; i ++ ){

for ( var j = 1 ; j < n ; j++){

console.log(i) // 0 0 0 0 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4
}
}
}

dosomething(5);

The inner loop goes through 1-4 every time the outer is incremented. First i becomes 0 and j goes through 1-4 in 4 steps. Then i is incremented, j goes through again 4 times and it continues until outer cycle ends. This is how nested for loops work.

3 Likes

thank you , i think i got it now

1 Like