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
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 likeSet
. It’s better in many cases to useSet#has()
instead ofArray#includes()
since it’s faster and more semantic.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:
also