How to optimize single if condition in JavaScript

PaperInFlames
2 min readAug 17, 2023

Hi, this article will help you in optimizing single if loop with different approaches.

Scenario 1:

Sometimes we’ve to execute huge code based on a flag as below.

Here we’ve to execute the code only when the user is not null. This can be optimized by simply returning when the flag is null, or else the remaining code will be executed.

Scenario 2:

We’ve to call a method based on a flag, if the flag is true the method should be called.

The above code can be further optimized as shown below

Scenario 3:

Just like the above scenario, based on the flag sometimes we’ve to call two different methods as below

The above condition can be optimized with the help of a ternary operator as below

Bonus:

Here we’ve to assign the user validity based on the below 2 conditions.

The below ternary operator can be optimized as below.

Hope this helps 😀🫠

--

--