DEV Community

Cover image for Short Circuiting JavaScript
bob.ts
bob.ts

Posted on

Short Circuiting JavaScript

A while back, I came across a pattern that became very useful. It allowed me to cleanly determine if a diagnostic mode was on and log information to the console.

It's a pretty pattern ... and logical. It also causes me some grief at times.

The Pattern

Here's the code.

// isDebug state will allow the console.log fire, if true
let isDebug = false;

// here is the conditional
(isDebug) && console.log('debugging this code', { isDebug });

This seems pretty cool, and I think it is.

Basically, if isDebug is ...

  • true, the && (and) forces the code on the right to execute ... console.log.
  • false, the && (and) logic in JavaScript does not attempt to execute the code on the right ... no console.log.

And More

Then, this was suggested to me ... a similar pattern.

let counts = {};

data.forEach(i => {
  // more code here
  (i.name in counts) || (counts[i.name] = 0);
  counts[i.name]++;
  });

Basically, this code is using similar logic to the isDebug logic above.

  • If the name is in the object counts, then move to the next line and add one.
  • If the name is NOT in the object counts, then add the key with an initial value of zero which then gets incremented by one on the next line.

With jshint.com, we get "Expected an assignment or function call and instead saw an expression." on the two lines in question here.

Looking for more detail, I found this documentation on why this issue is raised ... reading this, the issue is raised for the left-hand portion of the code in question, totally ignoring the potential of the code on the right-hand side.

Going even further, I found this documentation that showed this pattern as a "Short Circuit" and, if needed, allowShortCircuit is an option for the linter.

Conclusion

This is an interesting, terse pattern that seems to have gained some traction: Using an expression to determine which branch to follow in (or **short circuit out of) the code.

I will say, that on a personal level, I like the first pattern for conditional diagnostic information while the second pattern felt awkward, but readable.

Oldest comments (0)