Function with Return values

Posted on: March 5th, 2011 by alemieux

One of the questions I get most often from students about functions is “What is the :void for?” Indeed, most functions, especialy functions that are derivative of an event listener will have this form:

function someThing(e:MouseEvent):void { }

This is only when a function is not returning a value. Yes, functions can return values and if you think about it, it’s kind of a cool way to use functions. We can return numeric or string data from a function. In this quick example, we’ll use a function to assemble an address and then trace it out:

function address():String {
var street:String = "156 Primrose Hill Rd";
var cityState:String = "Dracut, MA";
var zip:String = "01826";

var fullAddress:String = street + cityState + zip;
return fullAddress;

Notice here that we use :String instead of :void. This indicates to the compiler what type of data is going to be returned by the function.

Next, we set up a few variables to hold the information for street, city, and zip. We use another variable to pull all of that info together. Then w use the return statement to return the fullAddress variable.

In our trace statement, we actually call on the function to return the value we want. We could also set up the function to return numeric data by datatyping the function to :Number or :int or :uint for that matter.

Tweet this! | Bookmark at Delicious

Comments are closed.