Trouble With .forEach Iterator

Hello, whilst completing the “.findIndex” lesson in javaScript, I wanted to see if I could use the .forEach function in order to take the provided array, “animals,” and create another array which lists off only the animals that start with the letter ‘s’.

const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant']; const animalsWithS = animals.forEach(animal => { if (animal[0] === 's') { return animal }; }); console.log(animalsWithS);

Could anyone let me know I’m doing wrong in this case? When I log the result to the console, it returns “undefined.” I already know that there are ways to achieve this goal with the for loops, but I wanted to know if this was possible to achieve with .forEach.

Any help is appreciated. Thanks!

Array.forEach() will always return undefined. We use the iterator to perform an action on every element in an array. Assigning it is meaningless.


Perhaps .forEach() is not the iterator to use in this instance. We want all the values that start with s. Sounds like a job for Array.filter(). That will return an array.

1 Like