I was learning about arrays methods and there's one thing I don't quite understand, possibly related to closures.
First things first though, here's the code snippet:
let range = {
minNumber: 20,
maxNumber: 30,
isValid(number) {
return number >= this.minNumber && number < this.maxNumber;
}
};
let numbers = [16, 23, 27, 30, 45];
let filteredNumbers = numbers.filter(range.isValid, range);
console.log(filteredNumbers.length); // 2
console.log(filteredNumbers[0]); // 23
console.log(filteredNumbers[1]); // 27
From what I understand by passing second argument we bind this
to range
, otherwise simply calling: numbers.filter(range.isValid)
will make this
undefined. Shouldn't it have access to this
either way though, as we're "calling" isValid
from range
context by using .
operator?
There is also a second approach that works:
numbers.filter(number => range.isValid(number))
What's going on here? Now it's able to pick up this
from range
object all of a sudden? Arrow functions have no this
iirc, so it's not that.
Thanks for all the help in advance. :)