When and why to 'return false' in javascript?
Er ... how about in a boolean function to indicate 'not true'?
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.
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.
http://jqueryfordesigners.com/jquery-tabs/ This will give you a good, easy example. Watch the screencast or check out the demo code.
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?
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