JavaScript is partly a functional language.

To learn JavaScript, we got to learn the functional parts of JavaScript.

In this article, we’ll look at how to create our own array methods.

Working Functionally on Arrays

Array functions are useful for manipulating arrays.

There are many built-in array methods like map and forEach .

Many of them take callbacks which let us do something with the array entries.

map

The map method lets us convert array entries from one thing to another.

To implement it, we can loop through each entry and call a function that we pass in.

The function’s returned value will be pushed into a new array and returned.

For example, we can write:

const map = (array, fn) => {
  const results = []
  for (const a of array) {
    results.push(fn(a));
  }
  return results;
}

The map function takes an array and fn function.

We use the for…of loop to loop through the entries.

fn is used to map a value from one to another value.

Then we push the returned item in the results .

And we return the results array.

Then we can use it by writing:

const arr = map([1, 2, 3], (x) => x ** 3);

Then arr is:

[1, 8, 27]

#web-development #programming #javascript #developer

Functional JavaScript :  Functional Programming and Arrays
3.15 GEEK