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.
// Call functions to draw a dotted line of two dashes. dashSpace(); dashSpace(); function dashSpace(){ // Define a function to draw and dash and a space. penDown(); moveForward(); penUp(); moveForward(); }
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(); }
Define a function that uses randomNumber(1) to randomly generate a one (heads) or zero (tails) and return the appropriate word.
// Call a function to flip a fair coin. Display the returned value on the console. console.log(coinFlip()); // Define a function that uses randomNumber(1) // to randomly generate a one (heads) // or zero (tails) and return the appropriate word. function coinFlip() { if (randomNumber(1)==1) return "HEADS"; else return "TAILS"; }
function myFunction() { // function body, including optional "return" command. }
Optional: A function can return a value by using the return command.
Found a bug in the documentation? Let us know at documentation@code.org