In JavaScript, a Guard Clause is a programming pattern that uses conditional statements at the beginning of a function to check for specific conditions. When these conditions are met, the function returns early, preventing the rest of the code from executing. Guard Clauses enhance code readability and help handle exceptional cases efficiently.
Syntax:
function exampleFunction(parameter) {
if (guardCondition1) {
// Handle case for guardCondition
return result;
}
} // Rest of the function logic
Example 1: In this example, the greetUser
function uses a Guard Clause to handle cases where the user’s name is missing or not a valid string, ensuring that the greeting message is displayed only when a valid name is provided.
function greetUser(userName) {
if (!userName || typeof userName !== 'string' ) {
console.log( "Please provide a valid user name." );
return ; // Guard Clause for missing or invalid name
}
// Main logic for greeting
console.log(`Hello, ${userName}!.`);
} // Testing the function // with different inputs greetUser(); // Missing name
greetUser(123); // Invalid name
greetUser( "Geek" ); // Valid name
|
Please provide a valid user name. Please provide a valid user name. Hello, Geek!.
Example 2: In this example, the calculateArea
function uses a Guard Clause to handle the case where the width or height is missing, not a number, or non-positive.
function calculateArea(width, height) {
if ( typeof width !== 'number' ||
typeof height !== 'number' ||
width <= 0 || height <= 0) {
console.log(
`Please provide valid positive numbers`);
// Guard Clause for invalid
// or non-positive dimensions
return ;
}
// Main logic for calculating the area
const area = width * height;
console.log(`The area is: ${area} square units.`);
} // Testing the function with different inputs calculateArea(); // Missing width and height
calculateArea(5, -8); // Invalid height
calculateArea(4, 9); // Valid width and height
|
Please provide valid positive numbers Please provide valid positive numbers The area is: 36 square units.