DEV Community

mixbo
mixbo

Posted on

2

javascript optional chaining

Alt Text

You may write code in javascript like this:

if (foo && foo.bar && foo.bar.baz) {
    foo.bar.baz();
}
Enter fullscreen mode Exit fullscreen mode

We want to call baz() but first need check if foo , foo.bar, foo.bar.baz present. i think this is a little bit more prolixity.

Now you can write code like

foo?.bar?.baz() 
Enter fullscreen mode Exit fullscreen mode

That all, just need use ?. operator, this called optional chainning. you need do something in babel config

// babel.config.js
module.exports = {
  env: {
        .....
      plugins: ['@babel/plugin-proposal-optional-chaining']
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

More optional Channing example:

Dealing with optional callbacks or event handlers

function doSomething(onContent, onError) {
  try {
   // ... do something with the data
  }
  catch (err) {
    onError?.(err.message); // no exception if onError is undefined
  }
}
Enter fullscreen mode Exit fullscreen mode

Optional chaining with expressions

let nestedProp = obj?.['prop' + 'Name'];
Enter fullscreen mode Exit fullscreen mode

Array item access with optional chaining

let arrayItem = arr?.[42];
Enter fullscreen mode Exit fullscreen mode

You can found more api optional chainning

Hope it can help you :)

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

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

Okay