Reputation: 95
Is it possible simplify this
var element = document.getElementById('myElement');
if(element)
element.addEventListener('click', (e) => { ... });
into something like this?
if(var element = document.getElementById('myElement'))
element.addEventListener('click', (e) => { ... });
Thank you.
Upvotes: 1
Views: 54
Reputation: 89432
You can use optional chaining.
The
?.
operator is like the.
chaining operator, except that instead of causing an error if a reference is nullish (null
orundefined
), the expression short-circuits with a return value ofundefined
.
document.getElementById('myElement')?.addEventListener('click', (e) => { ... });
Upvotes: 5