Free UI Resources - UI Dev Made Easy
Javascript

Javascript Array Methods – .map()

.map()

The .map() method is another powerful built-in function provided by JavaScript arrays. It allows you to create a new array by applying a transformation function to each element of an existing array. This method is extremely useful when you want to transform the contents of an array while maintaining a consistent length.

Here’s the basic syntax of the .map() method:

const newArray = array.map(function(currentValue, index, array) {
  // Return a new value for each element
});
  • currentValue: The current element being processed in the array.
  • index (optional): The index of the current element.
  • array (optional): The array that .forEach() is being applied to.

The .map() method returns a new array where each element is the result of applying the provided function to the corresponding element in the original array.

Here’s an example to illustrate how .map() works:

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

const squaredNumbers = numbers.map(function(number) {
  return number * number;
});

console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]

In this example, the .map() the method applies the transformation function to each element of the numbers array, squaring each number and creating a new array called squaredNumbers.

const doubledNumbers = numbers.map(number => number * 2);

Keep in mind the following points when using .map():

  1. New Array: The .map() method creates and returns a new array, leaving the original array unchanged.
  2. Transformation: You can use .map() to perform various transformations on array elements, like doubling values, converting data types, or applying more complex operations.
  3. Use Cases: .map() is great when you need to transform data in a one-to-one relationship, where each input element corresponds to one output element.
  4. Returning Values: Ensure that the function inside .map() explicitly returns a value for each element. If you omit the return statement, the resulting array will have undefined values.
  5. Mapping to Objects: You can also use .map() to transform an array of objects, creating a new array where each object has its properties modified according to the transformation function.

In summary, the .map() method is a powerful tool for creating a new array by applying a transformation function to each element of an existing array. It’s commonly used when you want to modify the contents of an array while keeping the same length and structure.

back to top