Build a Sentence Analyzer - Step 1

Tell us what’s happening:

My code not giving desired result, plz help me identify the issue

Your code so far


// User Editable Region

const getVowelCount = sentence => {
  for (let vowel of sentence) {
    if(vowel === 'a' || vowel === 'e' || vowel === 'i' || vowel === 'o' || vowel === 'u') {
      return vowel.length
    }
  }
}

console.log(getVowelCount("Apples are tasty fruits"))

// User Editable Region

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36

Challenge Information:

Build a Sentence Analyzer - Step 1

The issue with your code is that the return statement inside the if block ends the function prematurely after finding the first vowel. Additionally, vowel.length is incorrect, as you are trying to calculate the length of the vowel itself, which is always 1. Instead, you need to count all vowels in the string.

okay then I will create a value to store vowel count.

I thought about this and still I am not getting desired result-

let vowelCount = 0;
const getVowelCount = sentence => {
  for (let vowel of sentence) {
    if(vowel === 'a' || vowel === 'e' || vowel === 'i' || vowel === 'o' || vowel === 'u') {
      vowelCount += 1;
    }
  }
  return vowelCount;
}

console.log(getVowelCount("Apples are tasty fruits"));

you’re using a global variable (vowelCount), which can cause issues if the function is called multiple times. The global variable retains its value across calls, leading to incorrect results

Convert the sentence to lowercase for case-insensitivity.

Thank you, Got it :slight_smile: @hasanzaib1389 :blush: :heart:


const getVowelCount = sentence => {
  let vowelCount = 0;
  for (let vowel of sentence.toLowerCase()) {
    if(vowel === 'a' || vowel === 'e' || vowel === 'i' || vowel === 'o' || vowel === 'u') {
      vowelCount += 1;
    }
  }
  return vowelCount;
}

console.log(getVowelCount("Apples are tasty fruits"));
console.log(getVowelCount("Hello, World!"));
1 Like

Your welcome. That’s great you have passed the challenge, but don’t post the solution code whenever you have passed the challenge. Posting solution code isn’t allowed here on forum.

okay, thank you. I will not do it again.

1 Like

thank you a lot for the solution, i worked it with an array contains vowels and each loop i check if the leter in the current loop is included in the array, but, it allways count the letter multiple times if it is exist, thank you again

the problem was not as i said before, the problem was in that the leter y in my solution is not included in the test, and when i read the code with my screenreader i don’t read each later i thught it the correct until i read your soluction leter by leter
this a problem of screen reader, thank you

Welcome :slight_smile: You were almost there. Good luck mate :+1: