Answer the question
In order to leave comments, you need to log in
An example of a closure when using the arr.filter( ) method. How it works?
Here is an example of using a closure in learn.javascript:
function inBetween(a, b) {
return function(x) {
return x >= a && x <= b;
};
}
let arr = [1, 2, 3, 4, 5, 6, 7];
console.log( arr.filter(inBetween(3, 6)) ); // 3,4,5,6
But there is no explanation of how this works. It is not entirely clear here where some nowhere declared argument x comes from in an anonymous internal function? Intuitively, I assume that it can be determined by the filter method itself when passing through the array, but the mechanism itself is not entirely clear ..
Thanks in advance and good health to everyone.
Answer the question
In order to leave comments, you need to log in
const newFunction = inBetween(3, 6);
is tantamount to
const newFunction = function(x) {
return x >= 3 && x <= 6;
};
arr.filter(inBetween(3, 6))
arr.filter(newFunction)
arr.filter(function(x) {
return x >= 3 && x <= 6;
})
But there is no explanation of how this works. It is not entirely clear here where some nowhere declared argument x comes from in an anonymous internal function? Intuitively, I assume that it can be determined by the filter method itself when passing through the array, but the mechanism itself is not entirely clear ..
The filter() method calls the passed callback function once for each element present in the array and creates a new array with all the values for which the callback function returned a value that can be cast to true. The callback function is called only for array indexes with already defined values; it is not called for indexes that have been dropped or have never been assigned a value. Array elements that fail the callback test are simply skipped and not included in the new array.
The callback function is called with three arguments:
1. the value of the element;
2. element index;
3. the array through which the passage is carried out.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question