DEV Community

Vishnu Damwala
Vishnu Damwala

Posted on • Originally published at meshworld.in

Short Circuit Conditionals With Logical AND(&&) Operator - JavaScript

The short circuiting was meant to stop the further execution based on boolean operations. With Logical AND(&&) operator, if the false value of expression has already been determined than further execution will not happen.

Precedence for Logical AND is from left to right.

Example

Let us consider, we've an application on our device which uses Unsplash API to retrieve data from it. If the device is not connected to internet, then no data will not be fetched.

navigator.onLine

  • We will be using navigator.onLine property to verify whether the user is connected to the internet or not.
  • The navigator.onLine property return true if connected to internet else false.

Example using if condition

if (navigator.onLine) {
  fetchUnsplashImages();
}

Example using short circuit conditional

  navigator.onLine && fetchUnsplashImages();

Now the code is just a single line navigator.onLine && fetchUnsplashImages();. Here the fetchUnsplashImages() function only executes when navigator.onLine return true i.e user is connected to internet.

Read others post on our site MeshWorld

Happy coding

Top comments (2)

Collapse
 
brogrammerben profile image
Ben

Except don’t do this. This is the antithesis of easily digestible code. Static code analyzers will also hate this because the complexity increases unnecessarily. Just because you can doesn’t mean you should.

Collapse
 
cooldashing24 profile image
Vishnu Damwala • Edited

Thanks for your feedback. What should be its alternative?