Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can somebody explain the logic of .indexOf() in Javascript?

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?

  • To my understanding if .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?
  • Again, in that case 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.

like image 606
Roma Kim Avatar asked Oct 22 '25 15:10

Roma Kim


2 Answers

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)

like image 102
smootok Avatar answered Oct 25 '25 03:10

smootok


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

like image 39
Preston PHX Avatar answered Oct 25 '25 04:10

Preston PHX