re: Javascript Algorithms #1: Counting the Vowels in a String Of Text VIEW POST


A really good article for explaining algorithms through JavaScript for beginners. Good job and keep it up.

I thought though to try and add one more way of doing it, and that's recursively.
So here is my method for recursively finding the amount of vowels (feel free to use it).


var count = 0;

function countVowelsRecursive(text) {
    if(vowels.includes(text[0].toLowerCase())) {
    if(text.length == 1){
        console.log(`The text contains ${count} vowel(s)`);
        return count;
    } else {

countVowelsRecursive('I am a world-class developer using iterations');

The two important places are :

  • text[0] - gives us the first character of a string, because a string could be compared to an array of chars, and
  • text.substr(1) - removes the first character of the string, while it gives it to the method.

After those two, if we're left with only one character the method gives us the result and returns the counter.


Awesome work Boain. Did you test the performance implications?


I haven't tried, because I made it in like 10 minutes. But I presume it's could be close to yours. If you willing to test, do post the results here for future reference. I would be really interested to know.


It may be a correct algorithm but the implementation is not a very good one. The countVowelsRecursive should be a pure function and not depend to scoped count variable. What happens when we run the countVowelsRecursive twice in the same code snippet? Is the result of the 1st call the same as the 2nd?


No worries, you can make it a function in a function with the parent one having the count = 0 and then the child one doing the iteration. Though you got the point that the idea behind it was to showcase different algorithms, right ?

Yeah, i mentioned that the algorithm is correct at the beginning. But i felt the urge to comment about the implementation because i think it matters. Nevermind, the topic is about the algorithm so let's move on.

code of conduct - report abuse