DEV Community

Ravina Deogadkar
Ravina Deogadkar

Posted on

Replacing a conditional loop with short-circuit evaluation

Hi everyone! Hope everyone is safe and well. Let's discuss the most used technical term in every project Conditional checks. Yes, you heard it right! We deal with if-else loops and multiple nested if-else loops in every project. We can say that they are the main ingredient of our recipes, They add up a spice!

Let's have a look at the traditional condition check example.

Alt Text

This is a simple example, now let's make it more complex. Now let's say if we want to check whether the number is odd and less than 5.

Alt Text

Well, that's a traditional method for checking the condition. Sometimes it's just a single liner code, while sometimes it's multiple nested conditional checks. _If this then that or _if this and this then that. But how we can replace it or make it easier and in an optimized way. Let's look at the other topic we have mentioned, Short-circuit evaluation.

Short-circuit Evaluation

As we are aware of three logical operators &&, ||, ! are evaluated from left to right direction. So we make use of these logical operators in the short-circuit evaluation process. If the first expression satisfies the logical operator condition then the circuit will break and the second expression will not be executed. That's the reason we called them as short-circuit evaluation

Logical AND (&&):

expr1 && expr2 are evaluated for falsy expression, which means if expr1 is false then expr1 will be executed else expr2 will be executed.

Alt Text

Logical OR (||):

expr1 || expr2 is evaluated for truthy expression, which means if expr1 is true then expr1 will be executed else expr2 will be executed.

Alt Text

Logical NOT (!):

!expr1 is evaluated to false if expr1 is true else it is evaluated to true.

Alt Text

How we are going to use them?

We can use them to execute or avoid executing an expression based on some condition. Let's look at examples below for better understanding the concept.

(some falsy expression && expr1)

Alt Text

In this case, condition check doesn't short circuit in the first expression check so the second expression is executed. But, if the first expression is evaluated to falsy condition then the condition check would have short-circuited and the first expression would have been executed.

(some truthy expression && expr1)

Alt Text

In this case, condition check doesn't short circuit in the first expression check so the second expression is executed. But, if the first expression is evaluated to truthy condition then the condition check would have short-circuited and the first expression would have been executed.

Well, that's easier and due to its short-circuit behavior, execution time is subtly optimized.

I think that's a better replacement for the traditional condition check to have condition check and evaluation in the same line.

Happy Coding!

Top comments (0)