Why it prints undefined?

Hello,

When doing this exercise: https://www.codecademy.com/courses/introduction-to-javascript/lessons/javascript-iterators/exercises/find-index

I have this code:

const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];

const foundAnimal = animals.findIndex(i => {

return i === 'elephant';

})

console.log(foundAnimal);

const startsWithS = animals.findIndex(i => {

return i [0] === 's';

})

console.log(startsWithS);

console.log(foundAnimal[animals]);

console.log(startsWithS[animals]);

I would like to know why when I print the foundAnimal and the startsWithS it gives me undefined on the console. Shouldn’t it give me Elephant and Seal?

The exercise is correct but I wanted to print it just to see what it would do.
Thanks

1 Like

the syntax to access an array by index is:

array[index]

you seem to do the reverse? Not sure how to express that in words.

Hey there! Welcome to the community, @juansito22.

Just like @stetim94 said:

In these two lines:

console.log(foundAnimal[animals]);

console.log(startsWithS[animals]);

The array is animals, and foundAnimal and startsWithS are variables that contain the indexes to the ‘elephant’ element and the first element that starts with ‘s’, respectively.
Therefore, this is what you should be doing:

console.log(animals[foundAnimal]);

console.log(animals[startsWithS]);

Hope this helped! :upside_down_face:

Oh I see it now. Thanks for the help!

No problem :relaxed: