Ternary Operator & Other Shorthands For Conditional Statements

exit post

If you’re anything like me, this will excite you too!. I absolutely enjoy finding shorthand ways to write code, probably everyone does. It’s faster and well, relatively easier. So you can imagine my joy when i discovered writing javascript’s conditional statements in shorthand. I’ll jump right into it.

Ternary Operator

First one here is the ternary operator. It can be used to shorten the usual syntax of if ... else statement.

For example

  let wantRide = true;

  if(wantRide) {
      console.log ('See you!');
  }
  else{
      console.log ('Ok!')
  }

can be written with tenary operator as:

   wantRide ? console.log('See you!') : console.log ('Ok!');

It can be chained to make longer statments

Awesome right? I know. Let’s look at ways to shorten other conditional statements.

Truthy & Falsy Assigment

If you didn’t already guess, this one targets truthy & falsy statements.

An example for this would be

  let food = '';
  
  let foodOption = food;

  if (food){
      console.log(`I want ${foodOption}`)
  }
  else{
      console.log('I want to eat')
  }

written as

  let food = '';
  
  let foodOption = food || 'to eat'

  console.log(`I want ${foodOption}`)

Switch

Finally we’ll look at the switch keyword which matches values to a cases and can be used to write shortcut also for conditional statments.

We have

 if (clothColor === 'black'){
   console.log('dark');
 }
 else if (clothColor === 'white'){
    console.log('light');
 }
 else{
   console.log('colored');
 }

and can write it as

  switch (clothColor){

  case 'black' :
  console.log('dark');
  break;

  case 'white' :
  console.log('light');
  break;

  default : 
  console.log ('colored');
  break;
  }

At first glance, this may not look particularly short but imagine having to write lines and lines of else if statements, this definitely has better readablility and it easier to write.