Sobes.tech
Junior

Tell me about the map method.

sobes.tech AI

Answer from AI

The map method in JavaScript creates a new array by calling the provided function for each element of the original array and collecting the results of these calls.

It does not modify the original array.

Syntax:

arr.map(callback(currentValue[, index[, array]])[, thisArg])
  • callback: The function called for each element. It takes arguments:
    • currentValue: The current element being processed in the array.
    • index (optional): The index of the current element.
    • array (optional): The array that map was called upon.
  • thisArg (optional): The value to use as this when executing callback.

Example:

Transforming an array of numbers into an array of their squares:

const numbers = [1, 2, 3, 4, 5];
const squares = numbers.map(num => num * num);
// squares will be [1, 4, 9, 16, 25]

Differences from forEach:

  • map creates a new array based on the return values of the callback function.
  • forEach executes a function for each element but does not create a new array and returns nothing (specifically, it returns undefined).

Usage in QA:

  • Transforming test data into the required format.
  • Extracting specific fields from an array of objects (e.g., a list of users).
  • Generating test URLs from a base address and a list of paths.
Tell me about the map method. — QA / QA Automation - sobes.tech