Short circuit in javascript

Short circuit in javascript

Short circuit is an interesting concept in JavaScript where we make JavaScript to evaluate a typically unorthodox condition to human eye but make total sense to JavaScript typing engine

So what do I mean my unorthodox anyway?

Let’s take an if statement for example

if (condition) {
  // do something if true 
} else {
  // do something else

If you look at the above statement from a layman perspective, he/she could still understand what the code does just by knowing a little english!!

What that also means is that the code you see is as per the books and that’s how anyone teaches to code

The above code can also be written using ternary operators like below

(condition) ? // do something if true : // do something if false 

However, the reason why ternary operator code is not traditional is because it does not have any keywords in it. Anyone could still understand the above syntax, but when it’s implemented in actual code like

(a === b) ? x = y : x = z

It’s kinda hard for a newbie to understand what the code actually means or how it works. More about ternary operators here

Now, why am I taking about if statements and ternary operators when the heading says Short circuit in JavaScript!

It’s because though there is no performance improvement by using ternary operators instead of traditional if else, it’s a little less to write. And if that makes you insane, get ready for obsession

Short circuiting in JavaScript is all about how you play around logical operators with falsy and truthy values

Before we move any further, let’s understand what falsy and truthy values are

Any value that is considered false when expressed in boolean context is falsy. The value that I’m referring here could be anything. It could be a variable, array, object, condition, etc.

Ok, so a boolean variable can be assigned a value of false and it becomes falsy. But how can I assign a value of false to an array. An array can be empty or undefined but definitely not false. That would make no sense!

Good news is, JavaScript has some predefined values that are considered falsy

The falsy values in JavaScript are

  1. the number 0
  2. the BigInt 0n
  3. the keyword null
  4. the keyword undefined
  5. the boolean false
  6. the number NaN
  7. the empty string "" (equivalent to '')

The above values evaluate to false when coerced by JavaScript’s typing engine into a boolean value, but they are not necessarily equal to each other.

And what are truthy values then?

Everything else except falsy is truthy. Simple ❇️

Fun time!!

Let’s start with an example again. Consider the following if statement

if (condition) {
  // do something if true 

If we use the ternary expression, the above if statement can be written as

condition ? // do something if true : null

If you notice closely, you might see that there is an unnecessary else condition in the ternary expression which basically does nothing. The problem is you can’t neglect it. A ternary expression should always have something to do for both true and false conditions which makes ternary expression not an optimal choice when there’s only if and no else

Now, how can we rewrite this to make it smaller

Time to get obsessed

(condition) && // do something if true 

Like I said, it’s basically how we play around with logical operators

Before we dive into how the code works, it’s necessary understand how logical operators work. It works from left to right and short circuits

What do I mean by short circuit here?

When JavaScript evaluates an AND (&&) expression, if the first operand is false, JavaScript will short circuit and will not even look at what’s next in line

Remember, the logical AND returns true only if all conditions match. In other words, in a given sequence of conditions with logical AND operators will complete its execution successfully only if all conditions are true. The moment any of the condition is false, it just doesn’t matter whether or not the remaining conditions are true. The end result is gonna be false

Simply put, all conditions that comes after the false condition is not gonna affect the result. And if the result is clear even before evaluating all the conditions, it short circuits!

It’s the same principle, JavaScript just short circuits once it encounters a false value and just ignores the remaining conditions and returns to the next line of code

Before I close let’s just see a real example with logical AND (&&) and logical OR (||)

let a, b, x

a = 1
// b = undefined
x = 'I am the default value'

console.log(a && x) // prints 'I am the default value', since a is true
console.log(b && x) // prints undefined, since b is false (short circuits and anything after false is not executed)

console.log(a || x) // prints 1, since a is true (short circuits and anything after true is not executed)
console.log(b || x) // prints 'I am the default value', since b is false

That’s my best explanation of what short circuit is in JavaScript

After all, no one said a bread board logic would NOT be helpful someday in the programming world 🙂

Related Posts

Get The Best Of My Hands Delivered To Your Inbox

Subscribe to my newsletter and stay updated.