Home > Web Front-end > JS Tutorial > Guard expressions in JavaScript

Guard expressions in JavaScript

Patricia Arquette
Release: 2025-01-18 20:30:12
Original
799 people have browsed it

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);
}
Copy after login

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;
}
Copy after login

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';
}
Copy after login

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.

The above is the detailed content of Guard expressions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template