Skip to content

Instantly share code, notes, and snippets.

@navanathjadhav
Created June 27, 2022 15:41
Show Gist options
  • Save navanathjadhav/a05c2cec45cad4f0c194941807e840c7 to your computer and use it in GitHub Desktop.
Save navanathjadhav/a05c2cec45cad4f0c194941807e840c7 to your computer and use it in GitHub Desktop.
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