Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Meg Dooley
Meg Dooley
7,321 Points

Understanding the //array.map() method in JavaScript

const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

const secretMessage = animals.map(animals => animals[0]);

console.log(secretMessage.join('')); 

Hi all,

Hoping you can help me to understand the above code which prints out "Helloworld" to the console. It works fine its just that I can't figure out why the parameter "animals" has to be the same as the array name. (to clarify, if I change the name to something else the code doesn't work properly). When I look at other examples of the map method this is not the case.

Please help me understand!

3 Answers

Hello Meg!

Actually, the name of parameter doesn't need to be the same of the variable. Please, try the below code:

const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

// In the next line it will apply the function to each of elements of animals array and return the first character
const secretMessage = animals.map(a => a[0]);

console.log(secretMessage.join('')); 

// Similar Approach:
/* 
 const secretMessage1 = animals.map(function (a) {return a[0];});
 console.log(secretMessage1.join('')); 
*/

Best Regards!

Meg Dooley
Meg Dooley
7,321 Points

ah hah! makes sense now thanks!

Dave StSomeWhere
Dave StSomeWhere
19,870 Points

The .map() method is method of the array - so it has to be animals.map() in your example - the same name as the array.

Could you please show one of the example where it is different.

Meg Dooley
Meg Dooley
7,321 Points
var array1 = [1, 4, 9, 16];

const map1 = array1.map(x => x * 2);

console.log(map1);

Here the parameter name is 'x' - in the example I gave above, the parameter name is the same os the array name and the code doesn't work if I change it.