Reputation: 6147
I'm very new to JS, I've tried code below :
function isBigEnough(element, index, array, threshold) {
return (element >= threshold);
}
[1, 2, 3].every(isBigEnough(threshold=0)
I thought it doesn't work because prototype
(in Array.prototype.filter()
) does not contain threshold, so it is types mismatch, but we can't define like this :
isBiggerThenZero = isBigEnough(threshold=0)
so is there nice workaround for this case ?
Upvotes: 0
Views: 68
Reputation: 9699
When you do [1, 2, 3].every(isBigEnough(0))
. It:
isBigEnough
that returns false
.[1, 2, 3].every(false)
. Where false
is not a function. SO it gives you an error. You can use a closure that binds threshold value to the returned function:
function isBigEnough(threshold) {
return function(element, index, array) {
return (element >= threshold);
}
}
[1, 2, 3].every(isBigEnough(0))
Upvotes: 4
Reputation: 138257
Default parameters must be in the function declaration, e.g:
function isBigEnough(element, index, array, threshold=0) {
return (element >= threshold);
}
[1, 2, 3].every(isBigEnough);
However, now its difficult to pass threshold:
[1,2,3].every((...a)=>isBigEnough(...a,2));
So you could rather do:
function isBigEnough(threshold=0,element, index, array) {
return (element >= threshold);
}
[1, 2, 3].every(isBigEnough.bind(null,5));//threshold=5
Upvotes: 1