0

I'm doing something very simple. Looking through a string to count the vowels. I've later seen that there is a better way to write what I'm trying to do, but I feel like my code should also achieve the same result, even if it is a little long winded.

The problem seems to stem from my IF condition. I write if (array[i] === 'a'||'e'||'i'||'o'||'u') The idea being to check if the letter is a or e or i, etc.

If I look for just ONE vowel at a time it works. But, I thought that using the OR operator I could extend the condition to include other values.

Anyway, I hoping somebody will be able to explain why it's not working. I'll leave the full code just below.

The answer it's returning it the full letter count of whatever sentence I give it.

function VowelCount(str) { 

    str.toLowerCase();  
let count = 0;
let array = str.split('');

for (let i = 0; i < array.length; i++){
  if (array[i] === 'a'||'e'||'i'||'o'||'u'){
    count++
  }
}

  return array; 
}

1 Answers1

0
array[i] === 'a'||'e'||'i'||'o'||'u'

This is saying is array[i] === 'a' OR true OR true OR true, etc.

'e', 'i', 'o', 'u' are all truthy values and thus that if statement will always be true.

For it to do what you're intending it to do, you should do as Gerard mentioned in the comments:

if (array[i] === 'a' || array[i] === 'e' || etc.) {...}

Another shorthand way to do this as well is:

if (['a', 'e', 'i', 'o', 'u'].includes(array[i])) {...}
Alvin Abia
  • 1,221
  • 1
  • 17
  • 18