javascript – Understanding the indexOf

Question:

Because when using the indexOf method, must the condition be set to 0 to find the words that start with "A"?

 let teachers =["Alexys", "Jon", "Daniel", "Francisco", "Rafa", "José", "Alvaro"]; for (i = 0; i < teachers.length; i++) { if (teachers[i].toUpperCase().indexOf("A") == 0) { console.log(teachers[i]); } }

Answer:

The indexOf method returns the position in the string of the first occurrence of the value passed as a parameter (in this case "A" ).

If it does not find any occurrence, it returns a value of -1

0 would indicate that an occurrence exists in the first position (first character) of the string, 1 that exists in the second position (second character), 2 in the third, etc.

In this way, if the string begins with "A" return a value of 0 and if it does not, it will return a different value.

More information: String.prototype.indexOf

Scroll to Top