Menu
Coddy logo textTech

The Map Method

Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 52 of 65.

The map() method creates a new array with the results of calling a provided function on every element in the calling array. It transforms each element and returns a new array of the same length.

Basic syntax:

let newArray = arr.map(function(currentValue, index, array) {
    // return element for newArray
});

Here's a simple example:

const numbers = [1, 2, 3, 4];
const doubled = numbers.map((num) => {
	return num * 2;
});
console.log(doubled); // [2, 4, 6, 8]

Here is the same example with a shorter syntax:

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]

The map() method doesn't change the original array. It always returns a new array.

challenge icon

Challenge

Easy

Create a function called formatNames that takes an array of names (strings) as an argument. The function should use the map() method to transform each name so that it's in title case (first letter of each word capitalized, rest lowercase). Return the new array of formatted names.

Cheat sheet

The map() method creates a new array by calling a function on every element in the original array:

let newArray = arr.map(function(currentValue, index, array) {
    // return element for newArray
});

Example with arrow function:

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]

The map() method doesn't change the original array and always returns a new array of the same length.

Try it yourself

function formatNames(names) {
    return names.map(name => {
        // Write your code here
    })
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow