FAQ: Iterators - The .map() Method

I tried using this method and wrote my code like this:

const secretMessage = animals.map(animal => {

return animals.charAt[0]

Which I assumed would call the first letter from animals but it gives me an error.

I’m sure it something very simple but I just can’t seem to work this one out.

Remember to act upon the element in the iteration, not the array object, itself.


Given such a simple return value we can use implicit return and drop the curly braces. See my example.

Note also that charAt() is a method, not a subscriptable object.

Thanks for your help. This has raised another question for me though.

My understanding is that const animals = [‘Hen’, ‘elephant’, ‘llama’] these are my arrays with the name of the variable being animals.

So animal => this is the name of the function and the code to pass it as a function.

I don’t understand how I would pull through the first letter of animals using return animal[0] as animal is my function name.

1 Like

Those are the elements of the array. The name refers to the array, not the elements.

The function is anonymous and has no name, nor any need of one. animal is known as the function parameter. Since map is an iterator, it will iterate the object array, animals and perform an action on each element, animal.

Let’s examine the map method using ES5 syntax…

words.map(function (word) {
    return word.charAt(0)

Note there is no name given to the function (which is what anonymous means).

The new arrow syntax eliminates the function keyword but keeps the parameter container. When there is exactly one parameter we are permitted to drop the parentheses. We can also leave off the curly braces and the return keyword if our function body contains only one statement or expression.

1 Like

Thanks for that. I see where I went wrong with my understanding.

1 Like