GameSpark/Tutorials Open editor ↗
JavaScript · Lesson 8

Functions

A function is a named chunk of code you can run whenever you want. You’ve already been filling in update() and draw() — the engine calls those for you. Now you’ll write functions and call them yourself.

1. Define a function

There are two separate steps: defining a function and calling it. Defining writes down the steps and gives them a name — but it does not run them yet. Define one with function name() { … }:

function greet() {
  print('Hello!', 8, 8, 10);
}

On its own, that code draws nothing. The steps are written down, waiting — until something calls them.

2. Call the function

To actually run a function, you call it: write its name followed by (). Those parentheses are what set it going. Here draw calls greet, so "Hello!" appears:

function greet() {
  print('Hello!', 8, 8, 10);
}

function draw() {
  cls(1);
  greet();   // CALL greet — run its steps now
}
💡

The () is the part that runs it. greet() calls the function; greet on its own (no parentheses) just refers to it without running anything. And you can call a function as many times as you like — each call runs its steps again from the top.

3. Give it inputs: parameters

A function gets more useful when you pass it values. The names in the parentheses of the definition are parameters — here x and y. The values you hand over when you call it (like 30, 64) are called arguments. Now one coin function can draw a coin anywhere, as many times as you call it:

function coin(x, y) {
  circfill(x, y, 4, 10);        // gold body
  circ(x, y, 4, 9);             // darker rim
  line(x, y - 2, x, y + 2, 9);  // center line
}

function draw() {
  cls(1);
  coin(30, 64);
  coin(64, 64);
  coin(98, 64);
}

Three coins from one definition — that’s the whole point of functions: write it once, use it many times.

4. Get something back: return

A function can hand a value back with return, so you can use its result:

function double(n) {
  return n * 2;
}

function draw() {
  cls(1);
  print('double(5) = ' + double(5), 8, 8, 7);
  print('double(9) = ' + double(9), 8, 20, 7);
}
🎯

Try it: write ring(x, y) that draws a circle outline with circ, and call it a few times. Write add(a, b) that returns a + b and print the result.

What you learned