Functional JavaScript Tutorial #6 - What are predicates?

A predicate is just a special kind of function that answers a yes-or-no question.

Imagine you have a box full of toys, and you want to know if a toy is a car or not. A predicate is like your helper who looks at the toy and says "yes" or "no." That's all it does, check one thing and give a simple answer.

Like a Playground Rule

Think about playing on the playground. There’s a rule that says, “You can ride the swings only if you are taller than 4 feet.” This rule is like a predicate, it checks if someone meets a condition (height) and then decides if they can swing.

In JavaScript, predicates often end with ? or use words like is, has, or can. For example:

  • isCar(toy) returns true if the toy is a car.
  • canSwing(child) returns true if the child is tall enough.

Filtering with Predicates

Predicates are super useful for filtering, it’s like sorting your toys into two piles: “cars” and “not cars.” You can use them in loops or special tools (like . filter()), which help you pick out only what you need. It’s just like using a sieve to find the big rocks in your sandbox!

Take the quiz →

Examples

  1. A predicate is like a yes/no question in JavaScript. For example, checking if a number is even returns true or false.

Ask a question

See also

Discussion

Recent activity