Intermediate JavaScript Interview QuestionsIntermediateComparison
JavaScript · Question 54
What is the difference between preventDefault(), stopPropagation(), and stopImmediatePropagation()?
Direct answer
preventDefault requests cancellation of the event’s default browser action, stopPropagation stops further propagation through ancestors/descendants, and stopImmediatePropagation also prevents later listeners on the same target from running.
preventDefault()— affects the default action when the event is cancelable, such as navigation or form submission; it does not inherently stop propagation.stopPropagation()— stops the event from continuing through the propagation path, but other listeners already registered on the same current target may still run.stopImmediatePropagation()— stops propagation and prevents subsequent listeners on the same target from executing for that event.
These methods solve different problems, so using stopPropagation() everywhere to “fix” event bugs can break analytics, delegation, overlays, or other components that legitimately observe the event.
Also remember that some listeners can be registered as passive, in which case the browser does not allow that listener to cancel the default action with preventDefault().