DEV Community

Cover image for Replacing the if-else conditionals with logical operators && and ||
Akhil sai
Akhil sai

Posted on

Replacing the if-else conditionals with logical operators && and ||

(If you are not familiar with the concept of short circuit evaluation in javascript,please go through this post )

Ok. So if you are still here, then I believe that you are familiar with the short circuit evaluation concept.Let's get started!

If-else conditionals are generally used for checking truthy and falsy values and executing the logic accordingly as shown in following example

var flag = true;

var printTrue = function()
{
//do something here
console.log('true');
}

if(flag)
{
printTrue();
}
// -> true

Let's replace the if conditional with && operator and it prints the same output as the above

flag && printTrue()
// -> true

Now lets see how can we can use logical or || operator

var flag = false;
var printFalse = function()
{
//do something here
console.log('false');
}
if(!flag)
printFalse();
//-> false 
//or we can gain the same output using || operator
flag || printFalse();
//-> false

Similar concept can be used for

  • fallback to default value using logical or || operator
function Car(name)
{
   var _defaultName = "Tesla";
   //if name is not passed, then fallback to default name
   name = name || _defaultName;
   this.getName = function()
   {
    console.log('The name of car is ',name);
   }
}

var car1 = new Car('Beetle');
var car2 = new Car();// no name is passed is here and hence name is undefined

car1.getName();
// The name of car is Beetle
car2.getName();
// The name of car is Tesla
  • checking if the object is instantiated and then access its method using the logical and && operator as shown below
var car3 = new Car('Audi');
car3 && car3.getName();
//The name of car is Audi 
var car4;
car4.getName();//prints Uncaught TypeError: Cannot read property 'getName' of undefined 
//since car4 is not yet instantiated.
//To avoid such type of error the following line can be used
car4 && car4.getName();//checks if car4 is instantiated 
//undefined

/* similarly this can be used for following usecase  */
function Car(name){
var _defaultName = 'Audi';
name = name || _defaultName;
var capitalizeTheName = function(name)
{
return name.toUpperCase();
}
var modifiedName = name && capitalizeTheName(name);
this.getName = function()
{
console.log('The modified name is '+modifiedName);
}
}
var car5 = new Car('Ferrari');
car5.getName();
//The modified name is FERRARI

There are many other use-cases where we can use the similar concept for achieving them

Hope you find this article useful. Happy Coding!

Open for questions , suggestions and discussion

Credits

Cover image: Phot by Christopher Robin Ebbinghaus

Top comments (0)