What happens inside .map() in JS?


I recently heard about higher-order functions and I’m curious about how they work internally.

For example, consider this code:

var numbers = [16, 25, 36];
var results = numbers.map(Math.sqrt);
console.log(results); // [4, 5, 6]

What is the mechanism that allows each element of the numbers array to be iterated through one by one?

I have done some research, but I have yet to find a satisfactory answer.

The map function in JavaScript is a higher-order function that takes a callback function as an argument.

When you use numbers.map(Math.sqrt), it internally iterates over each element in the numbers array and applies the Math.sqrt function to each element. The Math.sqrt function calculates the square root of a number.

The map function takes care of iterating over each element in the array and applies the callback function to each element. It then collects the results of each function call and returns a new array containing the results.

In your example, numbers.map(Math.sqrt) applies the Math.sqrt function to each element in the numbers array, resulting in a new array [4, 5, 6], which is then assigned to the results variable.

So, the mechanism that allows each element of the numbers array to be iterated through one by one is the higher-order function map.