DEV Community

Cover image for Guard expressions in JavaScript
Anastazja Reut
Anastazja Reut

Posted on

Guard expressions in JavaScript

From Wikipedia: In computer programming, a "guard" is a boolean expression that must evaluate to true if the program execution is to continue in the branch in question. Regardless of which programming language is used, guard code or a guard clause is a check of integrity preconditions used to avoid errors during execution.

In other words, the guard expression is an expression (also called pattern) that checks the simplest conditions with the minimum of calculations to prevent errors and unexpected behavior. It's a common pattern in almost all programming languages.


Let's look at an example:

const capitalize = str => {
    // Guard expression
    if (typeof str !== 'string') return '';
    return str.charAt(0).toUpperCase() + s.slice(1);
}
Enter fullscreen mode Exit fullscreen mode

This is classical example of the guard expression. At the beginning of the function, it checks whether passed value is a string. If it fails, prevent the function from further calculations. With this approach, the main code is at the top level, and not inside of if statement condition. It helps to avoid nesting and improve code readability.

Here is another example:

const checkAge = age => {
  if (typeof age === 'number') {
    if (age < 21) return 'Not eligible';
    if (age >= 21 && < 60) return 'Eligible';
  }
  return null;
}
Enter fullscreen mode Exit fullscreen mode

This is a simple function that checks age. It looks fine, but we can make some improvements here.

const checkAge = age => {
    if (typeof age !== 'number') return null;
    if (age < 21) return 'Not eligible';
    if (age >= 21 && < 60) return 'Eligible';
}
Enter fullscreen mode Exit fullscreen mode

The condition return null if not a number is quite obvious. We start the function with the simple check and, if it fails, everything below the guard expression (the first check) falls. Now it's easier to read the function and, more importantly, it prevents unnecessary calculations.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay