Back to blog

Functional Programming in JavaScript: Working with Array Mapping

Hello HaWkers! How are you?

Imagine that you need to change all the elements of an Array, applying the same function to each one. With JavaScript and functional programming, you can accomplish this task simply and elegantly using the .map() method. That's what we're going to learn in this post.

Advertisement

What is Array Mapping?

Array mapping is a technique that allows us to transform all the elements of an Array, creating a new Array with the transformed elements.

See this Array example:

const array = [1, 2, 3, 4, 5];

Now, if we want to create a new Array with the square of each number, we can use the .map() method for that.

How to work with the .map() method in JavaScript?

The .map() method is used to create a new Array, based on the original Array, where each element is transformed based on a provided callback function.

Let's see how we can use it to create an Array with the square of each number:

const array = [1, 2, 3, 4, 5];const squareArray = array.map(num => num * num);console.log(squareArray);// [1, 4, 9, 16, 25]

In this example, we are using an arrow function as a callback function, which takes each number (num) from the original Array and returns its square (num * num). As a result, the .map() method returns a new Array squareArray with the squares of each number.

Final considerations

The .map() method is a powerful tool for manipulating Arrays in JavaScript, allowing you to apply a function to each element of the Array in a simple and efficient way. Remember, however, that it does not modify the original Array, but creates a new one with the transformed elements.

I hope this post was useful to you. If you have any questions or suggestions, feel free to send me a direct message on Instagram.

And if you've already used the .map() method to transform elements of an Array, share your experience with me there too!

I'll always be on hand to help you on your programming journey!

To continue learning and improving your skills, check out the article on Building a REST API with Deno.js and Oak.

Advertisement

Let's go up! 🦅

Previous post Next post

Comments (0)

This article has no comments yet 😢. Be the first! 🚀🦅

Add comments