forEach() vs map() in JavaScript

Updated on Jan 7, 2024

post banner

Table of Contents


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(callbackFunction);

Square of each element of an array

import { Inter } from "next/font/google";
import styles from "../styles/component.module.css";

const inter = Inter({
  variable: "--font-inter",
});

# Program to check Armstrong numbers in a certain interval

lower = 100
upper = 2000

for num in range(lower, upper + 1):

   # order of number
   order = len(str(num))

   # initialize sum
   sum = 0

   temp = num
   while temp > 0:
       digit = temp % 10
       sum += digit ** order
       temp //= 10

   if num == sum:
       print(num)

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

export async function generateStaticParams() {
  const posts = await fetch("https://.../posts").then((res) => res.json());

  return posts.map((post) => ({
    slug: post.slug,
  }));
}

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:

export default function Page({ params }: { params: { slug: string } }) {
  return <div>My Post: {params.slug}</div>;
}

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

import Link from "next/link";

export default function PostList({ posts }) {
  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>
          <Link href={`/blog/${post.slug}`}>{post.title}</Link>
        </li>
      ))}
    </ul>
  );
}

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.

How did you like the article?

like

Thanks for reading! 🙏