Jump to content

about return statement


newrehmi

Recommended Posts

hello all,first of all, i am sorry if this question is very noob. as if you want to know, i have made a lot of small project using javascript, but this question still stuck in my mind since I never use this 'return' thingy in any of my script. and have made some search through 6 pages of w3 javascript forum, just to grasp the concept of 'return' usage. So, if anyone could lend me a hand, in most simpler example just for me to grasp the concept, what does that thing do, because i believe this 'return' thing is a must know function for every programmer lived or I ll just live in a shame then..this is the example that i've made, but still can't work.

<head><script type='text/javascript'>function returnFalse()	{	alert('you will not going anywhere'); //but the the form still load the 'lol.php'	return false;	}</script></head><body><form action='lol.php' method='get'><input type='text' /><input type='submit' onsubmit='returnFalse()' /></form></body>

Thank you soooo much!!!!

Link to comment
Share on other sites

return just returns a value from a function (or in some cases just exits the function). For example:

function add(x, y) {   var sum = x + y;   return sum;}

With this function, you pass in two arguments. The function adds them together and returns the result. So if you do:var mySum = add(3, 4);the variable mySum will equal 7 because the function added the two arguments (3 and 4) and returned the result (7). The return value was assigned to mySum.In the case of the example you provided, the return value is always the boolean false. When false is returned from an event handler, it prevents the default action that occurs when that event fires. So in the onsubmit event, when false is returned, the form will not be submitted. Similarly, in an onclick event of an <a> tag, when false is returned, the link will not be followed.If no return statement exists in the function or the return value is true, then the default action will occur.EDIT: I just noticed that you have the onsubmit event on the submit button itself. Inputs do not have a submit event. Move the onsubmit to the form, and you'll see that it prevents the submission.

Link to comment
Share on other sites

You'll also want to return the value of the function to the event itself, simply calling it won't be enough in my experience.Using your example, the code will look like the following, taking ShadowMage's correct suggestion in account:

<head><script type='text/javascript'>function denySubmit()    {    alert('you will not going anywhere'); //but the the form will now NOT load the 'lol.php'    return false;    }</script></head><body><form action='lol.php' method='get' onsubmit='return denySubmit()'><input type='text' name='myText' /><input type='submit' /></form></body>

The reason for this, is that the onsubmit attribute of the form-element, is just a handler. When the event occurs, the handler will first be called, and as it calls another function, the return value of your function must be returned from the handler to the event itself to cancel the event.I also added a name attribute to your textfield, as that will be the accessible name for this field within lol.php. You can also choose to use the POST method instead of GET, if you want to be save and not overflow or expose the data in the URL.To add to ShadowMage's reply, the return-statement is used to return code execution from anywhere within a function back to wherever it was called, and returning a value with it is only optional. You can for instance also return from a function if a certain condition is met, to prevent the rest of the function. A simple example below:

function test(){      if (document.getElementById("myCheckbox").checked != "true") return;      //this code will not be executed it the checkbox is not checked      document.forms[0].submit();}

If your function is returning a value, you can use this value when you call it, just as if the function call were a variable or property. Doing so will require the function to always return a value though, and result in an error if it for some reason doesn't.

Link to comment
Share on other sites

EDIT: I just noticed that you have the onsubmit event on the submit button itself. Inputs do not have a submit event. Move the onsubmit to the form, and you'll see that it prevents the submission.
thanks. I tried your suggestion, on which i moved the onsubmit='returnFalse()' to form.
<form action='lol.php' method='get' onsubmit='returnFalse()'><input type='text' /><input type='submit' /></form>

It still didn't work.But, when I replace the function in onsubmit='returnFalse()' with just a statement onsubmit='return false', it worked! so what is the explanation?

<head><script type='text/javascript'>function returnFalse()	{	return false;	}</script></head><body><form action='lol.php' method='get' onsubmit='return false'><input type='text' /><input type='submit' /></form></body>

thank you soo much!

Link to comment
Share on other sites

Just as I explained, the onsubmit handler is using a value. If you return false from it, it will of cource cancel the event, but if you only call a function, it will not, regardless of the return value of that function. Unless you RETURN the return-value of the function like in above example :)This might seem a little weird for you in the beginning. But this eventhandler is, if you want to know, a separate code scope from the event itself. It will only cancel the event if it returns a value, just like your function does. If the handler calls a function itself, the return value must be returned from the handler too.

Link to comment
Share on other sites

Just as I explained, the onsubmit handler is using a value. If you return false from it, it will of cource cancel the event, but if you only call a function, it will not, regardless of the return value of that function. Unless you RETURN the return-value of the function like in above example :)This might seem a little weird for you in the beginning. But this eventhandler is, if you want to know, a separate code scope from the event itself. It will only cancel the event if it returns a value, just like your function does. If the handler calls a function itself, the return value must be returned from the handler too.
thank you for you time! sorry i posted just after you post, so i didnt read your post yet. Okay, i started to grasp just this part of return usage. How about other usage if you can give some example in some big project? i've made some lot of validation script, random generating, math, html re-styling and currently entering xml and etc, but never used this 'return' thingy.Thanks! :)
Link to comment
Share on other sites

also of note, all functions will return something, regardless of wether you return anything yourself. The value will be undefined however.

Link to comment
Share on other sites

How about other usage if you can give some example in some big project?
What other usage? There aren't really that many uses for return. It is used (as Jack more correctly stated) 'to return code execution from anywhere within a function back to wherever it was called' passing an optional value with it.Look at the example I gave you in my first post (the add function). That demonstrates how return is used to return a value from a function to be used later. Jack's example:
function test() {   if (document.getElementById("myCheckbox").checked != "true") return;   //this code will not be executed it the checkbox is not checked   document.forms[0].submit();}

Demonstrates how return is used without passing a value. This technique essentially "cancels" the code execution within the function and returns it to the previous scope (where the function was called).I personally don't use this technique very often as it seems unsemantic to me. In my eyes, return should return a value. I prefer to just write the code inside an if statement.

Link to comment
Share on other sites

Look at the example I gave you in my first post (the add function). That demonstrates how return is used to return a value from a function to be used later. Jack's example:
yeah, i just tried your example. It makes thing clearer now, so how about this code:
<head><script type='text/javascript'>function calc(x,y)	{	var sum = x + y;	var rum = x * y;	return rum;	return sum;	}document.write(calc(5,2));</script></head>

it does read the rum but not the sum, because the value is 10. So, is it because it only read the first return ever existed in a function?

Link to comment
Share on other sites

Correct, the return-statement returns code execution, so really any code that follows it is skipped. You cannot return multiple values precisely because of this, the only way of doing so would be by combining the values in one value, like an array (like Deirdre's_Dad explains below). You can also make the calc(x,y) function callable with a third parameter that is of boolean value, to indicate whether you want to add or multiply, and return the appropriate value by conditioning on the value of this parameter.

<head><script type='text/javascript'>function calc(x,y,multiply)    {    var sum = x + y;    var rum = x * y;    if (multiply == true) return rum;    //else    return sum;    }document.write(calc(5,2,false));  //7document.write(calc(5,2,true));   //10</script></head>

There are a lot of different ways to write this function. In my example here I've chosen an IF-condition to check on the value of the third parameter, but you could also use a conditional statement to compress this into one line:

<head><script type='text/javascript'>function calc(x,y,multiply)    {    var sum = x + y;    var rum = x * y;    return (multiply == true) ?rum :sum;    }document.write(calc(5,2,false));  //7document.write(calc(5,2,true));   //10</script></head>

Or if this code is all you need, even more compressed:

<head><script type='text/javascript'>function calc(x,y,multiply)    {    return (multiply == true) ?x*y :x+y;    }document.write(calc(5,2,false));  //7document.write(calc(5,2,true));   //10</script></head>

(notice I check the value of the multiply parameter if it is of boolean TRUE, you could also leave the equality check if you're sure the parameter is always a boolean)

Link to comment
Share on other sites

If you need to return multiple values, consider using an object or an array. The following is a shortcut:

function calc(x,y)	{	var sum = x + y;	var rum = x * y;	return [sum, rum]; // creates the array before returning it	}var arr = calc(5, 2); // stores the returned array in arrdocument.write(arr[0]);document.write(arr[1]);

Link to comment
Share on other sites

But I suppose if multiplication or addition is all you want, you probably don't need both of these values returned by the same function at the same time. For other cases, this is the way to do it though.There is another option to 'return' multiple values, but this is more like a hack and better done in OOP context.You can instead of hard returning a value, also change a variable or property that was created outside the function scope. If you change such a value from within the function, you don't need to return it from the function as it is already avaliable outside. This is not recommended programming though. If such variable management is necessary, consider learning the way of OOP programming instead. OOP stands for Object Oriented (Programming), and is what (I think) Deirdre's_Dad refers to with "using objects".

Link to comment
Share on other sites

just using objects is far from qualifying as OOP programming. It just happens that everything in Javascript is an object. JS is a functional/prototypal natured programming language that can be written to mimic psuedo-classical conventions and patterns, mostly through the use of closures to create objects (that you could "call" a class in this context) with private variables/methods.edit: what Jack is trying to say is you should refrain from using global variables, as it is arguably Javacripts worst design feature. The ability to pass and return data to/from functions is a step in avoiding polluting the global space. Most developers create a namespace, by creating one global variable, say

 APP = {};

and attaching all their code to that. From within that, they would create object to contain methods or widgets, with the intent of maintaining some sort of state, and for organization and convenience.

Link to comment
Share on other sites

That's right. I totally forgot about "normal use" of objects and assumed the use was referring to OOP.I think my only use for global variables is/was for preloading images with javascript, but then again, I don't use that anymore either because of the sprite-technique.My own reasoning behind not recommending global variables is that this scope is used to declare functions only, in the head section of your page. I see this section as a declaration of modules, and no actual execution of code.

Link to comment
Share on other sites

Thanks a lot everyone for the answer. :)

The ability to pass and return data to/from functions is a step in avoiding polluting the global space.
May you elaborate more on this quote please? How to pass data from function to a function without declaring a global variable? Is it by always keep on re-accessing/creating the object? and what happened if the global space is polluted, will it make our browser very slow? Sorry for the noob question :)
Link to comment
Share on other sites

It's about declaring one global variable (the so called "namespace"), and then assign everything else (functions and other variables) within it. The data that is passed "back and forth" is really variables within the namespace variable.The terminology in JavaScript is very confusing... strings, numbers, null, functions and arrays are all "objects", and an "object" is a collection of "objects". Except strings, numbers, nulls and functions are special kinds of objects that are stored "as is", despite the fact JavaScript exposes them to you as "objects". Confused yet? I was confused about it... until I learned C#, which has the same concept (known as "boxing").

Link to comment
Share on other sites

I don't know if global variables make your browser slow, but it does provide the certain danger of conflicts between scripts that you installed together. A global variable should not be used by multiple functions unintentionally, and if they are global, this is precisely what would be possible.In my opinion, it should always be visible where a variable comes from, and in what scope it is active. In OOP this is quite obvious if you fully qualify them, but in javascript, there is no such thing. So to keep things readable, I'd say just try to use just the one scope of every function, and not the global one, for declaring variables. Naming conventions might work to "qualify" a variable visibly, but wouldn't syntactically.@boen_robot: you got me there... glad that I'm not concerned about this in my work :)

Link to comment
Share on other sites

thanks a lot guys! =) bookmarked for my future reading and understanding. I have a lot of script that used global variable, now i am happy that it don't really make our browser slower. Just to care for the name conflict... because i don't really understand, without the use of global variable, how could I keep the data still 'living'.below is one of my simple script, i made last nite:

<script type='text/javascript'>var text;var texttobePlaced;var theLoop = 0;function generateText()	{	text = document.getElementById('thetext').value;	var textlength = text.length - 1	if (theLoop <= textlength)		{		var randomSpeed = Math.round(Math.random()*200)		texttobePlaced = text.charAt(theLoop);		document.getElementById('text_place').innerHTML = document.getElementById('text_place').innerHTML + texttobePlaced		theLoop = theLoop + 1;		setTimeout('generateText()',randomSpeed)		}	}</script>

can you look abit in my code and alter it, how could it run without declaring the global variable. Because, i think maybe i will understand it clearer by the example i made.p/s: the function write a text, in a given ID.Thanks a lot!!!!

Link to comment
Share on other sites

I believe you might write this function completely using parameters, eventhough you're using the setTimeout() function.Bear in mind the setTimeout() requires you to pass the function call as a string argument, as this means you can't simply pass in arguments to your function normally. You have to include the result of any argument into that string, which I present here:

<script type='text/javascript'>//var text;   //not necessary anymore//var texttobePlaced;//var theLoop = 0;function generateText(text="", textToBePlaced="", theLoop=0)    {    text = document.getElementById('thetext').value;    var textlength = text.length - 1    if (theLoop <= textlength)        {        var randomSpeed = Math.round(Math.random()*200)        texttobePlaced = text.charAt(theLoop);        document.getElementById('text_place').innerHTML += texttobePlaced        theLoop += 1;        setTimeout('generateText("' + text + '","' + textToBePlaced + '",' + theLoop + ')',randomSpeed)        }    }</script>

-You now don't need globals anymore (you'd have to test this though, haven't tried this much) because the variables are passed as arguments to the function every timeout.-I also added default values to the parameters, so if the function is called without arguments (i.e. the first time) they'll be initialised nevertheless.-Also notice you can use the "+=" operator to concatenate strings or increment integers.-Please notice the weird way of passing arguments in the setTimeout() function. The variables are concatenated to the string and embedded in double quotes if they represent a string themselves. This is important for it to work, as the scope of these variables is within the function where setTimeout() is called, not in the string of its argument. So you just have to concatenate them between the string. Again, you'd have to test this, this is only my second time I've tried it this way.

Link to comment
Share on other sites

Here's another option, with the help of a custom function method:

Function.prototype.createDelegate = function(obj, args){  var method = this;  return function() {	var callArgs = args || arguments;	return method.apply(obj || window, callArgs);  };}function generateText(theLoop){  var text = document.getElementById('thetext').value;  var textlength = text.length - 1;  var texttobePlaced, randomSpeed;  if ((typeof theLoop) == 'undefined')	theLoop = 0;  if (theLoop <= textlength)  {	randomSpeed = Math.round(Math.random()*200)	texttobePlaced = text.charAt(theLoop);	document.getElementById('text_place').innerHTML += texttobePlaced;	theLoop += 1;	setTimeout(generateText.createDelegate(this, [theLoop]), randomSpeed);  }}// start it offgenerateText();//or:generateText(0);

Link to comment
Share on other sites

@JSGI think your example might confuse newrehmi even more. :)While it's functional, and a really good example, I think it's a little too advanced...@JackYou're on the right track. Though you've declared the parameters wrong (you can't assign default values in the function definition like you can in PHP) and all of them really aren't necessary.The variables text and texttobePlaced can be kept completely local to the function since they don't rely on their own past values or any other values. They are completely reset each time the function runs.The variable theLoop can be passed as a parameter to the function.

function generateText(theLoop) {	var text = document.getElementById('thetext').value;	var textlength = text.length - 1;	if ((typeof theLoop) == 'undefined')		theLoop = 0;	if (theLoop <= textlength) {		var randomSpeed = Math.round(Math.random()*200);		var texttobePlaced = text.charAt(theLoop);		document.getElementById('text_place').innerHTML = document.getElementById('text_place').innerHTML + texttobePlaced;		theLoop = theLoop + 1;		setTimeout(function() { generateText(theLoop) }, randomSpeed);	}}//Start the loop, you can omit the parameter or pass in 0generateText();

Notice I've passed an anonymous function to the setTimeout. setTimeout accepts either a string or a function. An anonymous function is just a function without a name. This way is more efficient than passing a string, because the anonymous function does not have to be interpreted into code first (because it's already code) whereas a string does.

Link to comment
Share on other sites

thanks a lot guys! =) bookmarked for my future reading and understanding. I have a lot of script that used global variable, now i am happy that it don't really make our browser slower. Just to care for the name conflict... because i don't really understand, without the use of global variable, how could I keep the data still 'living'.
Like I exampled in my post, all you have to do is keep all your code within an object, and that will keep everything you have existing within that namespace, as long no one else uses the exact same name.
var myApp = {  var1 : 12,  var2 :  24,  add : function(){	 return this.var1 + this.var2;  }};alert(myApp.add());  //alerts 36

Link to comment
Share on other sites

@ShadowMage,The reduction in parameters is what I also had in mind, but I thought just to first show the idea of parametering what was already global. I didn't know setTimeout() also accepts an anonymous function though, thanks! The tutorial doesn't explain the type of that argument quite clearly (they call it a "reference", but use a string in their own example). And what stupid of mine, default values of parameters, lol. I haven't been using either PHP or JavaScript for a while now, obviously I'm mixing things up a little here.I fully agree with you that the custom function is confusing. If you're an experienced OOP programmer like I am, the prototype and createDelegate() stuff of the JavaScript language really doesn't make any sense. thescientists example is much clearer on what it does, this actually begins to look like a conventional class definition!

Link to comment
Share on other sites

I didn't know setTimeout() also accepts an anonymous function though, thanks! The tutorial doesn't explain the type of that argument quite clearly (they call it a "reference", but use a string in their own example).
The wording could be a little bit confusing, I suppose. By reference, they simply mean a "variable" pointing to a function. Remember, these two ways of defining a function are identical:
function test() {   //...do something}var test = function() {   //...do something}

Both create a function named test, which you would call like this: test();To pass that by reference you would just do: setTimeout(test, 1000);An anonymous function is just a "reference" with no name.

Link to comment
Share on other sites

If you're an experienced OOP programmer like I am, the prototype and createDelegate() stuff of the JavaScript language really doesn't make any sense.
That line seems backwards. It doesn't make sense to you because you're experienced? It makes sense to me though, does that mean I'm not experienced? It's just a way to return a copy of a function that executes in a particular scope, while sending parameters to it. If you've never used prototyping in Javascript to extend existing classes, then I don't think you're that experienced.
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...