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?

2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.