Nullish coalescing and optional chaining Explained!

In JavaScript, there are two operators - nullish coalescing and optional chaining. Nullish coalescing is used to check whether a value is nullish or not. The Optional Chaining Operator is there to safely call upon a variable or function without knowing if it exists or not./

Nullish coalescing :

The nullish coalescing (??) operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

const s = null;
const str = s ?? 'default string';
console.log(str); // Output: "default string"

const a = 0 ?? 42;
console.log(a); // Output: 0

In the above example, s variable is defined as null, so that str variable will return 'default string'.

The value of a variable is not null or undefined that's why it returns the left-hand side means 0.

  • The nullish coalescing operator can be seen as a special case of the logical OR (||) operator.

  • Logical OR returns the right-hand side operand if the left-hand side operand has a falsy value.

const a = 0;
console.log(a || 22); //Output: 22
console.log(a ?? 22); //Output: 0

Optional Chaining:

The optional chaining (?.) operator accesses an object's property or calls a function.

If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error.

const user = {
  name: 'Sudipta',
  address: {
    city: 'Kolkata'
  }
};

const state = user.state?.name;
console.log(state); // Output: undefined

In the above example, user.state does not exist, but when we try to access it, it won't throw an error, it returns undefined.

Nullish coalescing and optional chaining used together:

Optional chaining is often used together with nullish coalescing, which is the ability to fall back to a default value when the primary expression evaluates to null or undefined.

const user = {
  name: 'Sudipta',
  address: {
    city: 'Kolkata'
  }
};

const state = user.state?.name ?? "No state is present in the user object";
console.log(state); //Output: No state is present in the user object

In the above example, state is not present in the user object, so that the left side of ?? operator returns undefined, and using ?? operator we can show the default message "No state is present in the user object".

Thanks for reading. Hope my blog helps you to understand the concepts!😊