From the course: Learning Functional Programming with JavaScript ES6+

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Solution: Recreate the map function

Solution: Recreate the map function - JavaScript Tutorial

From the course: Learning Functional Programming with JavaScript ES6+

Start my 1-month free trial

Solution: Recreate the map function

(upbeat music) - [Instructor] Okay, so let's take a look at two possible solutions to the challenge of recreating the map function in JavaScript. We'll start with one of the easier possible solutions of using a for loop. Inside our function body, the first thing we want to do is define a new array so that we don't mutate the array that we pass into our function. That would go against functional programming's core tenet of immutability. So, let's write let since we'll be modifying this variable and newArray and the initial value will just be an empty array. And what we want to do now is iterate through all the elements in our array using the old index method from procedural programming. So, we'll write for let i for index equal zero, i is less than array.length and i++. And for each element in our array, we want to get the value of the result that we get when we call our function argument on the element and that'll look like this. Const result equals func array index i. And then we…

Contents