Functions
The purpose of a function is to help you organize your code and to avoid writing the same code twice. You can you define a function once, and then call the function a number of times.
When you define a function you give a name to a set of actions you want the computer to perform. When you call a function you are telling the computer to run (or execute) that set of actions.
A function definition can be provided anywhere in your code - in some ways the function definition lives independently of the code around it. It actually doesn't matter where you put a function definition. And you can call it from anywhere, either before or after the function definition. We will follow the convention of always putting function definitions at the bottom of our program, and the code for calling functions at the top of our program. Tips
Examples
// Call functions to draw a dotted line of two dashes. dashSpace(); dashSpace(); // Define a function to draw and dash and a space. function dashSpace(){ penDown(); moveForward(); penUp(); moveForward(); }
Example: Figure Eight
Call functions to draw a figure eight using two squares.
// Call functions to draw a figure eight using two squares. square(); turnLeft(); turnLeft(); square(); // Define a function to draw a square using left turns. function square(){ moveForward(); turnLeft(); moveForward(); turnLeft(); moveForward(); turnLeft(); moveForward(); turnLeft(); }
Example: Flip a coin
Define a function that uses randomNumber(1) to randomly generate a one (heads) or zero (tails) and return the appropriate word.
// Call functions to draw a figure eight using two squares. square(); turnLeft(); turnLeft(); square(); // Define a function to draw a square using left turns. function square(){ moveForward(); turnLeft(); moveForward(); turnLeft(); moveForward(); turnLeft(); moveForward(); turnLeft(); }
Tips
- A common error is defining a function but forgetting to call the function. A function does not automatically get executed.
- A function that does not explicitly return a value returns the JavaScript value undefined.