# forEach() vs map() in JavaScript

## Map() function

In JavaScript, the map function is a higher-order function that is used to create a new array by applying a provided function to each element of an existing array. The original array remains unchanged. The map function takes a callback function as its argument, and this callback function is applied to each element of the array.

**Here's a basic syntax for the map() function**:

`let newArray =` [`originalArray.map`](http://originalArray.map)`(callbackFunction);`

**Square of each elelment of an array**

![arrow](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x6iaupuycdkznunpnvs2.png align="left")

**You can also use arrow functions for a more concise syntax:**

![arrow function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7g63t5qmyn5fszldl9ic.png align="left")

## forEach() method

In JavaScript, the forEach method is used to iterate over elements in an array. It provides a concise way to loop through each element of an array and perform a specified operation for each element.

**Here's a basic syntax of the forEach() method:**

`array.forEach(function(currentValue, index, array){ // Your code here});`

**Here's an example:**

![forEach()function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6qbfgxbib2wuv5g51qmp.png align="left")

**What happen if we try to modify the array using forEach()**

![Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x2ykvyubo22kp6h3phax.png align="left")

*The output Will be undefined.*

**Correct approach of doing it.**

![array](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sp9tvz3fxu4r33e8g0jz.png align="left")

**When to use which**

Your use case will determine whether to use `map()` or `forEach()`. The `map()` provides a new array containing the transformed data, thus you should use it if you intend to modify, alternate, or use the data.But instead of using `map()`, use `forEach()` if you won’t require the resulting array.
