149

When and why to return false in JavaScript?

0

13 Answers 13

100

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.

Sign up to request clarification or add additional context in comments.

6 Comments

This is particularly good if you want an AJAX form that submits without reloading the page - but also works by submitting and reloading the page when javascript is not available.
Return false is actually overkill for preventing the default action when creating event handlers and can lead to fragile code. Explanation and examples at Douglas Neiner's post here fuelyourcoding.com/jquery-events-stop-misusing-return-false
With jQuery, its better to use event.preventDefault() for this functionality. I believe returning false is deprecated and doesn't always work anymore.
Sometimes the return false is in the method, does this changes anything ?
@onetwopunch In fact when I changed it to e.preventDefault() solved a problem with one of my functions based on a namespace touch event. Don’t know why but you gave me the idea. Thanks.
|
72

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

6 Comments

Of course, the 'href="#"' is bad practice, but your overall point still stands :-)
@vol7ron: the alternative is a real URL that acts as an alternative for those people without javascript. Otherwise, they'll just be clicking on a link with nothing happening.
@vol7ron: of course, it's down to each and every developer (or site owner) to determine exactly how much of the potential user base they want to cater for. In a case like this, however, where the option that targets more people is SO simple, I don't see why you wouldn't opt for it. Also, bear in mind that it's not just about people explicitly disabling javascript; it can be: someone else imposing that decision on them, a network problem downloading the JS file, a bug in one line of the JS causing it all to fail. Also, it's quite nice if right-click->open in new tab still works.
It's not less than 1% of users. Many people use extensions like NoScript for a reason. To turn things like javascript off purposefully.
@vol7ron The other scenario to consider is when "javascript breaks" (due to a syntax error higher up in the page). Having non-js fallbacks gives you some safety nets for this scenario. (Google.com was down for almost 30 minutes a while back due to a js syntax error!)
|
28

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.

1 Comment

the first part of this answer is wrong: returning false from an event handler will prevent the default action associated with an event; you could also do this via calling event.preventDefault() or setting event.returnValue = false (IE); in order to stop the event from bubbling, you'll have to call event.stopPropagation() or setting event.cancelBubble = true (IE)
18

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

2 Comments

Even in FileNotFound false is still not true ain't it?
Gleb: There's no "in FileNotFound", it's a TDWTF in-joke: thedailywtf.com/Articles/What_Is_Truth_0x3f_.aspx
15

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.

1 Comment

I have to notice here after some code test that: in jquery, function() { return false; } IS EQUAL TO function(e) { e.preventDefault(); e.stopPropagation(); }, but in pure js, it not the same, function() { return false; } IS EQUAL TO function(e) { e.preventDefault(); } actually. It does not stop propagation.
6

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

Comments

3

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?

Comments

2

When you want to trigger javascript code from an anchor tag, the onclick handler should be used rather than the javascript: pseudo-protocol. The javascript code that runs within the onclick handler must return true or false (or an expression than evalues to true or false) back to the tag itself - if it returns true, then the HREF of the anchor will be followed like a normal link. If it returns false, then the HREF will be ignored. This is why "return false;" is often included at the end of the code within an onclick handler.

Comments

1

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.

Comments

1

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.

Comments

1

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"

Comments

1

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.

1 Comment

Consider using: developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault as opposed w3schools. But solid answer.
1

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>

1 Comment

The DOM on-event handlers page has changed significantly and no longer contains the quote. Here's a cache: developer.mozilla.org.cach3.com/en-US/docs/DOM/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.