Tech Study

Maps JavaScript | JavaScript Array map() Method

What Is Map In Javascript?

JavaScript maps() make a new array by calling a function for each and every array element. It calls a function just once for each element in an array. It does not execute the function for null or empty elements. It does not change the modifies the original array.

SYNTAX 

javascript array map (function(currentValue, index, arr), thisValue)

  1. Function- a function to be run on each array element.
  2. currentValue – the value of the element of current index.
  3. index – It is optional. The index of the current element.
  4. arr – It is optional. It denotes the array of the current element.
  5. thisValue – It is optional. Its default value is undefined

For example – 

const arr1 = [4,9,16];

// Pass a function to map

const map1 = arr2.map(x => Math.sqrt(x));

console.log(map1);

// Expected output: Array [2,3,4]

The map() method is an iterative method. The map() method is a method of copying. It does not change this. However, the function provided as a callback can mutate the array. The length of the array is saved way before the first invocation of the callback function and will not go to any elements added beyond the array’s initial length when the call to map() starts. Modifications of already-visited indexes or elements do not cause e callback to be invoked again. If an already existing, yet-unvisited element or index of the array is modified by callback, its value passed in the callback will be the value at the time for which the element gets visited. Deleted elements are not visited.

Below is the code for mapping an array of numbers to their doubles ( 2*x)

const numbers = [1, 4, 9];

const roots = numbers.map((num) => num*2);

// doubles are now     [2,4,6]

// numbers are still [1,2,3]

Java Final keyword

Introduction : java final keyword The final keyword present in Java programming language is generally used for restricting the user. …

Read more

C++ Memory Management: new and delete

C++ Memory Management We know that arrays store contiguous and the same type of memory blocks, so memory is allocated …

Read more