return false vs preventdefault in js

Return False vs PreventDefault in JavaScript

Often JavaScript developers need to prevent the default behavior of an event, when it is fired. Some developers use preventDefault() for the event, while some return false value for this purpose. In this article, we will learn the difference between return false and preventDefault() in JavaScript.


Return False vs PreventDefault in JavaScript

Let us say you have the following anchor link on your page.

<a href="/home">home</a>

Bu default, when a user clicks this link, the web browser will take them to /home mentioned in the href attribute of the anchor link. Sometimes you may need to prevent this default behavior and do something else instead, when a user clicks this link.

Some developers return false value when this event is triggered. In the code below, we have used jQuery to handle click even but it also works for plain JS code.

$('a').click(function () {
    // custom handling here
    return false;
});

On the other hand, some developers use preventDefault() function.

$('a').click(function (e) {
    // custom handling here
    e.preventDefault();
});

When you are using jQuery, they both give the same result, that is, they both prevent the default behavior as well as stop the event from bubbling (propagating) to other events.

When you are using plain JS e.preventDefault() will prevent the default behavior while e.stopPropagation() will stop the event from bubbling up to other events. But return false will only prevent default event handler from running, it does not stop event propagation.

In this article, we have learnt the difference between return false and preventDefault(). Both are used to prevent default event handler in JavaScript as well as jQuery. It is also useful in other JS libraries. You can use either of them for simple things such as preventing clicks, form submissions, etc. But if you need to prevent default even handler but allow event propagation, you need to use the appropriate function as described above.

Also read:

How to Get Unique Values from JS Array
How to Disconnect User from SSH Connection
How to Get HDD Temperature in Linux
How to Install New Fonts in Linux
How to List GPG Keys in Linux

Leave a Reply

Your email address will not be published. Required fields are marked *