38. What is the difference between event.preventDefault() and event.stopPropagation() methods in JavaScript?
medium
In JavaScript, both `event.preventDefault()` and `event.stopPropagation()` are methods used to prevent or control the behavior of events. However, they serve different purposes:

`event.preventDefault()` is used to prevent an event from executing its default behavior. When you call this method on an event object, it will stop the execution of the default action associated with that event.
const form = document.getElementById('my-form');
const submitButton = document.getElementById('submit-button');

form.addEventListener('submit', (e) => {
  e.preventDefault();
  // validation logic here
});

submitButton.addEventListener('click', () => {
  form.submit();
});
In this example, when the user clicks on the submit button, `event.preventDefault()` is called to prevent the default behavior (form submission). If the validation logic returns true, you can call `form.submit()` to actually submit the form.
`event.stopPropagation()` is used to prevent an event from propagating up the DOM tree. When an event occurs on an element, it may trigger other events on its parent or sibling elements. You can use `event.stopPropagation()` to prevent these events from occurring.
const modalWindow = document.getElementById('modal-window');
const form = document.getElementById('my-form');

modalWindow.addEventListener('click', (e) => {
  e.stopPropagation();
  // close modal logic here
});

form.addEventListener('click', (e) => {
  if (!e.target.closest('#modal-window')) {
    e.stopPropagation();
    // close modal logic here
  }
});

In this example, when the user clicks outside the modal window, `event.stopPropagation()` is called to prevent the click event from propagating up the DOM tree. Similarly, when the user clicks on the form, if the clicked element is not inside the modal window, `event.stopPropagation()` is called to prevent the click event from triggering the close modal logic.
In summary, `event.preventDefault()` is used to prevent an event from executing its default behavior, while `event.stopPropagation()` is used to prevent an event from propagating up the DOM tree.