Array Map
Array Map
You can use map to transform an array of strings to array of their lengths. Note the
explicit return inside the map() callback function.
In this example, we create a new array called lengths that contains the length of each
string in the original array.
const strings = ["apple", "banana", "cherry"];
const lengths = strings.map((str) => {
return str.length;
});
Key Points:
map()creates a new array (doesn't modify the original)- Each element is transformed by the callback function
- The callback must use explicit
returnwhen using curly braces{}
Array Map: Implicit Return
Callback function can be an arrow function with an implicit return.
Implicit return is a short syntax where the result of the expression is automatically returned without
using the return keyword or curly braces.
In this example, we create a new array called greetings that contains the greetings for
each student in the original array.
const students = [
{ name: "Alice", age: 20 },
{ name: "Bob", age: 22 }
];
const greetings = students.map(student => `hello, ${student.name}!`);
Key Points:
- Arrow functions can use implicit return for single expressions
- No curly braces
{}and noreturnkeyword needed - Implicit return is cleaner syntax but only works for single-line expressions
- If you need multiple statements, you must use curly braces and an explicit return
Array Map: Song Titles
Callback function can be a regular function with multiple statements.
In this example, we transform an array of strings that represent songs in the format
"Artist - Title"
into an array of just the titles. Here we assign the title to a new variable before returning it.
const songs = ["Daft Punk - One More Time", "Justice - Genesis"];
const titles = songs.map((song) => {
const artistAndTitle = song.split(" - ");
const title = artistAndTitle[1];
return title;
});
Key Points:
map()can handle complex transformations with multiple statements- When using multiple statements, curly braces and explicit
returnare required - Assigning intermediate variables makes code clearer, especially for explanations or debugging