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
EasyCreate 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
})
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate Keys