loading...

javascript optional chaining

ihavecoke profile image mixbo ・1 min read

Alt Text

You may write code in javascript like this:

if (foo && foo.bar && foo.bar.baz) {
    foo.bar.baz();
}

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

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

Posted on by:

ihavecoke profile

mixbo

@ihavecoke

Web developer in Longbridge

Discussion

markdown guide