A function or method is a sub-program. It is comprised of a series of codes called the function body. Some values get passed to a function or method, and then the function/method returns a value.
There are many inbuilt functions and methods in Javascript. In this article, we'll learn about the map() method in JavaScript, its definition and uses with some code snippets.
Definition of the map() method
The map() method calls a specific function on each element of an array and stores the result in a new array. It is an immutable method that loops through an array calling a function on every element/item of an array.
Syntax:
array.map(function(currentValue, index, arr), thisValue)
Parameters: The map() method accepts two parameters, Below is the description of these parameters:
- function(currentValue, index, array): This function runs over every element of the entered array. It holds three parameters. They are
- currentValue: It holds the value of the existing element/item of the array.
- Index: It holds the current element's index and is optional.
- Array: It holds the entered array and is optional.
2. thisValue: This parameter keeps the passed value. It can be optional.
Return Value: It returns a new array. The elements of this new array are the outcome of a callback function.
The below examples illustrate the use of the array map() method in JavaScript:
Example 1: Returns the square of the array element using the map() method.
Code:
<html>
<head>
</head>
<body>
<div id="JDR"></div>
<script>
var el = document.getElementById('JDR');
var array = [5, 3, 5, 8, 2, 9];
var newArray = array.map(function(value, ind){
return {The_key:ind, The_value:value*value};
})
console.log(newArray)
el.innerHTML = JSON.stringify(newArray);
</script>
</body>
</html>
Output:
Example 2: Concatenates the letter S with every character.
Code:
<!doctype html>
<html>
<head>
</head>
<body>
<div id="root"></div>
<script>
var el = document.getElementById('root');
var name = "Pankaj";
// New array of characters concatenated with 'S',
var newName = Array.prototype.map.call(name, function(item) {
return item + 'S';
})
console.log(newName);
document.write('String: ' + name);
document.write('<br>Array: ' + newName);
</script>
</body>
</html>
Output:
Methods similar to map()- foreach(), reduce(), filter()
There are some other methods in JavaScript that are similar to the map() method. Below is their description with an example:
foreach()
The foreach() method executes a given or provided function once on each element or item in the array. This method doesn't get executed if there are empty elements.
Syntax:
array.forEach(function(currentValue, index, arr), thisValue)
Example:
Code:
<!doctype html>
<html>
<head>
<title>map() method in JavaScript</title>
</head>
<body>
<h2>The forEach() Method</h2>
<p>forEach() calls a function for each element in an array:</p>
<p id="demo"></p>
<script>
let text = "";
const fruits = ["apple","Pineapple", "orange", "Guava", "cherry", "Banana",];
fruits.forEach(myFunction);
document.getElementById("demo").innerHTML = text;
function myFunction(item, index) {
text += index + ": " + item + "<br>";
}
</script>
</body>
</html>
Output:
reduce()
The reduce() method executes a reducer function for the array element. It returns a value that is the accumulated outcome of the defined function. The reduce() method does not perform or execute the function for empty array elements. It doesn't alter the original array.
Code:
<html>
<head>
<title>map() method in JavaScript</title>
</head>
<body>
<p>Subtract the numbers in the array, starting from the left:</p>
<p id="demo"></p>
<script>
const numbers = [175, 50, 25, 5, 2];
document.getElementById("demo").innerHTML = numbers.reduce(myFunc);
function myFunc(total, num){
return total - num;
}
</script>
</body>
</html>
Output:
filter()
The filter() method creates a new array filled with elements that pass a test provided by a function. This method does not execute the function for empty elements. The filter() method does not alter the initial array.l
Code:
<html>
<head>
<title>map() method in JavaScript</title>
</head>
<body>
<p>Get every element in the array that has a value of 18 or more:</p>
<p id="demo"></p>
<script>
const ages = [32, 33, 16, 40, 17, 45, 12];
document.getElementById("demo").innerHTML = ages.filter(checkAdult);
function checkAdult(age) {
return age >= 18;
}
</script>
</body>
</html>
Output:
Conclusion:
In the above article, we’ve read about an inbuilt JavaScript method- map() method. It calls a specific function on each element of an array. There are some other methods that are similar to the map() method. They are:
- reduce(): This method executes a reducer function for the array elements.
- filter(): This method creates a new array filled with elements that pass a given condition.
- foreach(): This method executes a given or provided function once on each element.