Building Your Own map Method in JavaScript
JavaScript’s map
is a must-have tool when working with arrays. It allows us to transform an array by applying a function to each element, returning a new array with those transformed values. While using map
is easy, understanding how it works by building it yourself helps solidify your understanding of functional programming and array manipulation.
In this post, we’ll:
Build our own version of
map
.Explore how
map
helps create cleaner and more maintainable code.Walk through a real-world example of using
map
.
What map
Does
The map
method takes an array and returns a new array by transforming each element according to a callback function. Here’s what map
looks like in action:
const numbers = [1, 2, 3, 4, 5];
const squares = numbers.map(num => num ** 2);
console.log(squares); // Output: [1, 4, 9, 16, 25]
Here, map
applies num ** 2
to each item in numbers
and returns a new array of squares.
But how does map
actually work? Let’s recreate it from scratch.
Building map
from Scratch
To create map
, we need:
A result array to store the transformed elements.
A loop to go through each element in the array.
A way to apply a callback function to each element and store the result.
Here’s how our custom map
, which we’ll call myMap
, might look:
function myMap(array, callback) {
const result = [];
for (let i = 0; i < array.length; i++) {
result.push(callback(array[i], i, array));
}
return result;
}
How It Works:
Initialize
result
: This array will store the transformed elements.Loop through each element: We use a
for
loop to iterate througharray
.Apply the callback function: For each element,
callback
is executed, and its result is added toresult
.Return
result
: The function returns a new array with each element transformed bycallback
.
Testing myMap
Let’s test myMap
by using it to square each element in an array, like we did with map
:
const numbers = [1, 2, 3, 4, 5];
const squares = myMap(numbers, num => num ** 2);
console.log(squares); // Output: [1, 4, 9, 16, 25]
And that’s it! myMap
produces the same result as map
.
Real-World Example: Transforming Product Prices
Consider an e-commerce site where you need to adjust product prices based on a promotion. With map
, you can easily update the prices without modifying the original array.
const products = [
{ name: "Laptop", price: 1000 },
{ name: "Phone", price: 500 },
{ name: "Tablet", price: 750 }
];
const discountRate = 0.9; // 10% discount
const discountedPrices = products.map(product => ({
...product,
price: product.price * discountRate
}));
console.log(discountedPrices);
Explanation:
Original Array: Each item in
products
has aname
andprice
.Callback Function: We apply a 10% discount to each product’s price.
Result:
map
returns a new array,discountedPrices
, with the adjusted prices.
Using map
here keeps our code clear and focused on the transformation, without any need to modify the original data.
Why map
is So Powerful
Using map
not only shortens our code but also encourages a functional programming approach where data is transformed without mutation. This style of programming leads to:
More readable code: Focusing on what you want to achieve rather than how makes it easier to understand.
Cleaner, maintainable functions: The transformation logic stays isolated in one place.
Reusable logic: You can use the same mapping approach across different parts of your app.
Final Thoughts: Mastering map
Building map
from scratch helps us understand why it’s such a powerful and versatile tool in JavaScript. Now, when you use map
, you’ll know exactly how it works and why it’s an ideal choice for transforming data in a functional, readable way.
Try this yourself, and consider building reduce
or filter
from scratch to see how foundational array methods work!