Mapping values

suggest change

It is often necessary to generate a new array based on the values of an existing array.

For example, to generate an array of string lengths from an array of strings:

['one', 'two', 'three', 'four'].map(function(value, index, arr) {
  return value.length;
});
// → [3, 3, 5, 4]
['one', 'two', 'three', 'four'].map(value => value.length);
// → [3, 3, 5, 4]

In this example, an anonymous function is provided to the map() function, and the map function will call it for every element in the array, providing the following parameters, in this order:

map() accepts an optional second argument, used as this inside the callback. An arrow function ignores it and keeps the surrounding this. Without that argument, a strict-mode callback sees this as undefined. A non-strict browser callback sees window. The next callback is non-strict only if this script itself is non-strict:

['one', 'two'].map(function(value, index, arr) {
  console.log(this); // window (the default value in browsers)
  return value.length;
});

You can change it to any custom object like this:

['one', 'two'].map(function(value, index, arr) {
  console.log(this); // Object { documentation: "randomObject" }
  return value.length;
}, {
  documentation: 'randomObject'
});

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents