KhojChakra

Follow us for knowledge, code and other stuff

Follow publication

Understanding Short-circuit Evaluation in Javascript

Gurseerat Kaur
KhojChakra
Published in
2 min readOct 24, 2020

Explore about Short-circuiting in Javascript to make your code clean and beautiful.

In short-circuit evaluation, an expression with logical operators (|| and &&) is evaluated from left to right. So, if the condition is met and the rest of the conditions won’t affect the already evaluated result, the expression will short-circuit and return that result.

Logical OR(||) Operator

This operator will return the first true value. So, it won’t even reach the rest of the conditions and return true as the condition is satisfied.

true || false
// true

So how can we use this?

Let’s take an example

var x;
var y = 'Gurseerat';
var z = 'This will not evaluate';
var name = x || y || z;
console.log(name);
// Gurseerat

Here, since x is undefined, the condition will go on to check y next and store its value in name as it’s a truthy value.

Logical AND(&&) Operator

false && true
// false

This operator will return false as soon as it gets any falsy value and will return the last true value if all the values are truthy.

So how can we use this?

Let’s take an example

var age =  25;
function driveCar() {
return 'Driving Car';
}
var result = age > 18 && driveCar();
console.log(result);
// Driving Car

Here, since age satisfies the condition, the next condition will be checked and the last truthy value is printed.

Let’s take another example,

var age = 25;// Using if condition
if (age > 18) {
action = "Drive Car";
} else {
action= "Can't Drive Car";
}
console.log(action) // Drive Car
// Short-circuiting
greeting = (age > 18 && "Drive Car") || "Can't Drive Car";
console.log(greeting) // Drive Car

In the above example, since the condition has received all truthy values in the AND condition, the rest of the statement is ignored and the last truthy value in AND condition is returned. You can create chains of conditions this way and shorten the length of your code.

Please give a clap 👏 if you liked this post.

Happy Coding! 😄

Other Posts By Us

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

KhojChakra
KhojChakra

Published in KhojChakra

Follow us for knowledge, code and other stuff

Gurseerat Kaur
Gurseerat Kaur

Written by Gurseerat Kaur

Front End Developer | Part time coder, part time learner | Chicken Biryani fan

Responses (7)

Write a response