What is the Array map() function in JavaScript?

The Array map() function is a built-in function in JavaScript that transforms input arrays into output arrays. It takes a function as an input and applies it to every element in the input array, then returns the output array. The map() function was added in ES5, and is part of the standard library.

The map() function is often used to transform arrays into new arrays containing only specific elements. For example, the following code transforms an input array of numbers into an output array of only even numbers:

var input = [1, 2, 3, 4, 5];
var output = input.map(function(num) {
    if (num % 2 == 0) {
    return num;
	}
});

console.log(output);

The code above will print [2, 4, 6, 8].

The map() function can also be used to perform more complex operations. For example, the following code calculates the square root of every number in an input array:

var input = [1, 2, 3, 4, 5];
var output = input.map(function(num) {
    return Math.sqrt(num);
});
console.log(output);

The code above will print [1, 1.41421356, 1.73205081, 2, 2.44948974].

The map() function can be used with any type of input array, including arrays of objects. For example, the following code transforms an input array of objects into an output array of only objects with a name property:

var input = [
{name: "Bob"},
{name: "Joe"},
{name: "Sue"},
{name: "Mary"}
];

var output = input.map(function(obj) {
    if (obj.name) {
        return obj;
    }
});

console.log(output);

The code above will print

[{name: "Bob"}, {name: "Joe"}, {name: "Sue"}, {name: "Mary"}]
💡
Need a writer? Want to work with me? I have a subscription copywriting service available at Zipply.io. Subscribe to a set number of words and split it into as many copy assets as you need. Scale your startup, small business, or MVP. Upgrade, downgrade and pause at any time. Start your subscription here.