Search code examples
javascriptprototypejsunderscore.js

Why does Underscore.js define function aliases


Underscore.js defines aliases for functions like _.each (alias: forEach) and _.map (alias: collect) and I don't understand why.

I initially thought this was to avoid issues with browsers that didn't implement those functions natively, my thinking was that calling [].map() would throw an error in IE7 and 8 because they didn't implement it natively but found that there was no issue since Underscore already defines those.

Then I thought it could have something to do with conflicts with other JS libraries like Prototype that implement similarly named functions but then realised that having an alias doesn't actually make a difference in the case of _.map since prototype implements .map and .colelct and actually I'd been using prototype's implementation all along (eg. this.collection.collect(...)).

So far it doesn't seem to have made any difference and it hasn't created any issues but I'd really like to know why this is happening.


Solution

  • I guess the purpose of aliases is to make the library more familiar for programmers with different backgrounds (eg, collect and include are used in Ruby, fold in functional languages etc).

    Also, aliases can improve readability in some cases, for example

    list.select(...).reject(...)
    

    "sounds" better than

    list.filter(...).reject(...)