Reputation: 134
This throws an error:
['hello'].find('helloworld'.startsWith);
Uncaught TypeError: String.prototype.startsWith called on null or undefined
at startsWith (<anonymous>)
at Array.find (<anonymous>)
at <anonymous>:1:11
But when wrapped in an arrow function, it works fine
['hello'].find(string => 'helloworld'.startsWith(string));
"hello"
Why is this?
Upvotes: 2
Views: 1159
Reputation: 386560
Because you need not only the function, but also the bound object.
This could be achieved by using thisArg
of Array#find
console.log(['hello'].find(String.prototype.startsWith, 'helloworld'));
or by binding the string to the function.
console.log(['hello'].find(String.prototype.startsWith.bind('helloworld')));
// sloppy
console.log(['hello'].find(''.startsWith.bind('helloworld')));
CAVEAT
String#startsWith
and String#endsWith
have a second parameter for an index.
The index is handed over of Array#find
and works only on special circumstances, like for startsWith
with an array with a single string (at index zero) for all other strings, it is likely not to work.
endsWith
needs an index from the end of the array and it is dependent on the string length and index by using an array iterating method.
Upvotes: 8