+ 1

How do I return -1 using match() method if a search is not found?

//Write a JavaScript function that accepts a string as a parameter and counts the number of vowels within the string. function countVowels(string) { var vowels = [], regEx = /[aeiou]/gi, counter = 0; if(string === undefined) string = ''; vowels = string.match(regEx); counter = vowels.length; return vowels === null ? -1 : counter; } console.log('The quick brown fox') // logs 5 But I want the output to be -1 if a vowel is not found in the string. I have tried to use an if else statement like this: if(counter > 0) return counter; else return -1; // This doesn't work too. Outputs a blank screen I don't know if it is because of the match() method I used. I googled the return value of the match() method if no match is found and it is 'null'. That is why I used it in my code above: return vowel === null ? -1 : counter; //outputs a blank screen but it still doesn't work. What's the problem?

27th Oct 2020, 9:03 AM
Logos
Logos - avatar
5 Respostas
+ 5
You can also use the optional chaining(?.) operator. counter = vowel?.length So instead of getting an error message because of null, undefined is returned. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining Nullish coalescing operator (??) can also be used in concert with the optional chaining operator. To make code more concise. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
27th Oct 2020, 11:38 AM
ODLNT
ODLNT - avatar
+ 2
The problem is that when there is no vowels you cant assign a value to counter thus it will throw an error. This would work function countVowels(string) { var vowels = [], regEx = /[aeiou]/gi, if(string === undefined) string = ''; vowels = string.match(regEx); return vowels === null ? -1 : vowels.length;
27th Oct 2020, 9:42 AM
C K
C K - avatar
27th Oct 2020, 9:21 AM
C K
C K - avatar
+ 1
C K Thanks for your explanation. I understand now.
27th Oct 2020, 5:02 PM
Logos
Logos - avatar
+ 1
ODLNT I looked up the link you sent. It was very resourceful. I have a better understanding of how optional chaining and nullish coalescing operators works now. Thank you.
27th Oct 2020, 5:04 PM
Logos
Logos - avatar