18

As shown on MDN, Map's forEach callback is called with value first, and then key. E.g.:

map.forEach(function(value, key, map) { ... })

Seems like key, value is a lot more common than value, key. Even the Map constructor expects an array of [key, value] pairs.

7
  • 1
    I usually need the value only, and would end up writing something like .map(function(_, value) { ... }); Commented Oct 13, 2015 at 19:11
  • I don't now if it is more 'common', e.g. docs.angularjs.org/api/ng/function/angular.forEach Commented Oct 13, 2015 at 19:11
  • fyi Array.prototype.amp is described in ECMA-262 Edition 5 ecma-international.org/ecma-262/5.1/#sec-15.4.4.19 Commented Oct 13, 2015 at 19:12
  • 2
    I think the reason is that it better aligns with forEach method of the Array. Commented Oct 13, 2015 at 19:13
  • 4
    This was probably chosen for consistency with Array.prototype.forEach, whose callback function takes its parameters in the order value, index, where map items (obviously) are accessed by key rather than by index. Commented Oct 13, 2015 at 19:20

1 Answer 1

17

It's probably just for laziness sake. Most forEach loops will only care about the value itself. By supplying it as the first parameter, you can construct a function that only accepts one parameter:

map.forEach(function (value) { /* do something with value */; }) 

Instead of

map.forEach(function (unused, value) { /* do something with value */; }) 
Sign up to request clarification or add additional context in comments.

3 Comments

Or even map.forEach(val => val) vs map.forEach((key, val) => val)
Hm, yeah, that makes sense. It bit me though when I first used it recently, hence the SO question...
Yeah, by analogy with Array.map, whose callback takes value, index, array, it makes a lot of sense.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.