Build a Sentence Analyzer - Step 3

Tell us what’s happening:

My code not working please help me, how do I fix it ?

Your code so far

function getVowelCount(sentence) {
  const vowels = "aeiou";
  let count = 0;

  for (const char of sentence.toLowerCase()) {
    if (vowels.includes(char)) {
      count++;
    }
  }
  return count;
}

const vowelCount = getVowelCount("Apples are tasty fruits");
console.log(`Vowel Count: ${vowelCount}`);


// User Editable Region

function getConsonantCount(sentence) {
  let consonantCount = 0;
  for (let consonants of sentence.toLowerCase()) {
    if(consonants !== 'a' || consonants !== 'e' || consonants !== 'i' || consonants !== 'u' || consonants !== 'u') {
      consonantCount++;
    }
  } return consonantCount;
}

console.log(getConsonantCount("Coding is fun"))
console.log(getConsonantCount("Hello, World!"))
console.log(getConsonantCount("aeiou"))


// User Editable Region

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36

Challenge Information:

Build a Sentence Analyzer - Step 3
https://www.freecodecamp.org/learn/full-stack-developer/workshop-sentence-analyzer/step-3

Your logic is not quite correct.

Firstly, you’ll need to remove (or otherwise account for) all spaces and non-alphabet characters from any sentence which is passed to the function, otherwise these will be counted erroneously as consonants.

Secondly, the way you’ve constructed your conditional statement, with all of those conditional OR operators, won’t get the desired result.

For example, if I fed the string ‘aeiou’ into your function, the first iteration of the for loop would compare 'a' !== 'a' (false) OR 'a' !== 'e' (true) OR 'a' !== 'i' (true) etc… so would then increment consonantCount, for each of the characters in the string, returning a value of 5 from the function, when it should be 0.
The conditional statement should check that ‘a’ is not equal to ALL of the vowels. (You might wish to use logical AND instead of OR).

I wrote like this and test passed, is this the correct way ?

function getConsonantCount(sentence) {
  let vowelCount = 0;
  for (let vowel of sentence.toLowerCase()) {
    if(vowel === 'a' || vowel === 'e' || vowel === 'i' || vowel === 'o' || vowel === 'u' || vowel === " " || vowel === "," || vowel === "!") {
      vowelCount++;
    }
  } return sentence.length - vowelCount;
}

console.log(getConsonantCount("Coding is fun"))
console.log(getConsonantCount("Hello, World!"))
console.log(getConsonantCount("aeiou"))

You could use character instead of vowel, it’s more semantic
It’s a way to solve it, sure

Yes, I saw ‘char’ being used in solution, also includes() method. Thank you :slight_smile:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.