DEV Community

Discussion on: Guard Clauses: How to clean up Conditionals

Collapse
 
couch3ater profile image
Connor Tangney • Edited

Guards are fantastic! While your Javascript syntax is perhaps the most verbose, guards can also be written as follows:

//a variable to test with
let a = 'a';

//condition && result
a === 'a' && console.log('yes it does!');
Enter fullscreen mode Exit fullscreen mode

You may notice this looks similar to the ternary operator. This is great for one-liners (like return codes 😉) but should not be used for complex / multi-line statements:

//a variable to test with
let a = 'a';

//condition && result
// !! THIS WON'T WORK !!
a === 'a' && (
  console.log('did this work?')
  console.log('no :(')
);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ombratteng profile image
Ole-Martin Bratteng • Edited
//a variable to test with
let a = 'a';

//condition && result
// !! THIS WILL WORK !!
a === 'a' && (
  console.log('did this work?'),
  console.log('yes :)')
);
Enter fullscreen mode Exit fullscreen mode

replit.com/@omBratteng/guard-claus...