DEV Community

Saran Chakravarthi
Saran Chakravarthi

Posted on

JavaScript Demystified: Short-circuiting, nullish coalescing and Optional chaining

Hello Devs! In this blog, I'll walk you through the concepts of logical operator, Short-circuiting, nullish coalescing and optional chaining in JavaScript.

Logical operators:

It is essential to understand the working of logical operators inorder to understand short-circuiting.

There are three logical operators in JavaScript: the AND operator, the OR operator and the NOT operator.

AND operator:

AND operator will return true only if all the values are truthy, else it will return false.

const a = true, b = "hey", c = 0, d = null;
a && b //true
a && c //false
c && d //false
Enter fullscreen mode Exit fullscreen mode

OR operator:

OR operator returns true if atleast one of the values is true, else it will return false.

const a = true, b = "hey", c = 0, d = null;
a || b //true
a || c //true
c || d //false
Enter fullscreen mode Exit fullscreen mode

NOT operator:

The NOT operator will return true if used with a falsy value and it will return false if used with a truthy value.

const a=false, b = "hey"
console.log(!a) //true
console.log(!b) //false
Enter fullscreen mode Exit fullscreen mode

Out of these three operators, the AND operator and the OR operator can be short-circuited.

Short-circuiting:

Short-circuiting can be defined as the phenomenon in programming by which the compiler or the interpreter skips the evaluation of the sub-expressions in an expression, as soon as it determines the final result of that expression.

AND operator:

We know that the AND operator will return true only if all the values are true. So, it can safely return false, as soon as it encounters a falsy value. It does not have to check other values, because if one of the values is falsy, entire expression will turn out to be false.

const a = 12, b = "hello", c = 0, d = true;
console.log(a && b && c && d) // 0;
Enter fullscreen mode Exit fullscreen mode

Here in this example, JavaScript will stop evaluating the expression as soon as it encounters the variable c. Because c is 0 , and 0 is a falsy value.

OR operator:

The OR operator returns true if atleast one of the values is truthy. So, as soon as JavaScript encounters a truthy value, it can stop evaluating the expression.

const a = 0, b = "", c = 12, d = false;
console.log(a || b || c || d) //12;
Enter fullscreen mode Exit fullscreen mode

In this example, JavaScript will stop evaluating as soon as it encounters c, since it's a truthy value.

Before es6, default parameters were not a thing. So programmers used "OR short-circuiting" to get things done.

Let's say you are developing the backend for a bank. There are two types of accounts, zero balance account and normal account. The minimum balance for normal account is 1000, if that is the case, the customer can choose not to enter any value for deposit amount. In the backend, we can check if the deposit amount is present, if it is present, we can set it as the balance, if not, we can set 1000 as the balance. Sounds good?, let's implement this logic.

let dataBase = [];

function createAccount(name, id, depositAmount){
  const newUser = {
    name: name,
    id: id,
    balance: depositAmount || 1000,
  }
  dataBase.push(newUser);
  return newUser;
}

const user1 = createAccount("Alice", 1, 5000);
console.log(user1); //{ name: 'Alice', id: 1, balance: 5000 }
const user2 = createAccount("Bob", 2);
console.log(user2) //{ name: 'Bob', id: 2, balance: 1000 }
const user3 = createAccount("Joe", 3, 0);
console.log(user3) //{ name: 'Joe', id: 3, balance: 1000 }
Enter fullscreen mode Exit fullscreen mode

uh-oh, seems like our logic isn't that good. Notice what happens when the value passed as depositAmount is 0(incase of zero balance account). 0 is a falsy value hence the balance will get assigned with 1000. Which is wrong and bad for your business. What if I tell you there's a way around it?

Nullish coalescing operator.

The nullish coalescing(??) is very similar to the logical OR operator. The difference is nullish coalescing operator treats null and undefined as falsy values and everything else as truthy values.

let name = undefined ?? "John";
console.log(name);//John

let isVerified = true ?? null;
console.log(isVerified); //true
Enter fullscreen mode Exit fullscreen mode

So in the bank account creation example, we could use nullish coalescing operator instead of the OR operator. Trust me, it would save your bank a ton of money.

let dataBase = [];

function createAccount(name, id, depositAmount){
  const newUser = {
    name: name,
    id: id,
    balance: depositAmount ?? 1000,
  }
  dataBase.push(newUser);
  return newUser;
}

const user1 = createAccount("Alice", 1, 5000);
console.log(user1); //{ name: 'Alice', id: 1, balance: 5000 }
const user2 = createAccount("Bob", 2);
console.log(user2) //{ name: 'Bob', id: 2, balance: 1000 }
const user3 = createAccount("Joe", 3, 0);
console.log(user3) //{ name: 'Joe', id: 3, balance: 0 }

Enter fullscreen mode Exit fullscreen mode

Optional chaining:

Has it ever occurred to you, when you try to access a property of a variable you get the following error:

Error: Cannot read properties of undefined
Enter fullscreen mode Exit fullscreen mode

This is because we did not receive the expected object, instead we received undefined. I know this error is annoying.

The optional chaining operator checks whether the referenced object is nullish(null or undefined) or not. If it is nullish , it returns undefined. If not, it returns the actual value of that property.

const person = {
    name: "Joe",
    age: 25,
}

console.log(person.name); //"Joe"
console.log(person.fav?.food); //undefined
Enter fullscreen mode Exit fullscreen mode

connect with me:

I hope you liked this blog. Want to connect? You can DM on Dev.to and twitter.

Discussion (0)