What does the `&&` operator do?
The &&
or Logical AND operator finds the first falsy expression in its operands and returns it and if it does not find any falsy expression it returns the last expression. It employs short-circuiting to prevent unnecessary work. I've used this in the catch
block when closing database connection in one of my projects.
console.log(false && 1 && []); //logs falseconsole.log(' ' && true && 5); //logs 5
Using if statements.
const router: Router = Router();router.get('/endpoint', (req: Request, res: Response) => {let conMobile: PoolConnection;try {//do some db operations} catch (e) {if (conMobile) {conMobile.release();}}});
Using && operator.
const router: Router = Router();router.get('/endpoint', (req: Request, res: Response) => {let conMobile: PoolConnection;try {//do some db operations} catch (e) {conMobile && conMobile.release();}});
October 13, 2022
2047
Read more
What is the JavaScript += Operator and How Do You Use It?
December 04, 2022
JavaScriptUsing the startsWith() Method in JavaScript
December 04, 2022
JavaScriptReverse a String in JavaScript: 2 Easy Methods
December 02, 2022
JavaScript