Guard Clause in JavaScript
Last Updated :
01 Dec, 2023
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.
Javascript
function greetUser(userName) {
if (!userName || typeof userName !== 'string' ) {
console.log( "Please provide a valid user name." );
return ;
}
console.log(`Hello, ${userName}!.`);
}
greetUser();
greetUser(123);
greetUser( "Geek" );
|
Output
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.
Javascript
function calculateArea(width, height) {
if ( typeof width !== 'number' ||
typeof height !== 'number' ||
width <= 0 || height <= 0) {
console.log(
`Please provide valid positive numbers`);
return ;
}
const area = width * height;
console.log(`The area is: ${area} square units.`);
}
calculateArea();
calculateArea(5, -8);
calculateArea(4, 9);
|
Output
Please provide valid positive numbers
Please provide valid positive numbers
The area is: 36 square units.
Share your thoughts in the comments
Please Login to comment...