Here is my code I am trying to learn.
let depList : Array<number>;
depList = [1,2,3,4,5,6,7,8,9];
let numResults = depList.filter(num => num > 5); // predicate
console.log(numResults);
let resultFind = depList.find(num => num ==5); // predicate
console.log(resultFind);
let sum = depList.reduce((acc, num) => acc + num); // callback function
console.log(sum);
What’s the difference betweeen predicate and callback function here?
I tried going through the method definition but seems hard to understand the differnece.
2
Answers
There is a big overlap.
A "predicate" is a function that takes parameters and returns a boolean. It is always a boolean as it is always related to some logical check. Examples
A "callback" is any function that is passed in as a parameter. It might be a predicate (returning boolean) or not.
In the case of
.filter()
and.find()
the callback they accept is a predicate.A predicate needs not be used as a callback. And a callback needs not be a predicate. The two are orthogonal.
As indicated, a predicate is a function that takes a single argument, and returns a boolean. A callback is a function that is passed to another function.
In typescript, predicates are significant because they can be used for type narrowing. For example:
Because the predicate was annotated with
n is number
, it is now a type predicate. This means thatfiltered
now has the typenumber[]
– the type system knows that all the nulls have been filtered from the array.