function vowelsAndConsonants(s) {
var vowels = ['a','e','i','o','u'];
for(let i =0; i<s.length; i++){
if(vowels.indexOf(s[i]) > -1 ){
console.log(s[i]);
}
}
for(let j = 0; j<s.length; j++){
if(vowels.indexOf(s[j]) < 0){
console.log(s[j]);
}
}
}
The code above prints out the vowels and then consonants of an input.
I have troubles understanding how .indexOf()specifically works in this case.
I understand that .indexOf() searches array and returns the position of an element you're looking for, but why does the following condition if(vowels.indexOf(s[i]) > -1) only returns vowels?
.indexOf() returns -1 it means that no
match was found. In the case, would if(vowels.indexOf(s[i]) > -1)
mean that if a match is found we should execute the code, since it is greater than -1?if(vowels.indexOf(s[j]) < 0) would then mean
that if a match is not found execute whatever is inside the if
statement.Could somebody kindly explain the logic and give a simple example? I think I'm getting the logic, but at the same time I think I'm not.
indexOf function searches in the array of vowels.
If it finds a value it will return it's index, so the result will be greater than -1.
And if it doesn't find it, the result will be -1.
But it's better to use
if(vowels.indexOf(s[j]) === -1) instead of
if(vowels.indexOf(s[j]) < 0)
Unless you also actually need to know an indexOf result in order to do something with it, in modern JS it is preferable to use .includes() rather than testing against -1 or 0.
.includes() is simply more legible
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With