DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk3 min

JavaScript map() vs forEach(): Which Should You Use?

Use map() to turn array elements into a new array; use forEach() for actions that do not need a returned array. For early exit or awaited work, use a different control flow.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use map() when each array element should produce a value in a new array you plan to use. Use forEach() when you want to perform an action for each element and do not need a result array. Neither method is the right choice when you need to stop early or await asynchronous work.

How to choose between map() and forEach()

  • Transform data into a new array: use map(). Its callback return value becomes the corresponding value in the returned array.
  • Perform an action for each element: use forEach() when you do not need a returned array, such as logging or updating existing objects.
  • Stop early or manage asynchronous work: use a loop or a method suited to that control flow instead. Neither method awaits callback promises, and forEach() cannot be stopped with break.

What each method returns

Question map() forEach()
Purpose Transform each visited element into an output value. Run an action for each visited element.
Method return value A new array containing callback results. undefined; callback return values are discarded.
Callback returns nothing The output position contains undefined. The callback result is discarded.
Empty slots in a sparse array Skipped, with corresponding holes preserved in the output. Skipped.
Early exit Not an early-exit method. No native break.
Async callback Does not wait for returned promises. Does not wait for returned promises.

Use map() when you need transformed values

Each callback result becomes an element in a new array. For example:

As an Amazon Associate I earn from qualifying purchases.

const prices = [10, 20, 30];
const withTax = prices.map((price) => price * 1.2);
// withTax is a new array: [12, 24, 36]

If the callback reaches its end without returning a value, that position in the result is undefined; map() does not remove the element. To omit elements based on a condition, use filter() or a suitable flatMap() pattern.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Return a new object when transforming objects

For an immutable transformation, return a new object from the callback. If you are instead mutating existing objects and do not need an output array, forEach() makes the intent clearer.

Do not pass parseInt directly

map() passes the current index as the callback’s second argument, and parseInt treats its second argument as a radix. As MDN’s example shows, ["1", "2", "3"].map(parseInt) produces [1, NaN, NaN]. Wrap the call to provide the intended radix: values.map((text) => parseInt(text, 10)). Use Number instead when its conversion behavior suits the input.

Use forEach() when you need an action, not a result array

forEach() invokes a callback for each present element and always returns undefined. For example:

const names = ["Ada", "Grace", "Linus"];
names.forEach((name) => console.log(name));

The callback’s return value is ignored. Calling map() for the same kind of side effect constructs an array that goes unused. MDN Web Docs describes that as an anti-pattern and recommends forEach() or for...of instead: MDN Web Docs: Array.prototype.map().

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When neither method fits

You need to stop before the end

forEach() has no native break, and map() is not designed for early termination. Use for...of or a for loop when you need explicit control. A short-circuiting method such as some(), every(), or find() can also fit when its specific result and stopping behavior match the task. Throwing an exception is the only way to stop forEach() directly, but it is not a normal substitute for loop control.

You need to await asynchronous work

An async callback returns a promise, but neither method waits for those promises. In particular, forEach(async ...) is not a way to run tasks sequentially or to wait until all of them finish. Choose an explicit promise-composition pattern or a loop with the asynchronous behavior you need.

Sparse arrays: holes are not undefined values

Both methods skip empty slots in a sparse array. Those holes differ from elements that are explicitly set to undefined, which are present elements and are visited. When map() skips a hole, it preserves a hole at the corresponding position in its result.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Is one method faster?

The documented distinction is about intent and return behavior, not speed. The cited MDN references do not establish a general performance winner, so choose based on whether you need a transformed array, an action for each element, or different control flow.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.