In this article, we have a fun algorithm challenge: vowels.js
. It’s a simple problem – count the vowels in a string. Of course, there are multiple solutions to the problem, and we’ll explore two of them below.
Directions
- Write a function that returns the number of vowels used in a string.
- Vowels are the characters ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’.
Difficulty: Easy
This question is quite easy. It might be asked during a junior developer interview.
Solution #1
The first solution we’ll explore is an iterative way to solve this problem. It’s pretty straightforward.
We’ll declare a count
variable at the top, which is what we’ll use to keep count of the vowels in the string (str
). Next, we’ll want an array of the vowels, which will be used later to compare with the characters (char
) in the string (str
).
Rather than a traditional for
loop, we’re going to use a for of
loop. We think it makes the code a bit easier to read and understand.
Notice the method called on str
, .toLowerCase()
. It’s important not to forget this, else we might end up with an incorrect count (as ‘A’ !== ‘a’).
So, for each character in the string, search for a vowel. If there’s a match, increase the count.
The last step is to actually return
the count. We must not forget that!
function vowelCount(str) {
let count = 0;
const vowels = ["a", "e", "i", "o", "u"];
for (let char of str.toLowerCase()) {
if (vowels.includes(char)) {
count++;
}
}
return count;
}
console.log(vowelCount("abc")); // 1
console.log(vowelCount("hello")); // 2
Solution #2
This solution is even more straightforward. It makes use of a regular expression, and a ternary operator. It’s storing the regular expression matches (str.match()
) in the variable matches
. Then it returns the count of matches if there indeed is any, or 0 if there aren’t any matches.
function vowelCount(str) {
const matches = str.match(/[aeiou]/gi);
return matches ? matches.length : 0;
}
console.log(vowelCount("abc")); // 1
console.log(vowelCount("hello")); // 2
Conclusion
This challenge is rather simple, but it’s always useful to explore multiple solutions to problems. Feel free to check out some of the other challenges we’ve posted.
JavaScript Interview Question – Steps.js
Three Simple Algorithms with JavaScript
Topics
About the Author

Matt Fay
Matt is the founder of JavaScript Today, a platform dedicated to high-quality JavaScript education and commentary. With a deep curiosity for technology, he gravitates toward understanding how things work and has been diving into the world of information security. Outside of coding, Matt enjoys exploring languages; he can understand some Russian and Italian, and is currently learning Thai.
Discussion (Loading...)
Join the Discussion
Sign in to share your thoughts and engage with the JavaScript Today community.