Loops: Question on Whale talk JS Project (code printing thrice instead of twice)

Hey fellow coders,

Can anyone please tell me why the vowels within the input string “turpentine & turtles” are printed to the console three times when it should only be two ? I’ve been staring at my code for the last 20 mins trying to figure it out & cant seem to see where i’ve made a mistake? i’m sure it’ll be something really simple too!

Any help would be really appreciated! thank you


!!!

Heres a link to the project: https://www.codecademy.com/courses/introduction-to-javascript/projects/whale-talk

Here’s my code:

let input = "turpentine and turtles";

const vowels = ["a", "e", "i", "o", "u"];
//console.log(vowels[0])

let resultArray = [];

for (let i = 0; i < input.length; i++) {
  // console.log(` index is ${i}`)
  //console.log(input[i])
  if (input[i] = "e") {
    resultArray.push(input[i]);
  }
  if (input[i] = "u") {
    resultArray.push(input[i]);
  }
  for (let v = 0; v < vowels.length; v++) {
    //console.log(`index is ${v}`)
    if (input[i] === vowels[v]) {
      resultArray.push(input[i]);
    }
  }
}
console.log(resultArray)
const resultString = resultArray.join("").toUpperCase();
console.log(resultString)

Notice how you’ve used the assignment operator =, instead of equality ===:

Since you’ve now assigned a non-empty string to input[i], it is a truthy value, meaning that the code within each if block will always run.

2 Likes