libri-javascript-python

In this lesson we will talk about the JavaScript map method, used with arrays. This method creates a new array with the results of calling a function for each element of the starting array.

The syntax is as follows: array.map(function)

Where function can be an already existing function such as the absolute value function: Math.abs. Or it can also be a user-defined function.

The method returns a new array.

Also you can specify an optional value array.map (function, thisValue) which indicates the value to pass to the function to use as this value. Otherwise the passed value will be undefined.

Let’s take examples of using the map() method.

JavaScript map – first example

Apply the cube function to all elements of an array.

In this first example we first create an array of numbers.

Then we implement a cube function which simply returns the cube of a number. Then we want to apply it to all the elements of the array. Well we can use the map method on the starting array.

The result will be a new array where each element has been raised to the third.

Here is the simple example code:



var numbers = [5,4,3,2,6,12];

function cube(n) {
  return n * n * n;
}

var cubeNumbers = numbers.map(cube);
console.log(cubeNumbers);

For simplicity, we always display the result in the browser console.

JavaScript map – second example

Transform an array of numbers into an array of strings with the odd or even word.

In this second example we take an array of numbers.

Then we create a function that checks whether a number is even or odd. If it is even we return the even word, if instead the word odd is odd.

So we apply this function with the map method to each element of the array. As a result we will have an array where the odd or even value will appear instead of numbers.

Here is the complete code of the example that illustrates how the map method works in JavaScript.



var numbers = [5,4,3,2,6,12];


function evenOdd(n) {
  if (n % 2 == 0) {
    return 'even';
  }
  return 'odd';
}

var arrayStringa = numbers.map(evenOdd);
console.log(arrayString);

As usual, we display the modified array in the console.

Conclusion

These are just some simple examples of using the JavaScript map method, we will see other fields of application later.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript