1

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.

3
  • 5
    Why define a variable at all, instead of document.getElementById('myElement')?.addEventListener()? Commented Apr 11, 2022 at 15:05
  • 2
    I'd venture that the clarity of your first example trumps other approaches, even the optional chaining approach suggested by others. By packing multiple operations into the smallest footprint, readability suffers and debugging becomes harder. Commented Apr 11, 2022 at 15:12
  • I'm fairly sure that you don't have a requirement for declaring the variable, but it would be nice if you could confirm that a simplification that adds an event listener to the element if it exists is all you are looking for and that you don't actually have a requirement to also have an element variable declared. Right? Commented Apr 11, 2022 at 15:47

1 Answer 1

5

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 or undefined), the expression short-circuits with a return value of undefined.

document.getElementById('myElement')?.addEventListener('click', (e) => { ... });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.