0

I'm trying to understand why this bound function is behaving differently when called in these different ways. Here's the example.

var str = 'sss';
var f = str.endsWith.bind(str);

// false?
console.log(['s', 'q', 'r'].some(f))
// true
console.log(['s', 'q', 'r'].some(value => f(value)))
// true
console.log(f('s'))

What am I missing, why isn't the first call returning true?

pilchard
  • 12,414
  • 5
  • 11
  • 23
slevin
  • 308
  • 1
  • 8
  • 1
    Because the first example is also passing `index` and `arr` to `endsWith` and the [second parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith#parameters) of `endsWith` is `length` (it's equivalent to `.some((value, index, arr) => f(value, index, arr))`) see: [Why does parseInt yield NaN with Array#map?](https://stackoverflow.com/questions/262427/why-does-parseint-yield-nan-with-arraymap) – pilchard Jun 09 '22 at 22:29
  • 1
    Does this answer your question? [Why does parseInt yield NaN with Array#map?](https://stackoverflow.com/questions/262427/why-does-parseint-yield-nan-with-arraymap) – pilchard Jun 09 '22 at 22:31

1 Answers1

1

Array.some() passes 3 arguments to the callback function: the current array element, its index, and the array.

String.endswith() takes an optional second argument, which is used as the length of the string instead of its actual length.

So the first iteration calls

f('s', 0, ['s', 'q', 'q'])

which is equivalent to

"sss".endsWith('s', 0)

If you use 0 as the length of the string, it doesn't end with s, so this returns false.

When you use your function value => f(value), the extra arguments are discarded so the default length is used and the function operates as expected.

Barmar
  • 741,623
  • 53
  • 500
  • 612