JavaScript Interview Question #65
What does event.preventDefault() do?
DOM, Events & Event Loop Fundamentals Mid-Level Intermediate
Quick Interview Answer
preventDefault asks the browser not to perform the event's normal default action when that action is cancelable. For example, it can prevent a form submission or stop a link from navigating.
Detailed Explanation
preventDefault asks the browser not to perform the event's normal default action when that action is cancelable. For example, it can prevent a form submission or stop a link from navigating.
It does not stop the event from propagating. If propagation also needs to be stopped, that is a separate decision using stopPropagation.
Code Example
const form = document.querySelector("#loginForm");
form.addEventListener("submit", event => {
event.preventDefault();
// Validate and submit using application logic.
console.log("Default form submission prevented");
});