Whale Talk

Hello,

Struggling with the two concepts in the whale talk exercise. Why are the conditions in the for loops expressed like so:

for (let inputIndex = 0; inputIndex < input.length; inputIndex++)

Why are they not expressed as:

for ( i = 0; i < input.length; i++)

Also, is the following code saying:

if (input[inputIndex] === 'e'){
        resultArray.push(input[inputIndex]);
    }

---- If, during the loop of inputIndex one finds an ‘e’ in input – push that ‘e’ into resultArray. If someone could confirm my logic here; it would be much appreciated. I’ve included all the code below as a reference:


let input = 'turpentine and turtles'
const vowels = ['a', 'e', 'i', 'o', 'u'];
let resultArray = []
for (let inputIndex = 0; inputIndex < input.length; inputIndex++) {
    if (input[inputIndex] === 'e'){
        resultArray.push(input[inputIndex]);
    }
    if (input[inputIndex] === 'u'){
        resultArray.push(input[inputIndex]);
    }
    for (let vowelIndex = 0; vowelIndex <vowels.length; vowelIndex++) {
        if (input[inputIndex] === vowels[vowelIndex]){
           resultArray.push(vowels[vowelIndex]);
        }
    }
}
const resultString = resultArray.join('').toUpperCase();
console.log (resultString);

Hello!
For your first point, your two loops are pretty much identical. For the second, it’d probably need to be:
for (let i = 0; …)
but, i or inputIndex, the loops are the same.
They’ve probably used inputIndex as it’s more descriptive of what they’re using it for within the loop, and so a little clearer of what the loop is supposed to be doing - which can be helpful when coming back at a a later date, or reading someone else’s code.

Your logic is correct for your second point.
They could have put;
resultArray.push(‘e’)
and had the same effect.
(Though that would lead to extra work if you decided to change which letters you were looking for later on. i.e. you’d have to change the ‘e’ in two places rather than just one.
In longer, more complicated code this code be easily missed)

Hope that helps

The second question is answered. Thanks for your help; however – I;m struggling to understand the difference between i = 0 and let i = 0 ?

‘let’ is telling the program that you’re initialising a variable.
All variables you use need to be initialised either with var, let or const, so the program knows what they are and how to treat them - e.g;
let input = “turpentine and turtles”
or;
const vowels = [’…’]

So, because it’s the first time you’re using i or inputIndex, you need to use one of the initialisers, and let is the most appropriate for a loop like this.

Writing it as;
let i = 0;
for (i = 0; i < input.length; i ++) {

}
would be the same, but more long-winded.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.