itsopensource

Optional Chaining

January 17, 2020

TypeError: Cannot read property '<property>' of undefined has bugged every javascript developer enough. While expecting a response from APIs, we need to add several && to make sure our code doesn’t break. This may be not a problem while dealing with 2 levels of the nested object, but while dealing with large data objects this can be a nightmare. Unnecessary/redundant lines of code, change all occurrences if the structure of object changes, etc.

But we are now in 2020, the game has been changed with Optional Chaining proposal Stage-4.

Now no more redundant lines, but adding ? before . takes care of everything. This traverse the property chain one by one and returns undefined if the property doesn’t exist (instead of throwing TypeError), else return the value.

Consider following JSON object

{
  solar_system: {
    earth: {
      asia: {
        india: {
          delhi: {
            good_food: true
          }
        }
      }
    }
  }
}

The javascript code would look like

const data = `<above JSON object>`;
const hasGoodFood = 
  data.solar_system &&
  data.solar_system.earth &&
  data.solar_system.earth.asia &&
  data.solar_system.earth.asia.india &&
  data.solar_system.earth.asia.india.delhi &&
  data.solar_system.earth.asia.india.delhi.good_food;

But with optional chaining the whole code can be put into 1 line

const data = `<above JSON object>`;
const hasGoodFood = data?.solar_system?.earth?.asia?.india?.delhi?.good_food;
// true;

Also

const data = `<above JSON object>`;
const hasGoodFood = data?.solar_system?.earth?.asia?.philippines?.delhi?.good_food;
// undefined;

The object don’t have philippines, instead of throwing TypeError it returns undefined.

This is a TC39 stage-4 proposal. This means The addition will be included in the soonest practical standard revision. in all the modern browsers.

But if you do not want to wait for using this already into your code, you can include the Babel plugin in your project to support this already.

If you want to see this in action, this can be enabled in chrome browser with the following steps:

  1. Go to chrome://flags
  2. Search for experimental javascript
  3. Toggle the feature to enable
  4. Relaunch the browser.

*Always keep an eye on TC39 proposals for amazing additions to our beloved Javascript


Somethings never change

Without Optional chaining

Somethings do :)

With Optional chaining


Trishul Goel

Trishul Goel is a frontend developer, loves to talk about modern Javascript, frontend architecture, opensource, promotes PWAs (#teamWeb) and is expert in developing browser extensions..
@trishulgoel