event.preventDefault() vs. return false

event.preventDefault() vs. return false is a very important but confusing topic that which one should be used and for what. When we want to prevent other event handlers from executing after a certain event is fired, we can use one of these two techniques.
1. event.preventDefault()
2. return false

1. event.preventDefault() :

2. return false :

event.preventDefault() will prevent the default event from occuring like return false but has some difference and sometimes it will create confusion which will be the best to use and why.

Suppose we are capturing the click event on an anchor tag, otherwise which it would be a big problem if the user were to be navigated away from the current page. If our click handler uses return false to prevent browser navigation, it opens the possibility that the interpreter will not reach the return statement and the browser will proceed to execute the anchor tag’s default behavior.

But over this, if we add event.preventDefault() as the first line in the handler, will guarantee that the anchor’s default behavior will not fire, regardless if the last line of the function is not reached (eg. runtime error).

Suppose if we can place a lot of functions on the onClick event for one element. How can we be sure the false one will be the last one to fire?
preventDefault on the other hand will definitely prevent only the default behavior of the element.

So it depends on the situation, if we don’t have any chance of occurring any error/exception in our code we can use any of them but have chance of error/exception, than better to use event.preventDefault() at the first line in the event handler.

You Might Interested In

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.