JavaScript 'onclick' event 'return' keyword functionality

Shiroi98 picture Shiroi98 · Oct 19, 2011 · Viewed 93.8k times · Source

I am really new to javascript, and stumbled upon the return keyword. Basically, what is the difference in terms of these 2 statements?

<input type="checkbox" onclick="doAlert()" />

vs

<input type="checkbox" onclick="return doAlert();" />

Essentially, both returned the same results and called the function, but is there more to it? Any help greatly appreciated :). Thanks!

Answer

Y. Shoham picture Y. Shoham · Oct 19, 2011

Returning false from the function, will abort the effect of the checking. Because the native of functions that written hardcoded into html properties (it became some new local function), writing the html without the word "return" will just run the function, and lose its returning value, as if you've wrote:

function doAlert() {
   if(some_condition)
     return false;
   else
     return true;
}
function some_local_function() {
   doAlert();
}

Function some_local_function won't return any value, although doAlert returns.

When you write "return", it's like you wrote the second function like this:

function some_local_function() {
   return doAlert();
}

which preserves the returning value of doAlert, whatever it will be. If it's true - the action will perform (the checkbox will be checked) - otherwise - it will cancel.

You can see live expamle here: http://jsfiddle.net/RaBfM/1/