Count Vowels in a String
Explore methods to count vowels in a string by mastering both iterative loops and recursive function calls in JavaScript. This lesson guides you through implementing and understanding these two approaches, helping you solidify your recursion skills as compared to iteration.
We'll cover the following...
Problem Statement
Here we’ve to find the number of vowels in a given string. We know that the English alphabet contains vowels: . Let’s solve this problem by using both iterative and recursive methods.
Iterative Method
To solve this problem, we have to traverse the entire string. Therefore, we can initiate a simple for loop.
Let’s have a look at the code:
In the code snippet above, the main function countVowels() takes a string as input. It traverses over the entire length of the string.
The condition:
for (var i = 0; i < string.length; i++)
makes sure that the for loop breaks if i becomes equal to the length of string, calculated by using string.length.
Next, we use a condition:
isVowel(string[i])
to determine whether that particular character is a vowel or not. If this condition is satisfied we increment count by .
isVowel() is a function that returns true if the character being passed is a vowel and false otherwise.
The illustration below will help you understand the code snippet above:
Recursive Method
Let’s take a look at the recursive counterpart. We reduce the length of the string until the length of the string is equal to . Then we check whether the last character in the string is a vowel or not. If it is a vowel, the number of vowels is increased.
The isVowel() function checks whether the character being input to it is a vowel or not. This function is similar to the iterative version. The major change that occurs is the conversion of the for loop to the recursive call.
Here, we reduce the length of the input string and pass it to another instance of the same function. The leftover letter is checked, for whether, it is a vowel or not and the result is appended at the end after the function returns.
Let’s dry run our code:
In the next lesson, we have a challenge for you to solve for yourself.