Skip to content

Question on the order of callback parameters for iteration over object. #9

@mnmly

Description

@mnmly

Hi,
I'm a bit wondering why the order of the parameters are kinda reversed on object iteration. If there's any reason why the order is in this way, it would be helpful if you can share your thoughts in order for me and potentially others to avoid relevant mistakes and such.

Currently when you iterate over object, you will get key, (or property name) as the first argument:

var conf = {
  fast: 1,
  normal: 0.5,
  slow: 0.3
};
each(conf, function(key, val){
  console.log(val, key); // => 1, "fast"... 
})

But if we consider key to be more like index, the following order is a bit more consistent compared to other types, where val is always passed as first argument.

var conf = {
  fast: 1,
  normal: 0.5,
  slow: 0.3
};
each(conf, function(val, key){
  console.log(val, key);  // => 1, "fast"... 
})

each("something", function(val, index){
  console.log(val, index)  // => "s", 0... 
})

each(['a', 'b', 'c'], function(val, index){
  console.log(val, index); // => "a", 0…
})

underscore.js and lodash.js are passing val in the first parameter:

var _ = require('underscore') // require('lodash');
var conf = {
  fast: 1,
  normal: 0.5,
  slow: 0.3
};
_.each(conf, function(val, key){
  console.log(val, key); // => 1, "fast"... 
})

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions