map() - JavaScript Tutorial

map()

BLUF: This tutorial on map() provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: map()

Understanding map() is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

The map method in JavaScript arrays invokes a provided function on each element of the array and generates a new array as a result. Importantly, this method does not modify the original array in any way.

Syntax

The syntax for the map function is illustrated as follows:

Example

array.map(callback(currentvalue,index,arr),thisArg)

Parameter

callback - It denotes the function responsible for generating the new array.

currentvalue - The current element of array.

index - This parameter is not mandatory. It represents the position of the current element.

arr - This parameter is not mandatory. It refers to the array that the map function processes.

thisArg - This parameter is optional. It defines the value that will be utilized as 'this' during the execution of the callback function.

Return

An additional array is created where each element is derived from the output of a specified callback function.

JavaScript Array map method example

Let's see some examples of map method.

Example 1

In this context, the map function is utilized to round the specified elements to their closest integer value.

Example

<script>

var arr=[2.1,3.5,4.7];

var result=arr.map(Math.round);

document.writeln(result);

</script>

Output:

Example 2

In this instance, the map function produces a new array by taking each element from the specified array and multiplying it by 3.

Example

<script>

var arr=[2,4,6];

var result=arr.map(x=>x*3);

document.writeln(result);

</script>

Output:

Output

6,12,18

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience