DEV Community

mixbo
mixbo

Posted on

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 :)

Top comments (0)