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 thatmapwas called upon.
thisArg(optional): The value to use asthiswhen executingcallback.
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:
mapcreates a new array based on the return values of the callback function.forEachexecutes a function for each element but does not create a new array and returns nothing (specifically, it returnsundefined).
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.