Wanna replace if  statements with something even shorter than ternary operator ? (Short-circuiting)

Wanna replace if statements with something even shorter than ternary operator ? (Short-circuiting)

Β·

6 min read

As we all know betting on Javascript can never make you go hungry. So why not use some of it's shortcuts in order to trim some code and make your developing life much easier. In Javascript you could use short-circuiting the term represents that you can save your some unnecessary computation time by just evaluating required inputs.

What is required to use short-circuiting ?

Just some logical operators ( && , || , ?? ) and that's it. If you are someone like me who thought that these operators just returns the boolean value then you my friend are up for a great revelation and possibilities with it. If you are some-what familiar with these operators you know that && (AND) stops evaluating any further as soon as it finds Falsy value. The || (OR) stops evaluating as soon as it finds Truthy value. But did you know if a certain expression like (A || B) is assigned to a variable it will return the value where it stopped evaluating to the assigned variable. So these logical operator can take any value variable, number, boolean even functions !! and can also return the same. If you stick till the end you might learn how to trigger a function with itπŸ˜‰.
The below code will explain this clearly :

//----A is falsy and B is truthy----

let A = 0;  // A is falsy ( 0 is considered falsy in OR operator.)
let B = 44; // B is truthy

/* It will evaluate till B as it uses OR operator 
and A is falsy thus assigning the value of B to A */
A = A || B; 
console.log(A)
//output:- 44

1. Logical AND ( && ) - A && B

  • If A is falsy then it will immediately return the value of A regardless the value of B.
  • If A is truthy and B is falsy then it will return the value of B.
  • If A is truthy and B is also truthy it will return the value of B.
//  ----A is falsy and B is truthy---- 
let A = NaN      
let B = 3       
A = A && B       //  because A is falsy it will return with the value of A and will not evaluate B.
console.log(A)    
//output:-  NaN
//  ----A is truthy----
let A = " I'll be not shown in output 😒"    
A = A && undefined //  because A is truthy it will evaluate undefined and assign undefined to A
console.log(A)    
//output:-  undefined
//----A is truthy B is truthy----
let A = "Hello πŸ‘‹ "     
let B =  "World 🌏 "         
A = A && B       //  because A is truthy it will evaluate B and assign it's value to A although B is also true
console.log(A)    
//output:-  World 🌏

2. Logical OR ( || ) - A || B

  • If A is truthy then it will immediately return the value of A regardless the value of B.
  • If A is falsy and B is also falsy then it will return the value of B.
  • If A is falsy and B is truthy it will return the value of B.
//  ----A is truthy and B is truthy---- 
let A = "JS is ❀️"    
let B = 3       
A = A || B       //  because A is truthy it will return with the value of A and will not evaluate B.
console.log(A)    
//output:-  JS is ❀️
/*----A is falsy----*/
let A = ''      /* (empty string is also considered as a falsy value.)*/
A = A || null    /* because A is falsy it will evaluate null and assign null to A although B is also falsy*/
console.log(A)    
/*output:-  Null*/
//----A is falsy B is truthy----
let A = ""                         
let B = " Sunday chilling 😎"    
A = A || B        //  because A is falsy it will evaluate B and assign it's value to A 
console.log(A)    
/* output:-  Sunday chilling 😎 */

3. Nullish Coalescing (??) - A ?? B

  • The Nullish coalescing operator is a new and additional JavaScript operator that has been available since June 2020 with ECMAScript 2020 (ES2020) of the programming language.
    • It has a notation of ??
    • It is almost same as OR || operator but a little change that makes it stand apart.
    • If left-hand side value is falsy then only it returns with right-hand side value and if the value in left-hand side is true it immediately assigns the value to the variable. but there is a catch to It. It does not considers 0 or ' ' (empty string) as a falsy value. let's see this in action.
/* To see the difference between || and ?? let's compare these operators
 There are 0 guests in the house we need to assign some value if there is 
 no guests variable but How can we do that if guests has a 0 value which is falsy. */

let guests = 0;
guests = guests || 10 // This will result in altering the guests variable with 10 even though it exists
console.log(guests);
//output - 10

//This is where ?? operator shines
let guestsInTheHouse = 0;
guestsInTheHouse = guestsInTheHouse ?? 10; // This will take 0 as truthy and return 0.
console.log(guestsInTheHouse); 
// output - 0

Logical assignment operator. ( &&=, ||=, ??= ).

  • Javascript Introduced Logical assignment operators in its ES2021 .
  • Same as regular assignment operators but for logical operators.
// Logical assignment operator for && is &&=
let sum = 2;
sum &&= 10;     // same as  (sum = sum && 10) which will evaluate till 10 and assign 10 to sum.
console.log(sum)
/* output - 10 */
// Logical assignment operator for || is ||=
let  month = 2;
month ||= 10;     // same as  (month = month && 10) which will immediately assign 2 to month.
console.log(month)
/* output - 2 */
/* Logical assignment operator for ?? is ??= */
let  Money = 0;
Money ??= 200;     /* same as  (Money = Money && 200) which will immediately assign 0 to Money.*/
console.log(Money)
/* output - 0 */

Let's get to the fun part and apply our learnings to real world scenario.

  • A simple system to book flights with these operators.
const Flight = {
  flightName: null,
  departure:null,
  destination:null,
  windowSeatAvailable: 0,
  initial: function(...arg){
          this.flightName = arg[0];
          this.departure = arg[1];
          this.destination = arg[2];
       }   
}

/*Calling the function with values using &&= 
Flight.intial  returns true so the right-hand side value is evaluated*/
Flight.initial && Flight.initial("Vistara","Pune", "Delhi"); 

/*Adding a meal property to the object using ||=
Flight.meal was not present in the object so it returned false 
and right-hand side value is updated*/
Flight.meal ||= ["Paneer masala " ,"Biriyani"];

/*Checking if there are any window seats left with ??=
Flight.windowSeatAvailable has a value of 0 but ?? 
operator considers it true so it took the first value returned it*/
Flight.windowSeatAvailable ??=  "Book";

console.log(`Flight Name: ${Flight.flightName} \n` , `Departure: ${Flight.departure} \n`, `Destination: ${Flight.destination} \n`);
console.log(`Meal on flight: ${Flight.meal}`);
console.log(`Window seat: ${Flight.windowSeatAvailable}`);
/*Output:-
Flight Name: Vistara 
Departure: Pune 
Destination: Delhi 
Meal on flight: Paneer masala ,Biriyani
Window seat: 0*/

Thanks for reading !! Happy Coding!! ❀

Β