


Detailed introduction to the difference between Map and ForEach in JS
This article gives you a detailed analysis of the differences between Map and ForEach in JS and the differences in usage. Friends who are interested in this can learn it.
If you already have experience using JavaScript, you may already know these two seemingly identical methods: Array.prototype.map() and Array.prototype.forEach().
So, what is the difference between them?
Definition
Let’s first take a look at the definitions of Map and ForEach on MDN:
forEach(): executes a provided function for each element function once for each array element).
map(): Creates a new array with the results of calling a provided function for each element in the array. on every element in the calling array).
What is the difference? The forEach() method does not return the execution result, but undefined. In other words, forEach() will modify the original array. The map() method will get a new array and return it.
Example
An array is provided below. If we want to double each element in it, we can use map and forEach to achieve the goal.
let arr = [1, 2, 3, 4, 5];
ForEach
Note that forEach will not return a meaningful value.
We directly modify the value of arr in the callback function.
arr.forEach((num, index) => { return arr[index] = num * 2; });
The execution results are as follows:
// arr = [2, 4, 6, 8, 10]
Map
let doubled = arr.map(num => { return num * 2; });
The execution results are as follows:
// doubled = [2, 4, 6, 8, 10]
Execution speed comparison
jsPref is a very good website for comparing the execution speed of different JavaScript functions.
Here are the test results of forEach() and map():
As you can see, the execution speed of forEach() on my computer is map() is 70% slower. The execution results of everyone's browser will be different. You can use the following link to test it out: Map vs. forEach - jsPref.
JavaScript is so flexible (gui) and flexible (yi) that you don’t even know if there is a bug. You might as well connect to Fundebug for online real-time monitoring.
Understanding from a functional perspective
If you are used to using functions for programming, then you will definitely like to use map(). Because forEach() will change the value of the original array, and map() will return a brand new array, the original array will not be affected.
Which one is better?
Depends on what you want to do.
forEach is suitable when you don't plan to change the data, but just want to do something with the data - such as saving it to a database or printing it out.
let arr = ['a', 'b', 'c', 'd']; arr.forEach((letter) => { console.log(letter); }); // a // b // c // d
map() is suitable when you want to change the data value. Not only is it faster, but it returns a new array. The advantage of this is that you can use composition (combination of map(), filter(), reduce(), etc.) to create more tricks.
let arr = [1, 2, 3, 4, 5]; let arr2 = arr.map(num => num * 2).filter(num => num > 5); // arr2 = [6, 8, 10]
We first use map to multiply each element by 2, and then filter out those elements greater than 5. The final result is assigned to arr2.
Core Points
What can be done with forEach(), map() can also be used. The reverse is also true.
map() will allocate memory space to store the new array and return it, while forEach() will not return data.
forEach() allows the callback to change the elements of the original array. map() returns a new array.
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
jQuery ajax reads json and sorts in detail
jsWhat steps are needed to obtain ModelAndView
JS implements the function of exchanging left and right lists
The above is the detailed content of Detailed introduction to the difference between Map and ForEach in JS. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Users may have seen the term wapi when using the Internet, but for some people they definitely don’t know what wapi is. The following is a detailed introduction to help those who don’t know to understand. What is wapi: Answer: wapi is the infrastructure for wireless LAN authentication and confidentiality. This is like functions such as infrared and Bluetooth, which are generally covered near places such as office buildings. Basically they are owned by a small department, so the scope of this function is only a few kilometers. Related introduction to wapi: 1. Wapi is a transmission protocol in wireless LAN. 2. This technology can avoid the problems of narrow-band communication and enable better communication. 3. Only one code is needed to transmit the signal

Pubg, also known as PlayerUnknown's Battlegrounds, is a very classic shooting battle royale game that has attracted a lot of players since its popularity in 2016. After the recent launch of win11 system, many players want to play it on win11. Let's follow the editor to see if win11 can play pubg. Can win11 play pubg? Answer: Win11 can play pubg. 1. At the beginning of win11, because win11 needed to enable tpm, many players were banned from pubg. 2. However, based on player feedback, Blue Hole has solved this problem, and now you can play pubg normally in win11. 3. If you meet a pub

i5 is a series of processors owned by Intel. It has various versions of the 11th generation i5, and each generation has different performance. Therefore, whether the i5 processor can install win11 depends on which generation of the processor it is. Let’s follow the editor to learn about it separately. Can i5 processor be installed with win11: Answer: i5 processor can be installed with win11. 1. The eighth-generation and subsequent i51, eighth-generation and subsequent i5 processors can meet Microsoft’s minimum configuration requirements. 2. Therefore, we only need to enter the Microsoft website and download a "Win11 Installation Assistant" 3. After the download is completed, run the installation assistant and follow the prompts to install Win11. 2. i51 before the eighth generation and after the eighth generation

After updating to the latest win11, many users find that the sound of their system has changed slightly, but they don’t know how to adjust it. So today, this site brings you an introduction to the latest win11 sound adjustment method for your computer. It is not difficult to operate. And the choices are diverse, come and download and try them out. How to adjust the sound of the latest computer system Windows 11 1. First, right-click the sound icon in the lower right corner of the desktop and select "Playback Settings". 2. Then enter settings and click "Speaker" in the playback bar. 3. Then click "Properties" on the lower right. 4. Click the "Enhance" option bar in the properties. 5. At this time, if the √ in front of "Disable all sound effects" is checked, cancel it. 6. After that, you can select the sound effects below to set and click

This article will explain in detail how PHP returns an array after key value flipping. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP Key Value Flip Array Key value flip is an operation on an array that swaps the keys and values in the array to generate a new array with the original key as the value and the original value as the key. Implementation method In PHP, you can perform key-value flipping of an array through the following methods: array_flip() function: The array_flip() function is specially used for key-value flipping operations. It receives an array as argument and returns a new array with the keys and values swapped. $original_array=[

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Dogecoin is a cryptocurrency created based on Internet memes, with no fixed supply cap, fast transaction times, low transaction fees, and a large meme community. Uses include small transactions, tips, and charitable donations. However, its unlimited supply, market volatility, and status as a joke coin also bring risks and concerns. What is Dogecoin? Dogecoin is a cryptocurrency created based on internet memes and jokes. Origin and History: Dogecoin was created in December 2013 by two software engineers, Billy Markus and Jackson Palmer. Inspired by the then-popular "Doge" meme, a comical photo featuring a Shiba Inu with broken English. Features and Benefits: Unlimited Supply: Unlike other cryptocurrencies such as Bitcoin

Many users have printer drivers installed on their computers but don't know how to find them. Therefore, today I bring you a detailed introduction to the location of the printer driver in the computer. For those who don’t know yet, let’s take a look at where to find the printer driver. When rewriting content without changing the original meaning, you need to The language is rewritten to Chinese, and the original sentence does not need to appear. First, it is recommended to use third-party software to search. 2. Find "Toolbox" in the upper right corner. 3. Find and click "Device Manager" below. Rewritten sentence: 3. Find and click "Device Manager" at the bottom 4. Then open "Print Queue" and find your printer device. This time it is your printer name and model. 5. Right-click the printer device and you can update or uninstall it.
