DEV Community


javascript optional chaining

ihavecoke profile image mixbo ・1 min read

Alt Text

You may write code in javascript like this:

if (foo && && {;

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

Now you can write code like


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']

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

Optional chaining with expressions

let nestedProp = obj?.['prop' + 'Name'];

Array item access with optional chaining

let arrayItem = arr?.[42];

You can found more api optional chainning

Hope it can help you :)

Discussion (0)

Forem Open with the Forem app