I’m trying to code a loop which counts the amount of strings within the variable ‘animals’ that begin with an ‘A’. There are 8, but the console only logs 7 and I’m not sure why.
const animals = ['Alligator', 'Fox', 'Armadillo', 'Tiger', 'Anteater', 'Raccoon', 'Chicken', 'Sheep', 'Dog', 'Antelope', 'Albatross', 'Cat', 'Alpaca', 'Ape', 'Anaconda'];
let countAnimals = 0;
for (let i = 0; i < animals.length; i++) {
const currentAnimal = animals[i]
if (currentAnimal.indexOf('A')) {
countAnimals += 1
}
}
console.log(countAnimals)
2
Answers
Your loop is actually counting the words that don’t start with "A". This is because when you have a word that does start with "A",
indexOf("A")
will return0
and it causes yourif
condition to look like this:Since
0
is "falsey" and therefore implicilty converts to the Booleanfalse
, it turns out that words that start with "A" actually cause yourif
condition to evaluate as if it was written like this:And since
false
is nevertrue
, you don’t enter thetrue
branch with words that start with "A", however with any other word that doesn’t start with "A", you will get a non-zero number back and non-zero numbers are "truthy" and convert to the Booleantrue
when implicitly converted, so you wind up entering thetrue
branch of theif
statement when words that DON’T start with "A" are encountered.We can see this by adding a little logging:
You need to check the returned index to see if it is 0.
You can also accomplish this using one of the Array.prototype methods, which are geared towards these kinds of operations:
Actually, you are counting indices of
-1
or other values from1
or greater.String#indexOf
returns-1
for not found or the index of the found substring.To overcome this, you need to check with zero
or check the value at index directly
or with
String#startsWith