Why when using the indexOf method must the condition be equal 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]);
}
}
The method
indexOf
returns the position in the string of the first occurrence of the value passed as a parameter (in this case"A"
).If no occurrence is found, it returns a value of
-1
0
would indicate that there is an occurrence in the first position (first character) of the string,1
that it exists in the second position (second character),2
in the third, etc.In this way if the string begins with it
"A"
will return a value of0
and if it does not it will return a different value.More information: String.prototype.indexOf
The indexOf function returns the first index that contains a letter (in your case A). if it has no value it will return -1
Javascript has another way and you don't have to do a for , using the Filter method
Because indexOf is governed by the first letter in your example you want "A" as the first letter, other cases would be for example:
This is why if you are looking for words that begin with a certain letter , you should check position 0 of the string, which is the letter that it begins with.
If you use a second parameter you will specify where to start parsing the string, for example:
Strings are an array of characters whose indices start at 0, if you want to know if a string starts with a specific letter you must check its first occurrence, that is, index 0.