Skip to content

Edvins Antonovs

How to implement your version of in JavaScript

Implementing your version of popular JavaScript functions is a fairly trivial interview question, so to prepare for it, I decided to implement all of them on my own as a part of the interview process. is a starting point in the series. The next ones in the queue are Array.filter() and Array.reduce().

What is

To begin with, let’s first figure out what is. is a built-in JavaScript function for array manipulations and transformations based on the existing array. iterates each element of the existing array and applies a callback function for each element. doesn't mutate the original array. Instead, it returns a new one.

1const arr = [1, 2, 3];
3const doubled = => elem * 2);
6// Output: [2, 4, 6]

Implementing your version of

Now, let’s implement myMap() function, which will act as your replacement.

The myMap() function takes an arr (array) and a cb (callback) function as arguments. It returns a new array that results from applying the callback function to each input array element.

1const myMap = (arr, cb) => {
2 let temp = [];
4 for (let i = 0; i < arr.length; i++) {
5 if (arr.hasOwnProperty(i)) {
6 temp.push(cb(arr[i]));
7 }
8 }
10 return temp;

Let’s quickly go through the code to figure out what it does.

We start by creating a new empty array temp

1let temp = [];

Then we loop through each element of the input array arr

1for (let i = 0; i < arr.length; i++) {
2 // loop code

We do `hasOwnProperty`` check ensures that the callback is only executed on elements that actually exist in the array, and it won't be invoked for undefined elements or holes in the array.

1if (arr.hasOwnProperty(i)) {
2 ...

Inside the loop, it applies the callback function cb to the current element of the input array arr[i]. Finally, the result is pushed into a temporary array temp.


After we finish with the loop, we return the temp array.

1return temp;

That's it! Now you can use myMap() as an alternative replacement to the existing function.

1const arr = [1, 2, 3];
3const doubled = myMap(arr, (elem) => elem * 2);
6// Output: [2, 4, 6]


© 2023 by Edvins Antonovs. All rights reserved.