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:
- The code in the
findIndex()
method will iterate through all items (designated in your code as animal
) in the animals
array.
- It will check each
animal
(item) to see if the first letter of each animal
(item) in animals
is lower case “s”.
- 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`);