I keep getting "null", but I need a "0" to show

Hi. I need to count vowels (a, e, i, o, u, not y) in JS and I wrote this code:

function getCount(str) {
  let countVowels = /[aeiou]/g
  let result = str.match(countVowels)
  let final = result.length
    if (final > 0) {
  return result.length;
  else {
    return "0"

I have also tried: return 0 (without quotation marks) and nothing. I keep getting “null”, but I need to get a 0 if there are no vowels in the string I want to count. I’m trying to console log out “getCount(“my pyx”)” Please, help :smiley:

I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

you should look up what match returns when it doesn’t find any matches.
(hint: it is not a zero)

This is what I found: javascript - what is the condition to return the items that doesn't match - Stack Overflow
But it doesn’t really help. Should I change the entire code if, as per what I’ve read, I’m going to get null everytime? Thank you.

when you search for documentation, use keywords in google like “js match regex” and then pick the documentation that is appropriate and check the return values described.

Sounds good you guys! Thanks a lot!

Given above advice, even if this is fixed (you can’t access result.length if result is null), can replace:


return result?.length ?? 0

“return the length property of result if it is accessible, if it is not (ie it is null), return 0”

1 Like

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