Home > shorts > Coding map() function with JavaScript

Coding map() function with JavaScript


Coding map() function with JavaScript

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

const fruits = ["🍏", "🍎", "🍐", "🍊"]
const makeJuice = fruit => "🧃" + fruit

const juice = fruits.map(fruit => "🧃" + fruit)

juice // [ '🧃🍏', '🧃🍎', '🧃🍐', '🧃🍊' ]

Coding map() function with plain JavaScript

const juice = newMap(fruits, makeJuice)

function newMap(arr, transform) {
    const newArr = []
    for(let i = 0; i < arr.length; i++) {
        newArr.push(transform(arr[i]))
    }
    return newArr
}

juice // [ '🧃🍏', '🧃🍎', '🧃🍐', '🧃🍊' ]
© 2021, Andrew Losseff