What does animal[0] do?

Yes you explained it very well. Although I want to add that you don’t even need that ? true : false ternary expression because a condition always will evaluate to either true or false.

So writing:

const startsWithS = animals.findIndex(a => a[0] === 's');

is perfectly fine.


In the scope of the code you used for this exercise, the confusion lies in part in the variable name you (and perhaps @praveends0114195538) chose to represent each item in the animals array.

You chose animal to represent the items, as so:

const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];
const startsWithS = animals.findIndex(animal => animal[0] === `s`); // This is effectively the same as your code

As you probably know, animals[0] returns ‘hippo’.

* Note: the above is plural animals (i.e. the array provided by the exercise), not singular animal (the variable name you designated to represent the items in the animals array).

Next, lets think about what findIndex() does:

  1. The code in the findIndex() method will iterate through all items (designated in your code as animal) in the animals array.
  2. It will check each animal (item) to see if the first letter of each animal (item) in animals is lower case “s”.
  3. If/when it finds that test to be true, it will return the index number of the first animal (item) where the first letter in the item is “s” (in this case, index 3 [“seal”]).

To better understand, lets pull out “seal”, and set it to animal.

let animal = `seal`;
return animal[0] //=> s (the first letter of 'seal')

As others have said already, strings are array-like objects. That is, you can access the letters in a string in the same way you can access items in an index.

tl;dr animal[0] is not the same thing as animals[0].

Using animal to represent the items in the animals index makes sense, but it leads to confusion. Change animal out for another designator such as str, as so:

const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];
const startsWithS = animals.findIndex(str => str[0] === `s`);

I can understand this being very confusing in the beginning, but animal is more descriptive then str.

1 Like

Strings can be treated as an array, and since the first character is to be evaluated, the index [0] of each of the elements is taken.

So would it help if we expanded the code a bit?
this is how I understood it :

const startsWithS = animals.findIndex ( function(animal) {
return animal[0] === ‘s’;
where we pass animal through the callback function and it looks at the first index of each animal for a lower case ‘s’ until it returns a ‘true’ statement?

exactly :slight_smile:

1 Like