Iterator and for loops in Whale Talk Project

here is the link to the project I am working on:

Hello, I have been working on this project and have an issue. After I followed directions exactly how the lesson teaches and also watching the video and trying to solve it before seeking help, I’m not understanding the output. Not sure if its my code or an issue with the output console.

I get nothing to output in the console. I want to know what is wrong with this code before I continue with the project
Thank you for your help.

const input = "song of the ocean";
const vowels = ["a", "e", "i", "o", "u"];
const resultArray = [];

for(let i = 0; i < input.length; i++){
  //console.log('i is ' + i);
  for(let i = 0; i < vowels.length; i++){
    //console.log('i is ' + i);
    if(input[i] === vowels[i]){

Consider carefully what is being compared here.


Are you sure you want to use i to iterate through both for loops?

1 Like

Well, i was wondering about that but I do not know. I was thinking that each for loop runs independently and comparing the string characters to each other even with both having the i iterator. I looked at the hint in the question and it has the i iterator. The video shows inputIndex and vowelIndex as for loops variables but I wanted to try the i and not just copy the video lesson.

Also, I did not expect to get nothing to output at all including errors.

Thank you for your time.

The issue is in the line I mentioned. It’s all about scope. In that particular if statement, the same i assigned value is used for both arrays.

So running through the nested for loop:

First run: i = 0, input[i] = 's', vowels[i] = 'a' 's' === 'a' -> false
Second run: i = 1, input[i] = 'o', vowels[i] = 'e' 'o' === 'e' -> false
Third run: i = 2, input[i] = 'n', vowels[i] = 'i' 'n' === 'i' -> false
Fourth run: i = 3, input[i] = 'g', vowels[i] = 'o' 'g' === 'o' -> false
Fifth run: i = 4, input[i] = ' ', vowels[i] = 'u' ' ' === 'u' -> false

All 5 iterations proved falsy in your if statement, so nothing was printed to the console.

Since input.length is 17, that same sequence will repeat 17 times without ever printing anything.
What would happen if you used another variable name for the inner loop’s iterator? Common convention would be to use j for nested loop.

I did try with another variable. It work and I did get a result printed that makes sense. I will continue with the project.

Thank you for the good explanation.

1 Like