JAVASCRIPT Tutorial

Map in JS

What is Map?

  • A built-in function that creates a new array by applying a function to each element of the original array.
  • Does not modify the original array.

How to Use Map:

  1. Call the map() function on the original array.
  2. Pass it a callback function that takes each element and any other parameters as input.
  3. The callback function returns the new value for the new element.
  4. The result is a new array with the transformed elements.

Key Concepts:

  • Callback Function: A function that is passed to map() to specify how each element should be transformed.
  • Does Not Modify Original Array: map() does not change the original array. It only creates a new one with the transformed elements.

Syntax:

const newArr = arr.map(callbackFunction);

Example:

const nums = [1, 2, 3, 4, 5];

const doubled = nums.map((num) => num * 2);

console.log(doubled); // Output: [2, 4, 6, 8, 10]
console.log(nums); // Output: [1, 2, 3, 4, 5] (original array remains unchanged)
Improved Accessibility Example:
// Original array of names
const names = ['John', 'Mary', 'Bob', 'Susan', 'Alice'];

// Create a new array of uppercase names
const uppercaseNames = names.map((name) => name.toUpperCase());

// Print the new array
console.log(uppercaseNames); // Output: ['JOHN', 'MARY', 'BOB', 'SUSAN', 'ALICE']

// Original array remains unaffected
console.log(names); // Output: ['John', 'Mary', 'Bob', 'Susan', 'Alice']