Define a function

Category:Functions

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.

Examples

// 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();
}

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();
}
                        

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 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";
}

Syntax

function myFunction() {
    // function body, including optional "return" command.
}

Returns

Optional: A function can return a value by using the return command.

Tips

  • 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.
  • 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.

Found a bug in the documentation? Let us know at documentation@code.org