Javascript - Map function (Functional programming)

About

The functional programming function map in a Javascript context is only an array method as all functional programming javascript method.

For the map data type, see Javascript - Map Data Type

Example

Arrow Function

With an Arrow function as argument

  • Letters that we want to lowercase
const letters = ['A', 'B', 'C', 'D', 'E'];
console.log("Showing only the function value call");
const lowercases = letters.map((letter) => letter.toLowerCase());
console.log(lowercases);
  • With the index
console.log("Showing the value, index call");
letters.map((letter, index) => console.log("Letter at position "+index+" is "+letter.toLowerCase()));

Function Declaration

With an Javascript - Function Declaration

  • The function declaration
function double(num) {
    return 2*num;
}
  • The array of number that we want to double.
const numbers = [1, 2, 3, 4, 5];
// Passing the function name
const doubled = numbers.map(double);
// Declaring the function inside the map works also
const doubled2 = numbers.map(function double(num) {
    return 2*num;
});
console.log("doubled data");
console.log(doubled);
console.log("doubled2 data");
console.log(doubled2);

Syntax

  • Functional Form
myArray.map((element, index) => { ... });
  • Procedural form
map((element, index, myArray) => { ... });

map builds a new array that you should use otherwise use other loop construction such as foreach or for…of

Documentation / Reference





Discover More
Functional Programming in Javascript

in javascript. array operationsDoc To get the cookies All function returns an array. A few returns an element...
Javascript - (Loop|Iterator)

This page is how to iterate in Javascript (ie the Iterator pattern in Javascript) To iterate / loop in Javascript, you can use the following syntax structure: the for statement the functional...
Javascript - Array

array in Javascript can contain any type of data. Different types of values can be stored within the same array Because arrays are special objects (as typeof implies), they can also have properties, including...
Javascript - foreach instruction

How to loop with foreach in Javascript
React - JSX

JSX is a Javascript HTML Like language that compiles to Javascript React API. The first motivation of JSX is that reading and writing React elements, are easier. It permits to: write JSX elements...



Share this page:
Follow us:
Task Runner