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); }
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 &&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 &&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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3