Array
/Object
prototype method JS-D008Many built-in functions defined on prototypes for Object
and Array
are pure, and return modified versions of their inputs.
If the return values from these functions aren't used, the function call is essentially a no-op and might as well be removed.
// These calls do not modify the array, instead they
// return new arrays with the desired properties.
xs.map(x => x.prop)
xs.filter(x => x.prop === 'value')
xs.concat(ys)
xs.reduce((x, y) => (x.value + y.value))
Perhaps, you're using map
to iterate over an array and induce some side-effect, like logging to the console as shown here:
xs.map((x, i) => console.log(`element #${i}:`, x))
This use of map
is however misleading.
The map
/filter
/concat
methods should only ever be used to produce new arrays that are used elsewhere.
Instead, you should use the forEach
method:
xs.forEach((x, i) => console.log(`element #${i}:`, x))
const characters = [
{ name: 'Paul Atreides', age: 15 },
{ name: 'Kaladin Stormblessed', age: 19 },
{ name: 'Miss Kobayashi', age: 25 },
{ name: 'Eren Yeager', age: 14 },
{ name: 'Illidan Stormrage', age: 3000 }
]
characters.map(character => character.name);
// characters array is not modified by the call to `map`.
console.log(characters)
const characters = [
{ name: 'Paul Atreides', age: 15 },
{ name: 'Kaladin Stormblessed', age: 19 },
{ name: 'Miss Kobayashi', age: 25 },
{ name: 'Eren Yeager', age: 14 },
{ name: 'Illidan Stormrage', age: 3000 }
]
// array returned by call to `map` is now stored.
const characterNames = characters.map(character=> character.name);
console.log(characterNames)
// [ 'Paul Atreides', 'Kaladin Stormblessed', 'Miss Kobayashi', 'Eren Yeager', 'Illidan Stormrage' ]