Interactive Tutorial: Variables

If you did the previous interactive tutorial about background color and screen size (which you can find here), you’ve seen how we can pass values called arguments or parameters into functions.

This time, let’s try storing those values in reusable structures called “variables.”  You can think of a variable as a named space or box in the program’s memory that can store a value. Just like with a box, you can change what’s stored in the variable throughout the program.  Let’s again look at some code that changes the background color, but this time, let’s store the color values in variables, and pass those into the background() function instead of the actual numbers.

Note: The code example is shown on this site, but if it doesn’t work for you, click this link to open it in a new window: https://editor.p5js.org/empressdragonlady/sketches/KeOU8TBBJ

You’ll notice that on the first three lines of the code, we see the word var.  This keyword means that we are creating a variable.  Next, we give the variable a name, and then set it equal to a value.  So for example, let’s look at the first line:

var r = 50;

We are creating a variable named r and giving it a value of 50. Here are the next two variables we create:
var g = 0;
var b = 60;

Now we have two more variables, one named g that is given a value of 0, and another named b with a value of 60.

Now that we have created the variables, we can use them elsewhere in the code by writing their names (without having to use the var keyword again). For example, we can pass the variables as arguments to set the background color:

background(r, g, b);

When the program runs, the variable names will be replaced with their values.

Note: There are some rules that you must remember when creating variable names.  Here is a reference where you can read more about the rules: https://www.dummies.com/web-design-development/javascript/naming-javascript-variables/

Challenge: Try changing the values stored in the r, g, and b variables to change the background color. Hint: to accomplish this, you can change the values that come after the = signs in the first three lines of code.

JOIN OUR NEWSLETTER
Sign up to receive updates about new tutorials, game news, and educational opportunities.
We hate spam. Your email address will not be sold or shared with anyone else.

Share This:

Comments are closed.