DEV Community

Dinesh Pandiyan
Dinesh Pandiyan

Posted on

22 4

Short Circuit Assignment in JavaScript

JS short circuit assignment

tldr; Assign default value to a variable using short circuit evaluation, when expected value is not found.

JavaScript is amazing. But most of the times we end up scratching our heads for accomplishing a simple task, like, assigning a default value to a variable when the expected value is not found (probably null/undefined).

Let's take this example,



const person = {
    name: 'Jack'
};

const name = person.name;
const greetings = 'Hello' + ', ' + name + '!';
console.log(greetings) // => 'Hello, Jack!'


Enter fullscreen mode Exit fullscreen mode

Now if the name key is not available in person object,



const person = {};

const name = person.name; // name is undefined here
const greetings = 'Hello' + ', ' + name + '!';
console.log(greetings) // => 'Hello, undefined!'


Enter fullscreen mode Exit fullscreen mode

This problem is very common in JavaScript world. We usually tackle scenarios like this by assigning default values.



// we either use if case
let name = 'Sunshine'; // default value
if (person && person.name) {
    name = person.name;
}

// or we use ternary operator
const name = person && person.name ? person.name : 'Sunshine';

const greetings = 'Hello' + ', ' + name + '!'; // name will never be undefined now
console.log(greetings) // => 'Hello, Jack!'


Enter fullscreen mode Exit fullscreen mode

The above case was a simple scenario because we had to check only one variable. But if we need to assign based on multiple variables, then we end up writing messy not-easy-to-read code.



let foo, bar, baz;

// if case mess
let name;
if (foo) name = foo;
else if (bar) name = bar;
else if (baz) name = baz;
else name = 'Sunshine';

// ternary operator nightmare
const name = foo ? foo : (bar ? bar : (baz ? baz : 'Sunshine'));



Enter fullscreen mode Exit fullscreen mode

To save the world from messy code, there's one more sweeter trick to assign default values.

Short Circuit Assignment ✨

This is a shorter and cleaner way of assigning default values in JavaScript. This works based on short-circuit evaluation of logical operators where the first truthy value is returned.



const name = person.name || 'Sunshine';

// if you're not sure if person object is defined
const name = (person && person.name) || 'Sunshine';

// can be used with as many variables as needed
let foo, bar, baz;
bar = 'Bar-da-Jack';
// first truthy value will be assigned to name
const name = foo || bar || baz || 'John'; // => name = 'Bar-da-Jack'


Enter fullscreen mode Exit fullscreen mode

The evaluation circuit breaks when a truthy value is found, and is returned to the assignment.

Any value which is not false, 0, '', "", null, undefined and NaN is considered to be truthy in JavaScript.

Note: Keep in mind, if you're expecting 0 as a value in a variable, this trick might not work as expected, as 0 is considered falsy in JavaScript.

So, fellow comrades, short-circuit and save the JavaScript world from messy code structures, one line at a time! πŸŽ‰

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (1)

Collapse
 
jagerbom profile image
Zachary Truong β€’

I'm doing a review of my JS knowledge and this is an amazing article to enrich my learning.
Thanks.

nextjs tutorial video

Youtube Tutorial Series πŸ“Ί

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series πŸ‘€

Watch the Youtube series

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay