JavaScript Program to Count Vowels and Consonants
includes(), counts vowels and consonants separately, and returns the counts.Examples
How to Think About It
Algorithm
Code
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');
Dry Run
Let's trace the input 'hello' through the code
Convert to lowercase
'hello' becomes 'hello'
Initialize counters
vowelCount = 0, consonantCount = 0
Loop through each character
Characters: 'h', 'e', 'l', 'l', 'o'
Check each character
'h' is consonant, consonantCount=1; 'e' is vowel, vowelCount=1; 'l' consonantCount=2; 'l' consonantCount=3; 'o' vowelCount=2
Print result
Vowels: 2, Consonants: 3
| Character | Is Letter? | Is Vowel? | Vowel Count | Consonant Count |
|---|---|---|---|---|
| h | Yes | No | 0 | 1 |
| e | Yes | Yes | 1 | 1 |
| l | Yes | No | 1 | 2 |
| l | Yes | No | 1 | 3 |
| o | Yes | Yes | 2 | 3 |
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
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');
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');
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple Loop | O(n) | O(1) | Performance and clarity |
| Regular Expressions | O(n) | O(1) | Concise code, beginners may find regex tricky |
| Array Filter | O(n) | O(n) | Functional style, easier to read for some |