Whale Talk JS Project General Question

You must select a tag to post in this category. Please find the tag relating to the section of the course you are on E.g. loops, learn-compatibility

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!

Hey guys,

Just a quick question surrounding Whale Talk in Loops. I understand the flow and logic, but I’m kind of confused about one section, as shown below. Why is [i] in square brackets? It’s confusing because “i” is iterating through a string, not an array. What am I missing at this point? Appreciate some tips.

const input = "whales";
const vowels = ["a", "e", "i", "o", "u"];

let resultArray = [];

for (let i = 0; i < input.length; i++){
  //console.log("i is "+ i);//
//i is 0
//i is 1
//i is 2
//i is 3
//i is 4

    for (let z = 0; z < vowels.length; z++){
      if (input[i] === vowels[z]){           <<<<<<<<<<<<<here    
        if (input[i] === "e") {
          resultArray.push("ee")
        }
        else if (input[i] === "u"){
          resultArray.push("uu");
        }
        else{
          resultArray.push(input[i]);
        }
      }
  }
}

console.log(resultArray.join("").toUpperCase());

1 Like

We can access strings and arrays by index using square brackets. Syntax is the same for both

strings are also kind of lists of characters

1 Like

Try reading the ‘Character access’ section of MDN’s documentation for JavaScript.

Refer this link.

This would clear your question!

You can think of strings as a kind of array. We can access individual letters in a string by their index number. so if

const input = "whales";

then:

input[0] = 'w'
input[1] = 'h'
input[2] = 'a'
// and so on
1 Like

so in this case you use the brackets to signify that you want to access the index of the array. If you wanted to access the first item in the array you would put input[0], for the second item input[1] etc. In this situation you have a variable, i, and you need to access the index of the array stored at the location in i, so as the value of i changes, you iterate through the array. So i is not in brackets because it itself is an item in an array, but because you are accessing the index of an array, and i is storing the number that corresponds to the specific thing you want.

Ok - thanks a bunch everyone!

1 Like