How to exit a function in the middle and continue on with the code

I saw a lot of searches for this so I decided to write an article about it. So you can jump out of a function at anytime using the "return;" command. Here is an example

function test(isContinue):void{
var i:String = "bal bla ablababallaa";
trace(i);

if (!isContinue){
return;
}
i = i+"sadfdsafasdfasdf";
trace(i);
}

test(false);

This bit of code will output:

bal bla ablababallaa

if we run

test(true)

then we end up with :

bal bla ablababallaasadfdsafasdfasdf

you can use "return;" on functions that return a value or that do not have a return type or are of return type void as I have shown above.

Another interesting technique that is simular to this is getting out of a loop but not out of the function. Lets take our original function and modify it to show how "break;" works.

function test(isQuitEarlyOn5):void{
var i:uint;
for(i; i < 10; i++){
if (i == 5 && isQuitEarlyOn5){
break;
}
trace(i);
}
trace("done");
}

if we run the function

test(true);

then we get :

0
1
2
3
4
done

if we run:

test(false)

then we get

0
1
2
3
4
5
6
7
8
9
done

Notice no matter what the "done" gets ran. The break only gets us out of the loop but not the function like the "return;" command.

The "break;" comand works in any loop( while, for, do...while etc).


comments powered by Disqus