0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Count Vowels and Consonants

Use a JavaScript function that loops through each character of a string, checks if it is a vowel with includes(), counts vowels and consonants separately, and returns the counts.
📋

Examples

Inputhello
OutputVowels: 2, Consonants: 3
InputJavaScript
OutputVowels: 3, Consonants: 7
Input123!@#
OutputVowels: 0, Consonants: 0
🧠

How to Think About It

To count vowels and consonants, first look at each letter in the string one by one. Check if the letter is a vowel by seeing if it matches any of the vowels (a, e, i, o, u). If yes, add to the vowel count. If it is a letter but not a vowel, add to the consonant count. Ignore any characters that are not letters.
📐

Algorithm

1
Get the input string and convert it to lowercase.
2
Create counters for vowels and consonants and set them to zero.
3
Loop through each character in the string.
4
Check if the character is a letter.
5
If it is a vowel, increase the vowel counter.
6
If it is a consonant, increase the consonant counter.
7
After the loop, return or print the counts.
💻

Code

javascript
function countVowelsAndConsonants(str) {
  const vowels = 'aeiou';
  let vowelCount = 0;
  let consonantCount = 0;
  const lowerStr = str.toLowerCase();

  for (const char of lowerStr) {
    if (char >= 'a' && char <= 'z') {
      if (vowels.includes(char)) {
        vowelCount++;
      } else {
        consonantCount++;
      }
    }
  }

  console.log(`Vowels: ${vowelCount}, Consonants: ${consonantCount}`);
}

countVowelsAndConsonants('hello');
Output
Vowels: 2, Consonants: 3
🔍

Dry Run

Let's trace the input 'hello' through the code

1

Convert to lowercase

'hello' becomes 'hello'

2

Initialize counters

vowelCount = 0, consonantCount = 0

3

Loop through each character

Characters: 'h', 'e', 'l', 'l', 'o'

4

Check each character

'h' is consonant, consonantCount=1; 'e' is vowel, vowelCount=1; 'l' consonantCount=2; 'l' consonantCount=3; 'o' vowelCount=2

5

Print result

Vowels: 2, Consonants: 3

CharacterIs Letter?Is Vowel?Vowel CountConsonant Count
hYesNo01
eYesYes11
lYesNo12
lYesNo13
oYesYes23
💡

Why This Works

Step 1: Convert to lowercase

Using toLowerCase() makes sure the program treats uppercase and lowercase letters the same.

Step 2: Check if character is a letter

We only count characters between 'a' and 'z' to ignore numbers and symbols.

Step 3: Count vowels and consonants

If the character is in the string 'aeiou', it is a vowel; otherwise, it is a consonant.

🔄

Alternative Approaches

Using Regular Expressions
javascript
function countVowelsAndConsonantsRegex(str) {
  const vowels = (str.match(/[aeiou]/gi) || []).length;
  const consonants = (str.match(/[bcdfghjklmnpqrstvwxyz]/gi) || []).length;
  console.log(`Vowels: ${vowels}, Consonants: ${consonants}`);
}
countVowelsAndConsonantsRegex('hello');
This method uses regex to find vowels and consonants directly, making code shorter but slightly less clear for beginners.
Using Array Filter
javascript
function countVowelsAndConsonantsFilter(str) {
  const vowels = 'aeiou';
  const letters = str.toLowerCase().split('').filter(c => c >= 'a' && c <= 'z');
  const vowelCount = letters.filter(c => vowels.includes(c)).length;
  const consonantCount = letters.length - vowelCount;
  console.log(`Vowels: ${vowelCount}, Consonants: ${consonantCount}`);
}
countVowelsAndConsonantsFilter('hello');
This approach uses array methods for clarity and functional style but may be less performant on very large strings.

Complexity: O(n) time, O(1) space

Time Complexity

The program loops through each character once, so time grows linearly with input size.

Space Complexity

Only a few counters and variables are used, so space is constant regardless of input size.

Which Approach is Fastest?

The simple loop method is fastest and uses least memory; regex and filter methods are more concise but slightly slower.

ApproachTimeSpaceBest For
Simple LoopO(n)O(1)Performance and clarity
Regular ExpressionsO(n)O(1)Concise code, beginners may find regex tricky
Array FilterO(n)O(n)Functional style, easier to read for some
💡
Always convert the string to lowercase before counting to handle uppercase letters easily.
⚠️
Beginners often count non-letter characters as consonants or vowels, so always check if a character is a letter first.