How does onclick differ from addEventListener()?
1. The main difference
| Characteristic | onclick | addEventListener() |
|---|---|---|
| Number of handlers | Only one - a new one overwrites the old one | You can add several |
| Removal | Just assign null | Via removeEventListener() |
| Flexibility | Only one event (e.g. onclick) | Any event: click, keydown, scroll, input, customEvent |
| Extra options | None | Available (once, capture, passive) |
| Compatibility | Old, supported everywhere | Modern, supported in all modern browsers |
2. Example: overwriting a handler
const btn = document.querySelector('#btn');
// first handler
btn.onclick = () => console.log('First');
// second handler
btn.onclick = () => console.log('Second');In the end, clicking only outputs
Secondbecause the second one overwrote the first.
But with addEventListener() both fire:
btn.addEventListener('click', () => console.log('First'));
btn.addEventListener('click', () => console.log('Second'));On click:
First
Second3. Example of removing a handler
With onclick:
btn.onclick = null; // removes the handlerWith addEventListener:
function handler() {
console.log('click');
}
btn.addEventListener('click', handler);
btn.removeEventListener('click', handler);4. Example with options (available only with addEventListener)
btn.addEventListener('click', handler, { once: true });The handler fires only once and is automatically removed.
This is not possible with onclick.
5. You can assign any events
With onclick you can only use "click", but with addEventListener you can use any type, even a custom one:
element.addEventListener('myCustomEvent', () => console.log('custom event!'));6. An example of the difference in HTML
You can add a handler right in HTML:
<button onclick="alert('Hello')">Click</button>But this is not recommended - it mixes structure (JS inside HTML) and is hard to maintain.
Modern practice is to always use addEventListener() in JS.
Summary
onclick | addEventListener() | |
|---|---|---|
| Can assign multiple handlers | No | Yes |
| Can control behavior (once, capture) | No | Yes |
| Can listen for any events | Click only | Any |
| Can be used directly in HTML | Yes | No |
| Modern standard | Legacy | Recommended |
Conclusion:
onclickis a simple but outdated way, fine for small tasks.addEventListener()is the modern, flexible, and correct way to assign events in JavaScript.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.