.map()
Anonymous contributor
Published Jun 21, 2021Updated Jun 8, 2023
Contribute to Docs
Creates a new array with the results of calling a function for every element in array.
Syntax
array.map((element, index, array) => {...});
The callback function accepts the following parameters:
element
(required): The current element we are iterating through.index
(optional): The index of the current element we are iterating through.array
(optional): The array that.map()
was called on.
Examples
Create a new array which doubles the values in numbers
:
const numbers = [1, 2, 3, 4, 5];const doubled = numbers.map((value) => value * 2);console.log(doubled);// Output: [2, 4, 6, 8, 10]
Create an array of full names from the students
array full of objects:
const students = [{ first_name: 'Samantha', last_name: 'Jones' },{ first_name: 'Hector', last_name: 'Gonzales' },{ first_name: 'Jeremiah', last_name: 'Duncan' },];const fullNames = students.map((student) => {return `${student.first_name} ${student.last_name}`;});console.log(fullNames);// Output: ['Samantha Jones', 'Hector Gonzales', 'Jeremiah Duncan']
Codebyte Example
The example below defines a new array teachers
. Next, the results of the .map()
method are stored in a new variable, array courses
. Finally, the items of the courses
array are logged to the console.
All contributors
- Anonymous contributor
- Anonymous contributor
- Christine_Yang
- christian.dinh
- Anonymous contributor
- robgmerrill
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours