Defining 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 that set of actions.

Click Create a Function to define a new function. A pop-up will open that takes a function name, description of what the function does, and the code blocks for the function. Basically, when you define a function you give a name to a group of code you want the computer to perform. The new function will show up in the function toolbox.

Clicking on the edit button in any function block will reopen the pop-up and allow the function to be edited or deleted.

Examples

Example 1

Click edit to see how the function “switchBackgrounds” is defined.

Example 2

Press different keys and touch other sprites to change the crab’s property. The project uses a “reset” function that can be called with various events to return the crab to its original properties.

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.
  • Make sure your function name is descriptive. It should be easy to understand what a behavior does without having to look at its code.
  • You can call a function within the definition of another function.

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