[thelist] "return" in JS question

.jeff jeff at members.evolt.org
Tue Jun 4 14:28:08 CDT 2002


tom,

><><><><><><><><><><><><><><><><><><><><><><><><><><><><><
> From: Tom Dell'Aringa
>
> I understand that when using return in a function, you
> can return a value. I can do
>
> return x;
>
> and return x to the caller of the function.
>
> [snip]
>
> I assume the return; here exits you out of the script -
> is this correct? I've never quite understood the concept
> - return by itself also assumes "return true"..is this
> correct? I've looked it up on the web dozens of times
> yet still am not straight on it.
><><><><><><><><><><><><><><><><><><><><><><><><><><><><><

a return statement always does two things.

1. returns a value to the caller
2. immediately halts further execution

if there isn't an expression assigned to the return statement then it
returns undefined.  here's an example showing the event handler execution
being halted causing the alert() immediately following the return statement
to never be fired:

<a href="JavaScript://"
   onclick="return false; alert('foo')"
>click here</a>

here's an example of the same thing within a function:

function myFunction()
{
  return false;
  alert('foo');
}

and finally, here's an example of a function that uses a return statement to
halt execution of a function that's called from an event handler.  this
function called is wrapped in an alert() so you can see the value the
function is returning.

function myFunction()
{
  return;
}

<a href="JavaScript"
   onclick="alert(myFunction()); return false"
>click here</a>

when you click on the link you should get an alert() dialog with the word
"undefined" in it.

i hope this helps explain it better.

good luck,

.jeff

http://evolt.org/
jeff at members.evolt.org
http://members.evolt.org/jeff/





More information about the thelist mailing list