You can use optional chaining (?.
) with the bracket notation (object property accessor) by adding the ?.
symbol before the bracket notation, like so:
// ES11+
obj?.['prop']
For example:
// ES11+
const obj = { 'foo-bar': 123 };
console.log(obj?.['foo-bar']); // 'bar'
console.log(obj?.['non-existent']); // undefined
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.