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":
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, when we want to animate our drawings.
- Variable names can begin with letters, or the symbols "$" or "_". They can only contain letters, numbers, "$" and "_". (They cannot begin with a number). "myVariable", "leaf_1", and "$money3" are all examples of valid variable names.
- 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.