skip to Main Content

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


  1. 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 return 0 and it causes your if condition to look like this:

    if(0)
    

    Since 0 is "falsey" and therefore implicilty converts to the Boolean false, it turns out that words that start with "A" actually cause your if condition to evaluate as if it was written like this:

    if(false)
    

    And since false is never true, you don’t enter the true 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 Boolean true when implicitly converted, so you wind up entering the true branch of the if statement when words that DON’T start with "A" are encountered.

    We can see this by adding a little logging:

    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')) {
            // The following will show that your test is actually testing
            // for words that DON'T start with "A" (indexOf returns -1)
            console.log(currentAnimal, currentAnimal.indexOf('A'));
            countAnimals += 1
        }
      }
      
      console.log(countAnimals)

    You need to check the returned index to see if it is 0.

    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') === 0) {
            // By specifying that you need the index to be 0,
            // you get the correct words:
            console.log(currentAnimal, currentAnimal.indexOf('A'));
            countAnimals += 1
        }
      }
      
      console.log(countAnimals)

    You can also accomplish this using one of the Array.prototype methods, which are geared towards these kinds of operations:

    const animals = ['Alligator', 'Fox', 'Armadillo', 'Tiger', 'Anteater', 'Raccoon', 'Chicken', 'Sheep', 'Dog', 'Antelope', 'Albatross', 'Cat', 'Alpaca', 'Ape', 'Anaconda'];
    
    // Return a filtered array that only include words that start with "A" and get the length of tthat array.
    console.log((animals.filter(word => word.indexOf("A") === 0)).length);
    Login or Signup to reply.
  2. Actually, you are counting indices of -1 or other values from 1 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

    animals[i].indexOf('A') === 0
    

    or check the value at index directly

    animals[i][0] === 'A'
    

    or with String#startsWith

    animals[i].startsWith('A')
    
    const animals = ['Alligator', 'Fox', 'Armadillo', 'Tiger', 'Anteater', 'Raccoon', 'Chicken', 'Sheep', 'Dog', 'Antelope', 'Albatross', 'Cat', 'Alpaca', 'Ape', 'Anaconda'];
    
    for (let i = 0; i < animals.length; i++) {
        console.log(i, animals[i], animals[i].indexOf('A'))
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search