Hackerrank Solution: for-of loop in JavaScript

In this post I’m going to show you one possible solution of one of the 10 Days of JavaScript challenges from Hackerrank. We’re going to use for-of loop to first print vowels and then consonants in a given string.


Full description of the challenge: 10 Days of JavaScript. Day 2: loops.

Solution and explanation

First thing that came to my mind was to use two loops: one for the consonants and the other for the vowels. Obviously, that’s not the cleanest way. My goal was to loop through the given string just once.

In the below code s is the input. I have created a variable called vowels which is initialized with the vowels existing in English. The loop uses it to check whether specific letter from the given string is a vowel. The other variable, consonants, has different purpose. I used it to store all the consonants that are found while looping through the input (s).

What happens is this:

  • the program is looping through every letter in the string (for (let letter of s));
  • it checks if current letter is a vowel (vowels.includes(letter)); if yes, it prints it in the new line;
  • if the current letter is not a vowel, is added to consonants (consonants += letter + ‘\n’;); there is also a new line character at the and of each letter so I can print them later in a new line each;
  • after the loop consonants are printed (console.log(consonants);).

. . .

Yes, this stupid code works 💛

Leave a Comment