skip to Main Content

so i’m still new to coding and i came a cross this problem it says

Write a function, countVowels(word), that takes in a string word and returns the number of vowels in the word.

I came up with this solution but it’s not working there’s an issue in it and i don’t know what

let arr = ['a','e','o','i','u','U','I','O','E','A']
function count(word){
    let count = 0

    for (let i = 0 ; i< word.length;i++){
        let letter = word[i]
        if (arr.includes(letter) ){
            return count ++
        }
        return count
    }
}

what can i do to make it work ?!

i tried doing it with foreach and it worked but i don’t know what is missing from this solution

3

Answers


  1. You should return count in the end of the function, otherwise you return prematurely on the first vowel. Also I would suggest to learn modern JS data structures like Set. It’s better in many cases to use Set#has() instead of Array#includes() since it’s faster and more semantic.

    let set = new Set(['a','e','o','i','u','U','I','O','E','A']);
    function count(word){
        let count = 0
    
        for (let i = 0 ; i< word.length;i++){
            let letter = word[i]
            if(set.has(letter)){
                count ++
            }
        }
        return count;
    }
    
    console.log(count('Hello WORLD!'));
    Login or Signup to reply.
  2. Your problems are that you are returning inside the for loop. The first return you don’t want at all, you just want to increment count. The second return you just want to move outside the for loop. See the working snippet:

    let arr = ['a','e','o','i','u','U','I','O','E','A']
    
    console.log( count(arr) )
    
    function count(word){
        let count = 0
    
        for (let i = 0 ; i< word.length;i++){
            let letter = word[i]
            if (arr.includes(letter) ){
                // Only incrment the count, do not return
                count ++
            }
        }
    
        // Return only after all the counting is done
        return count
    }
    Login or Signup to reply.
  3. also

    const vowels = 'aeiouAEIOU';
    
    function count_vowels(word) 
      {
      let count = 0;
      for (let letter of word)
        if (vowels.includes(letter)) count++;
      return count;
      }
      
    console.log( count_vowels('Hello world') );
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search