Nilesh Saini

Concise explanation of map() method in Js

Photo by GeoJango Maps on Unsplash
  1. Creates a new array.
  2. Iterates through an array.
  3. Runs a callback function for each element in the array.
  4. Adds the result of that callback function to the new array.
  5. Returns the new array.

Note: map() always returns a new array of the same length.

How does it work?

Note: learn more about callback function parameters here.

Examples:

  1. Triple the value of each element in the given array.

2. Return a new array with the square root of all the values of the given array.

--

--

Concise explanation of forEach() method in Js

Photo by Katie Moum on Unsplash
  1. Iterates through an array.
  2. Runs a callback function on each value in the array.
  3. Returns undefined.

Note: forEach always returns undefined.

How does it work?

Parameters:

  • Callback Function: Function to execute on each element. It is called with the following arguments:
  • Value: Current element being processed in the array.
  • Index: index of the element in the array.
  • Array: The complete array on which forEach method is called.
  • thisArg: Value to use as this when executing the callback function.

Note: In the callback function we don’t always have to use the three parameters (Value, Index, Array), Use whichever ones you need, just remember the order is important.

Note: thisArg parameter is optional too.

Examples:

  1. Given an array, print all the values in the console using forEach().

2. Return the sum of all elements in the array using forEach().

--

--

Nilesh Saini

Nilesh Saini

Web Developer/ Front-end engineer who loves solving Rubik's Cube