The preventDefault stops the default browser behaviour when an event is fired like not redirecting the page on url click etc.
The returnfalse also stops the default browser behaviour when an event is fired and does not let the event propagate. The callback execution is also stopped is returned immediately when called.
Following is the code for PreventDefault() and return false in JavaScript −
Example
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-weight: 500; font-size: 18px; color: blueviolet; } </style> </head> <body> <h1>preventDefault() Vs return false</h1> <a href="https://www.google.com" class="link">Google</a> <input type="checkbox" class="check" onclick="return checkedOrNot(false)"/><br /> <div class="result"></div> <br /> <div class="result"></div> <h3>Click on the above link or checkbox to see preventdefault() or return false in action</h3> <script> let resEle = document.querySelectorAll(".result"); let linkEle = document.querySelector(".link"); let checkEle = document.querySelector(".check"); function printText(event) { resEle[0].innerHTML ="preventDefault() has stopped the default link behaviour"; event.preventDefault(); } function checkedOrNot(val) { if (val === true) { checkEle.checked = true; } else { resEle[1].innerHTML = "return false prevented the checkbox from being checked"; return false; } } linkEle.addEventListener("click", printText); </script> </body> </html>
Output
On clicking the ‘Google’ link −
On clicking the checkbox −