Skip to content

Instantly share code, notes, and snippets.

@navanathjadhav
Created Jun 27, 2022
Embed
What would you like to do?
Example of guard clause
/*
* Here important code is written inside long if block
*/
function login(username, password) {
const user = await UserSchema.find({ email: username, password: password })
if (user) {
// Important code...
} else {
return new Error('Invalid credentials')
}
}
/*
* Here user is asserted at the beginning and the error has been returned thus stopping the further unnecessary execution
*/
function login(username, password) {
const user = await UserSchema.find({ email: username, password: password })
/*
* Guard Clause
*/
if (!user) {
return new Error('Invalid credentials')
}
// Important code...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment