Can't use String#trim as a callback for Array#map

For some reason I can't use as a callback for array methods, such as map or filter.

In this case, two functions work the same:

function trim(string) {
  return string.trim();

var string = ' A ';

trim(string);                       // 'A'; // 'A'

However, when I try to pass them as a callback for an array method, second one fails:

var array = [' A', 'B ', ' C '];;                       // ['A', 'B', 'C'];; // TypeError: undefined is not a function


I assume in a latter case that this doesn't point to an array element, but I would like to get clear explanation of what's happening.


Answer; // 'A'; // TypeError: undefined is not a function

When you invoke the call method in the first case, its this value is bound to the String.prototype.trim function. In the second case, you just access the call function without having it bound to anything - you could just have used

This method is getting invoked with nothing as the this value, the element from your array, the index and the whole array as parameters. When you call call not on a function, it throws. You can either use the second parameter of map or the bind method to fix the this value for the call:, String.prototype.trim)


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.