JS interview: Implement map function

Photo by Shahadat Rahman on Unsplash

As a JavaScript developer, we frequently deal with operations on Array. JavaScript allows us to use declarative style where we can tell what to do and not how to do i.e. there are functions like map, reduce, filter etc. that work on each item of the Array and return the result. The underlying business logic how these functions work on data is black box to the caller of these functions.

In this story, we will see how many ways we can implement the Array map function i.e. mimic the JavaScript map function in a way that it will give same output as the original JavaScript map function.

Imperative way

  • We have overridden the map function in Array class using the prototype in JavaScript.
  • We are using a for loop in myMapFunction which is we are instructing that how to do the work i.e. Imperative way.

The async callback argument can also be used in map function like below:-

Declarative way using Array reduce function

So now we know how the Array map function works. Surely, the declarative way of doing things makes your code less buggy as you don’t need to know how things work under the hood, it’s only you need to tell what needs to be done.

If this post was helpful, please click the clap 👏 button below a few times to show your support! ⬇⬇

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store