When and why to 'return false' in JavaScript?

JavascriptJquery

Javascript Problem Overview


When and why to return false in JavaScript?

Javascript Solutions


Solution 1 - Javascript

Often, in event handlers, such as onsubmit, returning false is a way to tell the event to not actually fire. So, say, in the onsubmit case, this would mean that the form is not submitted.

Solution 2 - Javascript

I'm guessing that you're referring to the fact that you often have to put a 'return false;' statement in your event handlers, i.e.

<a href="#" onclick="doSomeFunction(); return false;">...

The 'return false;' in this case stops the browser from jumping to the current location, as indicated by the href="#" - instead, only doSomeFunction() is executed. It's useful for when you want to add events to anchor tags, but don't want the browser jumping up and down to each anchor on each click

Solution 3 - Javascript

It is used to stop the propagation of the event. You see when you have two elements both with a click event handler (for example)

-----------------------------------
| element1                        |
|   -------------------------     |
|   |element2               |     |
|   -------------------------     |
|                                 |
-----------------------------------

If you click on the inner element (element2) it will trigger a click event in both elements: 1 and 2. It is called "Event bubbling". If you want to handle the event in element2 only, then the event handler has to return false to stop the event propagation.

Another example will be the link onclick handler. If you want to stop a link form working. You can add an onclick handler and return false. To stop the event from propagating to the default handler.

Solution 4 - Javascript

Er ... how about in a boolean function to indicate 'not true'?

Solution 5 - Javascript

I also came to this page after searching "js, when to use 'return false;' Among the other search results was a page I found far more useful and straightforward, on Chris Coyier's CSS-Tricks site: The difference between ‘return false;’ and ‘e.preventDefault();’

The gist of his article is:

> function() { return false; } > > // IS EQUAL TO > > function(e) { e.preventDefault(); e.stopPropagation(); }

though I would still recommend reading the whole article.

Update: After arguing the merits of using return false; as a replacement for e.preventDefault(); & e.stopPropagation(); one of my co-workers pointed out that return false also stops callback execution, as outlined in this article: jQuery Events: Stop (Mis)Using Return False.

Solution 6 - Javascript

When using jQuery's each function, returning true or false has meaning. See the doc

Solution 7 - Javascript

I think a better question is, why in a case where you're evaluating a boolean set of return values, would you NOT use true/false? I mean, you could probably have true/null, true/-1, other misc. Javascript "falsy" values to substitute, but why would you do that?

Solution 8 - Javascript

Solution 9 - Javascript

You use return false to prevent something from happening. So if you have a script running on submit then return false will prevent the submit from working.

Solution 10 - Javascript

When a return statement is called in a function, the execution of this function is stopped. If specified, a given value is returned to the function caller. If the expression is omitted, undefined is returned instead.

For more take a look at the MDN docs page for return.

Solution 11 - Javascript

return false using only if you have some worng in function (by some test) or you want to stop some function, example use return false in end "onsubmit"

Solution 12 - Javascript

Also, this short and interesting link to read through https://www.w3schools.com/jsref/event_preventdefault.asp

Definition and Usage

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.

For example, this can be useful when:

Clicking on a "Submit" button, prevent it from submitting a form
Clicking on a link, prevent the link from following the URL

Note: Not all events are cancelable. Use the cancelable property to find out if an event is cancelable.

Note: The preventDefault() method does not prevent further propagation of an event through the DOM. Use the stopPropagation() method to handle this.

Solution 13 - Javascript

Why return false, or in fact, why return anything?

The code return(val); in a function returns the value of val to the caller of the function. Or, to quote MDN web docs, it...

>...ends function execution and specifies a value to be returned to the function caller. (Source: MDN Web Docs: return.)

return false; then is useful in event handlers, because this will value is used by the event-handler to determine further action. return false; cancels events that normally take place with a handler, while return true; lets those events to occur. To quote MDN web docs again...

>The return value from the handler determines if the event is canceled. (Source: MDN Web Docs: DOM OnEvent Handlers.)

If you are cancelling an event, return false; by itself is insufficient.

You should also use Event.preventDefault(); and Event.stopPropagation();.

>The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. (Source: MDN Webdocs.)

  • Event.stopPropagation(); : To stop the event from clicking a link within the containing parent's DOM (i.e., if two links overlapped visually in the UI).

>The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. (Source: MDN Webdocs.)

Working Demos

In this demo, we cancel an onclick function of a link and prevent the link from being clicked with return false;, preventDefault(), and stopPropagation().

Full Working JSBin Demo.

StackOverflow Demo...

document.getElementById('my-link').addEventListener('click', function(e) {
  console.log('Click happened for: ' + e.target.id);
  e.preventDefault();
  e.stopPropagation();
  return false;
});

<a href="https://www.wikipedia.com/" id="my-link" target="_blank">Link</a>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionzsharpView Question on Stackoverflow
Solution 1 - JavascriptChris Jester-YoungView Answer on Stackoverflow
Solution 2 - JavascriptmattView Answer on Stackoverflow
Solution 3 - JavascriptNadia AlramliView Answer on Stackoverflow
Solution 4 - JavascriptBobby JackView Answer on Stackoverflow
Solution 5 - JavascriptflyingaceView Answer on Stackoverflow
Solution 6 - Javascriptgeowa4View Answer on Stackoverflow
Solution 7 - JavascriptFrank RosarioView Answer on Stackoverflow
Solution 8 - JavascriptJamnaView Answer on Stackoverflow
Solution 9 - JavascriptrhysclayView Answer on Stackoverflow
Solution 10 - JavascripthabibunView Answer on Stackoverflow
Solution 11 - JavascriptAbdul Aziz Al BasyirView Answer on Stackoverflow
Solution 12 - Javascriptjet2016View Answer on Stackoverflow
Solution 13 - JavascriptHoldOffHungerView Answer on Stackoverflow