GameSpark/Tutorials Open editor ↗
JavaScript · Lesson 1

What is a variable?

A variable is a named box that remembers a value. You put something in it, read it back later, and change it whenever you need to. Almost every game is really just a pile of variables changing over time — a score, a position, a timer.

1. Make one with let

Write let, a name, =, and a starting value. Here score starts at 0, and we show it on screen:

let score = 0;

function draw() {
  cls(1);
  print('Score: ' + score, 8, 8, 7);
}

The name score now stands for that value everywhere you use it.

2. Change it any time

That is the whole point of a variable — it can vary. Give it a new value with =, or build on the one it already has. Here the score climbs by 1 each time you press space:

let score = 0;

function update() {
  if (keyp(' ')) {
    score = score + 1;   // take the old score, add 1, store it back
  }
}

function draw() {
  cls(1);
  print('Score: ' + score, 8, 8, 7);
}
💡

score = score + 1 looks strange next to maths, but in code = means "put the right side into the left". So it reads: the new score is the old score plus one. You will write this constantly.

3. Values come in types

So far score held a number. But a variable can hold other kinds of value too, called types. The main ones you will meet:

Each type gets its own lesson next — this one is just the big idea: a name that holds a value you can change.

What you learned