Start learning free

LESSON 140 OF 161 · FRONTEND: INTERVIEW QUESTIONS

Write Array.prototype.map in JavaScript

Practice

map makes a new array: it calls a function on each item and puts each answer at the same index. In interviews you are often asked to write it yourself, without .map, to show you know its details.

Three details matter. fn gets three arguments: the item, its index and the whole array. A hole, a slot that was never set, like the middle of [1, , 3], stays a hole, and fn is not called for it. And the original array never changes.

Here is the real map on other values:

[4, 5].map((n, i) => n + i);   // [ 4, 6 ]
[2, , 4].map((n) => n * 2);    // [ 4, <1 empty item>, 8 ]

Then you give every array the method. A function stored on Array.prototype can be called as [1, 2].myMap(fn), and inside it, this is the array before the dot. The check prints, among others:

myMap([12, 7, 29], (price) => "$" + price)
  result: [ '$12', '$7', '$29' ]
myMap(array, fn) with array = [1, , 3, ,], fn = (n) => n * 10
  fn(1, 0, array) returns 10
  fn(3, 2, array) returns 30
  result: [ 10, <1 empty item>, 30, <1 empty item> ]
[5, , 7].myMap((n) => n + 1)
  result: [ 6, <1 empty item>, 8 ]

Your task: write myMap(array, fn) without using .map, then add Array.prototype.myMap(fn), which does the same for the array it is called on.


Assignment
Follow the Coding Tutorial to build myMap with a loop over the indexes that skips the holes, then add it as a method of every array.


Hint
new Array(n) starts as n holes, so a slot you skip stays a hole. i in array is false only for a hole. Write the method with function, not an arrow function, so it gets its own this.


STEP 1 OF 7
    Ctrl + Enter to check

    Fe Array Map in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free