If you're seeing this message, it means we're having trouble loading external resources for Khan Academy.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

Here's what we covered in this tutorial on variables.

A variable is a way to store values. To use a variable, we must both "declare" it, to let the program know about the variable, and then we must "assign" it, to let the program know what value we are storing in the variable.

Here's how we would declare a variable named "xPos":

var xPos;

Now, we can assign it to hold the value 10:

xPos = 10;

 

If we want to (and we often do!), we can declare and assign it in one statement:

var xPos = 10;

If, for some reason, we want to change the value of a variable later, we can "re-assign" it:

var xPos = 10;
// some time later ...
xPos = 20;

We'll soon see why re-assignment can be useful.

 

A variable can store the result of any expression, so a variable's value can be computed based on the values of other variables:

var bodySize = 300;
var headSize = bodySize/3; // 100
var noseSize = headSize/2; // 50

 

How can we pick names for our variables? For variables in JavaScript, follow these rules:

  • Variable names should begin with letters, "$" or "_" and only contain letters, numbers, "$" and "_"
  • Variable names are "case sensitive" - that means that "xPos" is different from "xpos", so make sure you are consistent with how you type it.
  • Variable names can't be the same as existing variable names, and there are a lot in our ProcessingJS programming environment. If you ever see an error pop up like "Read only!", try changing your variable name.
  • Variable names should be clear and meaningful - for example, instead of "ts", use "toothSize".
  • Variable names should use "camel case" for multiple words, like "toothSize" instead of "toothsize" or "tooth_size".

We'll use variables a lot when we learn animation in the next tutorial, so ask questions here if you don't understand something about them.