2

Excuse me if I've something missed, but when I try to use call method as a callback it gives me strange error in both Chrome and Node.js.

['  foo', ' bar  '].map(String.prototype.trim.call);
TypeError: ["  foo", " bar  "].map is not a function
at Array.map (native)

But these snippets works:

['  foo', ' bar  '].map(function (item) { 
    return String.prototype.trim.call(item);
}); // => ['foo', 'bar']
/*
  and ES2015
*/
['  foo', ' bar  '].map(function () { 
    return String.prototype.trim.call(...arguments);
}); // => ['foo', 'bar']

Also I've checked type of call function:

typeof String.prototype.trim.call; // => 'function'

Am I doing something wrong? Could anyone please explain me why I get such error? Thanks.

Ermon
  • 25
  • 8

1 Answers1

1

The easiest solution to your problem is to just write it out:

['  foo', ' bar  '].map(s => s.trim());

If you want to pass a function, you will need something more complicated than you want, along the lines of

.map(Function.call.bind(String.prototype.trim))

or if you prefer

.map(Function.call, String.prototype.trim)

This question may answer all your issues.

Community
  • 1
  • 1
  • Thanks for answer. First one with bind gives me the same error as above. Second one works. – Ermon Feb 09 '16 at 18:32
  • @Ermon: He meant to bind `call` to `trim` :-) – Bergi Feb 09 '16 at 18:42
  • aside: `[' foo', ' bar '].map(eval.call, "".trim)` is a short way of saying that. – dandavis Feb 09 '16 at 18:43
  • @dandavis: Using the `Date` constructor or `eval` function for brevity golfing will confuse the heck out of anyone. If you do that, you should first eliminate all whitespaces :-) – Bergi Feb 09 '16 at 18:46
  • any rose by the name of `call` smells as sweet... not for prod, but great for console snips... – dandavis Feb 09 '16 at 18:47