I don’t understand why having 1 argument in list.bind() returns an empty array. Can someone please illustrate what’s going on here?
EDIT: is it because the first argument is supposed to provide context, which in this case there isn’t any?
Yes. If you just passed 37 then you are saying “wrap the function in another function that executes in the context of 37”, which doesn’t make a lot of sense.
Whereas with what you’ve got there, you’re saying “wrap the function in another function. I don’t care about the context, I’m not trying to execute it in any specific scope, but when it executes, pass 37 to the executed bound function”.
The three related function methods (apply, bind and call) let you borrow methods defined as properties of one object and have them execute in the scope of a different object. But often you don’t care about that. In this bind example, you just want to execute the function with an argument prefilled, that’s all, so you just tell it you don’t care about that scope option. bind takes two arguments, so you have to pass something as the first option (could be null, could be undefined, could even be 37 as well but that would be confusing to read)
Edit: it’s very useful to know how these work, but note that they aren’t super useful day-to-day, there are normally better approaches nowadays (though when it turns out you do actually need them, they’re useful weapons)
function largestOfFour(arr) {
return arr.map(Function.apply.bind(Math.max, null));
}
Could you please explain how this works? How is it being used without defining an element within map() the way we normally do, for example map(a => a + 2)? I would really appreciate it if you could break this down for me like you did in the previous reply, that was very helpful.
P.S my solution was this
function largestOfFour(arr) {
return arr.map(a => Math.max(...a))
}
So here I had to define a, that’s why the solution using apply() and bind() is that much more confusing to me
It loops the array and calls the function it was passed, passing it the element, index, and original array as arguments.
The function you passed to map in the example code is not invoked. It is an anonymous function definition that when called by map will call the inner function (which is invoked).