3:2 Variables
A variable is a named thing that can store a number, text and some other stuff.
They are the fundamental way we change and affect things with code.
JavaScript Variables
JavaScript has a number of ways of creating variables.
let
const
var
We will almost always use let
const makes an unchangeable variable, we aren't going to concern ourselves right now with const, but as you progress you may.
You will see var a lot in older tutorials - it still works, but isn't used much these days.
Lets create a variable
When you first make a variable you use let.
This lets JavaScript know we're making a new variable.
let xPosition = 30;We just made a new variable called "xPosition" and gave it a value of 30
Later on in the code we can change that variable, for instance:
xPosition = 40;(you only use let the first time you make a variable)
Things to look out for
Some variable names are protected.
This means that they're already in use by the system. The system could be your browser, or it could be a library like p5.js. p5js will normally warn you if you do this.
How to name variables
Variables are case sensitive (i.e. they care about capitals), variables can't have spaces - there's some good guidance here:
https://www.w3schools.com/js/js_conventions.asp
camel case is most commonly used. This involves using a capital letter for the start of each word in a variable with no spaces and a beginning with a lowercase letter. Think of a camels humps!
🐫
for instance:
let myCamelName = "Bernard"Using a variable to position a circle
We will modify the x position of our circle we made in a previous tutorial. So lets think of a useful name for the variable.
I could be called anything, but as its modifying the x position lets call it xPosition. So put this at the very top of your code:
let xPosition = 0;We've made a new variable and set it to zero.
Feel free to duplicate the sketch as your starting point.
Moving the circle
By changing the variable we can move the circle.
The draw function runs the code inside it 60 times per second so lets add something to the variable there to change it repeatedly and animate the circle:
This code will add 1 to xPosition
xPosition = xPosition + 1;However we can do exaclty the same thing with more concise code (this does the same thing:
xPosition += 1See it in action below:
The circle is moving a very slowly! Try increasing the value from 0.1 to something bigger to speed it up. This value is added onto the variable every frame.
Using system variables
p5js has a lot of variables built in, for instance the size of the window, or the position of the mouse. These are called system variables, lets use some.
windowWidth and windowHeight are p5js system variables that store the current size of the window. These are very useful to make your canvas full screen.
Once you've made the canvas with createCanvas you can use the system variables width and height too.
Introducing variables to make an animation
Next Lesson:
Making decisions