![]() |
In this article, we will learn how to implement a polyfill for an Array.prototype.map() method in JavaScript. What is a polyfill? A polyfill is a piece of computer code written to implement a feature in a browser that does not yet support it. It could be because of the older version of the browser you are using, or because the new version of the browser does not have that feature.
What is Array.map() method? We will discuss the map() method supported by arrays in JavaScript, and implement our own version of it as well. The map() method calls a callback function for each of the array elements and returns a new array with the new values returned by the callback function. Syntax: // Arrow function map((element, index, array) => { /* … */ }) // Callback function map(callbackFn, thisArg) // Inline callback function map(function (element, index, array) { /* … */ }, thisArg) Parameters: This method accepts five parameters as mentioned above and described below:
Return value: This method returns a new array created by using the values modified by the arg_function using the value from the original array. This function does not modify the original array on which this function is implemented. Example: Javascript
Output: [2, 4, 6, 8] [3, 4, 5, 6 ] Now let’s create our own implementation of the Array.prototype.map method: Steps:
Javascript
Output: [0, 2, 6, 12] [3, 4, 5, 6] In the first example, a new array is created by multiplying each element of the original array with its respective index. And in the second example, a new array is created by adding 2 to each element of the original array. |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |