LearnJavaScript Array Methods: map()

Dustin Usey

Dustin Usey
writes on November 14, 2022

Still using a for loop to iterate over a collection of array elements? Try out this javascript array method known as map() instead!

What is map()? Accordion the MDN documentation, the map() method creates a new array populated with the results of calling a provided function on every element in the calling array. What exactly does all of that mean, though? Let’s break it down.

Consider the following array:

const colors = ['red', 'blue', 'green'];

If we wanted to log each array element to the console, we’d normally write something like this with a standard for loop:

for (let i = 0; i < colors.length; i++) {
    console.log(colors[i]);
}
// expected output: 'red'
// expected output: 'blue'
// expected output: 'green'

While nothing is wrong with the above code, there is a better way to write that. Using the map() method, we could just write:

colors.map(color => console.log(color));

// expected output: 'red'
// expected output: 'blue'
// expected output: 'green'

Pretty simple right? You might be slightly confused as to where this color word came from though. If we checkout the parameters we are able to use with this method in the MDN documentation, you’ll see a parameter called element. Accordion to MDN, ‘element’ is the current element being processed in the array. Basically, this element parameter is a variable that holds the value of each element in the array. You can name this anything you’d like. I called this parameter color in the above example.

I know what you’re thinking, what’s the difference between just running a for loop? Or even using the forEach method. Both options work exactly the same. So what’s the difference? Well, map() actually does one thing differently. Lets look at the definition again.

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

MDN – map() JavaScript Array Method

The difference with map() is that it creates and returns a brand new array. So we can actually run some logic in our function and store it in a variable as a new array. Check this out:

const colors = ['red', 'blue', 'green'];

const colorsUpperCase = colors.map(color => color.toUpperCase());
console.log(colorsUpperCase)

//expected output: ['RED', 'BLUE', 'GREEN']

I hope this quick guide on using the map() method was helpful and you can comfortably use this in your javascript like a pro going forward!

GET STARTED NOW

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Get Started

Leave a Reply

You must be logged in to post a comment.

man working on his laptop

Are you ready to start learning?

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Start a Free Trial
woman working on her laptop