skip to Main Content

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


  1. 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

    const isEmpty = x => x.length === 0;
    const isOdd   = n => n % 2 === 1;
    const isEven  = n => n % 2 === 0;
    

    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.

    Login or Signup to reply.
  2. 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:

    const myArray:Array<null | number>();
    ...
    const filtered = myArray.filter((n):n is number => n != null)
    

    Because the predicate was annotated with n is number, it is now a type predicate. This means that filtered now has the type number[] – the type system knows that all the nulls have been filtered from the array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search