When the nested loop is done looping, is the variable j going to be reset back to zero? I assume it is, because we start from the beginning again, but I want to make sure that all you experts out there agree with me. Also, where can I find the answer to this in textbooks and not here?

const userTextInput = "Hello my name is Luka";
const vowels = ["a", "e", "u", "e", "i"];

for(let i = 0; i <= userTextInput.length; i = i + 1){
  for(let j = 0; j <= vowels.length; j = j + 1){
    if(userTextInput[i] === vowels[j]){
      console.log(vowels[j]);
    }
  }
}

4 Answers

0
Florian Schlag On

Yes it is set back to the value you initialized it, everytime the loop starts. For your case, yes it is 0.

1
junvar On

Technically, not quite. When the nested lop finishes, j will not be defined. Only when it starts again (for the next iteration of i), will j then be reset.

For example, the below will give you a j is not defined error.

for (let j = 0; j < 5; j++)
  ;
console.log(j);

1
Maheer Ali On

The following steps may help you to understand the code:

  • The variable j is only present inside the the nested loop.

  • When the nested loop ends means j <= vowels.length becomes false the code exits the loop.

  • At this point there is no j. j is destroyed.
  • Now the outer for loop in continued again and i is incremented.

  • This time a new variable j is again created and initialized to 0.

  • This happens while i <= userTextInput.length; is true

1
Louis Matthijssen On

Just to be clear, the loop isn't doing anything special here. You are resetting the variable every time you enter the loop.

A for loop has 3 parts (for (1; 2; 3) {}):

  1. Run once before starting the loop
  2. Condition to check if the loop body should be executed
  3. Code to execute after each iteration

So, when you are doing this:

for (let j = 0; j < 5; j++) {}

You are declaring and j and setting it to 0. This always happens before you enter the loop. Then, the loop body is executed while j is less than 5, and after every iteration j is incremented by 1.

Because you declared j in the for statement, it only exists within the for loop. When you exit the loop, the variable is gone.

However, even if the variable would still exist outside the loop, you would reset it the next time you enter the loop again, because you're doing j = 0.

In this example I'm declaring the variable outside the for loop, so it still exists outside the loop:

let j = 0;

for (let i = 0; i < 5; i++) {
    for (; j < 5; j++) {
        console.log(`iteration ${j}`);
    }
}

console.log(i);
console.log(j);

// Prints:
// iteration 0
// iteration 1
// iteration 2
// iteration 3
// iteration 4
// undefined
// 4

I've omitted the first part of the for loop, so j is never reset. This causes the inner loop to only run 5 times, which would be 25 times if the variable would be reset every time.