A function is a block of code wrapped together in a way so that it can be re-used at anytime in the code. It is used to save time as repeated tasks can be written only once and then called multiple times. It centralizes the code so that all of it is placed in a specific place that can be easily updated without having to manually modify each time the code is used. Using functions also makes reading the code by humans easier as it could be used to logically arrange code performing a collective task in a single place.
Click here to learn more How to define function?
Function Code Example
For example, say that you want to create an instance of a certain object, set its x and y properties, and add it to the display list. You can do that by using the code below:
myVal = new Val();
myVal.x = 100;
myVal.y = 200;
addChild(myVal);
var myStar:Star;
myStar = new Star();
myStar.x = 100;
myStar.y = 150;
addChild(myStar);
myStar = new Square();
myStar.x = 100;
myStar.y = 150;
addChild(myStar);
You would then have to repeat the same code multiple times each time you want to add a new rectangle to the screen. This is a tiresome job and would end up in the creation of massive identical code. In order to avoid duplicating the same code, you can create a function. This function will have the core code you need and then you can reuse it multiple times to repeat the code:
Sample code using function
var myStar:Star;
function makeRectangle():void {
myVal = new Val();
myVal.x = 100;
myVal.y = 150;
addChild(myVal);
}
makeRectangle();
makeRectangle();