0

I have stumbled upon this unexpected behavior in javascript

'use strict';
var _ = require('lodash');
_.map([1, 2, 3], function(x){console.log(x); });
_.map([1, 2, 3], console.log);

the two calls to map are behaving differently.

the first is printing the 1, 2, 3 line by line, whereas the latter call to map prints the iterator that map yields.

is there a more elegant way to write the first call? (without using es6 => operator)

epsilonhalbe
  • 15,637
  • 5
  • 46
  • 74

1 Answers1

2

You can use ary to limit the number of arguments passed to console.log.

_.map([1, 2, 3], _.ary(console.log, 1))
georg
  • 211,518
  • 52
  • 313
  • 390
  • is not quite what I had expected - but I am dealing with javascript here so, better get in the habit of not wondering – epsilonhalbe Jul 16 '15 at 13:27
  • 1
    Yeah; it's a pitfall of optional/varardic arguments and mapping. – Retsam Jul 16 '15 at 16:30
  • 1
    If you're getting an `Illegal invocation` error, try this: `_.map([1, 2, 3], _.ary(console.log.bind(console), 1))` ([reference](http://stackoverflow.com/a/8159338/2014893)) – Robert K. Bell Sep 02 '15 at 00:00