Return!
Goals:
- Write functions that compute values or create objects.
Coding Snippets:
- Use a return statement to instruct a function to return a data value back to the place in your code where the function was called.
- A function can return a value of any data type, including number, string, arrays, objects (including labels and sprites), and even other functions.
Math and Computer Concepts:
- A return statement exits a function; any code in the function that appears after it will not be executed. This is a useful feature when using conditional logic, as illustrated by the
isPrime
function shown to the right. If the argument passed to the function is less than 2,isPrime
exits with the execution ofreturn false
in the firstif
block. The last statement,return true
, is only executed if none of the three return statements above it are executed. - A return statement can only be used to pass a single value. While this may seem like a significant limitation, it is easy to work around using a collection of data, i.e., an array or an object.
getxy
andpagexy
are examples of built-in functions that return arrays; the expressionrandom(position)
returns an object.
Activities:
Save each of the following in a folder called .
- MathExamples: Define your own version of two or more of the math functions introduced in Math, Mod, and More! Use original function names (such as
computeABS
rather thanabs
) so that you can compare how your function performs compared to the original. Test your functions using relevant test values and print output on screen usinglabel
. - RandomPosition: The expression
random(position)
generates an HTML coordinates object, e.g.,{pageX:260, pageY:90}
, which represents a random coordinate on the visible screen. Define an alternativerandomPosition
function that generates an array of coordinates in more-familiar center-based Cartesian coordinates. - FactoryFunction: A function that returns an object is called a factory function. Design a factory function that produces a sprite of your choice. For example, code a makeFish function that creates a fish sprite or a makeStar function that creates a sprite of a star. Your function should accept arguments to specify size, color, and/or other features specific to your drawing or image. Use this function to generate multiple instances (i.e., copies) of this sprite.
- MakeLabel: Write a factory function
makeLabel
that accepts a string argument. The function should create a label and return a reference to that label. Incorporate your function in a loop that generates labels for each word in a short sentence and randomly places them around the screen. For an extra challenge, make your program subsequently reposition the labels in their original order.