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

I'm a little confused with the .map function. Any help?

I am confused how to write and what the .map function in JavaScript is. Please help!

1 Answer

andren
andren
28,558 Points

The map function takes the contents of an array and then run each item though a function that you pass it, then creates a new list where each of the items have been changed to whatever was returned from the function that had the item passed in.

I think it's easier to illustrate it's use though examples.

function timesTwo(number) {
    return number * 2;
}

let evenNumberArray = [2,4,6,8,10];

let newArray = evenNumberArray.map(timesTwo);

console.log(newArray);
// Prints: [ 4, 8, 12, 16, 20 ]

In that example I define a function that simply multiplies a number by two, then I use .map and pass all the numbers of the array though that function. The result is a new array where each of the numbers in the evenNumberArray has been multiplied by two. You can of course also pass in an anonymous function into the map function rather than a previously declared one like I do above.

The above code is equivalent in behavior to this code:

function timesTwo(number) {
    return number * 2;
}

let evenNumberArray = [2,4,6,8,10];
let newArray = [];
for (let i = 0; i < evenNumberArray.length; i++) {
    newArray.push(timesTwo(evenNumberArray[i]));
}

console.log(newArray);
// Prints: [ 4, 8, 12, 16, 20 ]

Which takes each item in the array and pushes the result of passing that item into another function to a new array. .map is just a shorter and more convenient way of transforming a list in this type of way.