javascript optional chaining
mixbo
Posted on June 27, 2020
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 :)
💖 💪 🙅 🚩
mixbo
Posted on June 27, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.