Findlay
Findlay

Reputation: 134

Why can't I use Array.prototype.find with String.prototype.startsWith as the filter?

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

Answers (1)

Nina Scholz
Nina Scholz

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

Related Questions