DEV Community

Ganesh R
Ganesh R

Posted on • Originally published at ganes.dev

3 1

Nullish coalescing and Optional chaining

Canonical Url: https://ganes.dev/nullish-coalescing-and-optional-chaining/

In this post, I'll explain about two of the recent additions to the javascript. Nullish Coalescing and Optional Chaining.

Nullish Coalescing

When accessing a property of a object in javascript, we usually provide a fallback value incase the property is not present (undefined) or null.

For Example. Consider a object like this

const Blog = {
  showPost: false,
  blogTitle: 'A new Post',
  animationDuration: 0,
  blogSubTitle: '',
  nullVal: null,
};

A usual way for this handle fallback is by using the || operator

const undefinedValue = Blog.someValue || 'default value'; // result: default value
const nullValue = Blog.nullVal || 'some other default value'; // result: some other default value

// Other Cases
const showPost = Blog.showPost || true; // expected: false, result: true
const postAnimationDuration = Blog.animationDuration || 400; // expected: 0, result: 400
const blogSubtitle = Blog.blogSubTitle || 'Subtitle'; // expected: '', result: Subtitle

The first two examples work as we expected, but for other cases we get the result as right hand side value of || operator as shown in the above example.This is because the values on left hand side already evaluate to falsy in Javascript.

For this problem, we use the Nullish Coalescing operator

const showPost = Blog.showPost ?? true; // expected: false, result: false
const postAnimationDuration = Blog.animationDuration ?? 400; // expected: 0, result: 0
const blogSubtitle = Blog.blogSubTitle ?? 'Subtitle'; // expected: '', result: ''

Once we switch to nullish Coalescing, we get the expected results.

Optional Chaining

When accessing a nested property in the object, we usually have to check whether intermediate properties are present.

For Example, Consider a object with nested properties like this

const Person = {
  name:'Ganesh'
  address:{
    home:'Home Address',
    work:'Work Address'
  }
}

const homeAddress = Person.address.home

Since, we are accessing nested values, if address is undefined we get an error like Cannot read property home of undefined. In this case, we use Optional Chaining operator.

To use the optional chaining operator, we have to put a ? before accessing a property. So above example changes to this

const homeAddress = Person?.address?.home;

// We can also use this for functions
someObj?.func();

Combining both of them

Although these both operators are good seperately, when combined they become very useful.
I can take the sample example and nullish coalescing operator at the end of it.

// The result defaults to Home if left side of nullish coalescing is null (or) undefined.
const homeAddress = Person?.address?.home ?? 'Home';

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️