In Javascript, functions are first class objects. Functions can be assigned used as a values. One such type is Predicate, as the name suggest refers to a function that accepts an input and returns boolean(true/false) as an output. Let's look at example.
const Person={name:"John",age:30,height:5.6}
We have defined a Person object with name, age and height field. Now we will check if age of the object is more than 25.
const isAbove25=((p)=>p.age>25);
p=Person();
console.log(isAbove25(p));
Here it will print true as output.
filter
filter() iterates through each element of array and returns elements that satisfies the specified condition. filter() loops through each element of an array and invokes predicate on each element.
const numbers=[2,5,7,3,9,15,18,29];
Let's find numbers that are divisible by 3 using a predicate.
const isDivisibleby3((x)=> x%3===0);
const result=numbers.filter(x => isDivisibleby3(x));//[3,9,15,18]
some
some() loops through elements of an array in ascending order, and invokes predicate on each element of an array. If predicate returns true, then looping stops and returns true immediately.
const isDivisibleby3((x)=> x%3===0);
const result=numbers.some(x => isDivisibleby3(x));//true
Here 3 is found matching the criteria immediately the loop stops and true is returned as output.
find
find() iterates through each element of array and returns first element that satisfies the specified condition. find() loops through each element of an array and invokes predicate on each element.
const isDivisibleby3((x)=> x%3===0);
const result=numbers.find(x => isDivisibleby3(x));//3
findIndex
findIndex() iterates through each element of array and returns first matched element index that satisfies the specified condition. find() loops through each element of an array and invokes predicate on each element.
const isMoreThan10((x)=> x>10);
const result=numbers.find(x => isMoreThan10(x));//5
That's all for now, but the predicates can be used with other functions as well.
Predicates are more over like lambda, but predicate takes single input and returns only boolean. Predicates are used only for testing objects against criteria.
Happy Coding!
Top comments (3)
As a shorthand for
const result=numbers.filter(x => isDivisibleby3(x));
you can do
const result=numbers.filter(isDivisibleby3);
- so without having to explicitly pass it each array element.Array.filter (and some other array methods) takes a predicate function (returns boolean value) as an argument, and the function is called for each array element.
Documentation:
developer.mozilla.org/en-US/docs/W...
Super helpful, thank you!
Thanks for reading!