JavaScript — Short Circuit Conditionals
Learn Short-Circuit ‘&&’ Conditionals in three minutes

Udemy Cyber Monday Sale — Thousands of Web Development & Software Development courses are on sale for only $10 for a limited time! Full details and course recommendations can be found here.
This is part one in a two part series this week:
- Short Circuit Conditionals with
&&
- Short Circuit Evaluation with
||
The Example
Consider this scenario: You have a program that must fetch data, but it can only fetch this data if it is online. We might consider using an if statement to first check if we are online, and if we are, fetch the data. Here’s what that code might look like:
if (online){
getData();
}
Awesome. This code works great.
But, what if I told you this code does the exact same thing as the above code:
online && getData();
Logical AND
In JavaScript, the logical AND operator will return true if both operands are true. It returns false in any other scenario. Here are a few simple examples:
true && true
// truetrue && false
// falsefalse && false
// false
There are two important aspects of logical operators inJavaScript that you should know:
- They evaluate from left to right
- They short-circuit
Short circuiting means that in JavaScript when we are evaluating an AND expression (&&), if the first operand is false, JavaScript will short-circuit and not even look at the second operand.
In other words — for the second operand in a logical AND expression to even be looked at, the first operand must be true. This allows us to do some pretty cool stuff with logical AND.
Understanding the Example
Going back to our initial example — remember in this scenario, online
must be true
before we can invoke our getData()
function.
Here’s the short-circuit conditional again:
online && getData();
If online
is false, our equation will short circuit, and our getData()
function will never run. Only when online
is equal to true
, will the second half of the equation ever be looked at/run.
That is why the above code will do the same thing as our typical conditional code:
if (online){
getData();
}
Pretty Cool ay?
Note: If faced with a scenario like this, it is probably better to write your code with an
if
statement and not with a short-circuit conditional. However, it’s important to understand that they are doing the exact same thing.
Closing Notes:
Thanks for reading, and hopefully this was helpful! If you’re ready to finally learn Web Development, check out The Ultimate Guide to Learning Full Stack Web Development in 6 months.
I publish 4 articles on web development each week. Please consider entering your email here if you’d like to be added to my once-weekly email list, or follow me on Twitter.