Skip to content Skip to sidebar Skip to footer

Js Using Partially Parametrized Function

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)

Solution 1:

When you do [1, 2, 3].every(isBigEnough(0)). It:

  • Calls isBigEnough that returns false.
  • Executes [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:

functionisBigEnough(threshold) {
  returnfunction(element, index, array) {
     return (element >= threshold);
  }
}
[1, 2, 3].every(isBigEnough(0))

Solution 2:

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:

functionisBigEnough(threshold=0,element, index, array) {
 return (element >= threshold);
}
[1, 2, 3].every(isBigEnough.bind(null,5));//threshold=5

Post a Comment for "Js Using Partially Parametrized Function"