JavaScript Data Structures: Variables

Overview and Objectives

Variables are one of the cornerstones of programming and development. At the most basic level, variables are containers. On their own, a variable is just an empty placeholder waiting to store a value. Variables have a typename, and value. Once data is stored inside a variable, it can be used and manipulated in your scripts. You’ll learn about the different assignment keywords (const and let) in JavaScript and when to use each.

Lesson Objectives

  • Understand how to use variables for storing and modifying data in a sketch
  • Declare a constant variable using const
  • Declare a re-assignable variable using let
  • Explain the key differences between const and let in JavaScript and when to use each one

Variables in JavaScript

JavaScript is what’s known as a weakly typed or dynamic language, which means that variable types don’t need to be declared ahead of time. The variable type is determined automatically when the code runs.

Variables are declared in the following way:

//This is an example of a comment in JavaScript! let myVar = 400; //myVar is a Number let myVar = "DHF"; //myVar is now a String let myVar = true; //myVar is now a Boolean
Code language: JavaScript (javascript)

While you don’t need to declare the variable type in advance, JavaScript still includes different variable types. In the above example, the variable named myVar has been set to 3 different data types: a Number, a String, and a Boolean. The code would be interpreted top to bottom, so if the above code were to be interpreted, myVar would be a Boolean since that is the last declaration.

The value of myVar is able to be changed because of the keyword let. Go ahead and try to use const instead and see what happens.

Variable Types

Here are some of the most common variable types you’ll encounter. There are more types, but they’re rarer. You’ll encounter these types in most JavaScript code:

Note: The initial value is optional, whereas the name is required.

  • Numbers: Numbers include both integers and floating points (decimals). This is different than in other languages where these are separate variable types.
  • Strings: Strings are text data. Strings must be contained in either single or double quotes. Note that if you did let myVar = “one”; that it would be interpreted as a string, not a number.
  • Booleans: These are Boolean values (true or false).
  • Undefined: These are variables that haven’t been assigned any value. An example would be let myVar;

Variable Scope in p5

There is one additional point to consider when working with variables in p5. This is what’s known as variable scope. You’ve encountered this concept in Scratch when you created a variable. Scratch asks if you want your variables to be local (this Sprite only) or global (all sprites). The data stored in local variables was only accessible to the Sprite it was connected with, whereas the data in global variables could be accessed by any sprite in your game.

JavaScript variables have a property called scope, and therefore variables in p5 also have this property. The two scopes that variables have are global and local:

Global variables can be seen and used by every function in your p5 code.

Local variables are only seen by the function that they’re declared in.

Here’s a non-programming parallel:

Your full given birth name is on your birth certificate and is seen/accessed by anyone in any of your circles, as long as you reveal it. This is your “global name.” A nickname that is known to only your inner circle of friends and only applied to you when in their company is your “local name.” There is no record of it anywhere else other than that particular local circle, so if someone called you by this particular nickname in an official capacity, it wouldn’t be recognized.

Using Global Variables in p5

Remember that function setup() and function loop() are both functions. This means that any variables declared within those functions will be local to it. Any global variables must be declared outside of these functions. Any variables that you need to use in both the setup and draw functions of your game must be written outside the functions. This is typically done in the space above the function setup().

Common p5 Variables

Variables will make your life a lot easier! There are several built-in variables in p5 that you can access. Two of the most commonly used are width and height. These are available to you in anything that you write in p5.

The width variable is the value of the width that’s set in createCanvas() and height is the height value.

If you were to create a canvas with the following command createCanvas(640,480), the width variable is 640 and height variable is 480.

Two other common variables are mouseX and mouseY. These are used for tracking the mouse position. The mouse’s x position is stored in the mouseX variable and the y position is stored in the mouseY variable.

Activity: Experimenting With Variables

Let’s revisit the ellipse sketch from before. This time, instead of hardcoding the parameter values, you’re going to use variables instead! Take a look at this sketch:

/* these values are outside of the functions so that they're available to all functions remember, for a variable to be global it must be placed outside the functions in the sketch! */ let xVal = 100; let yVal = 100; function setup() { createCanvas(640,480); } function draw() { background(255,0,100); //now the background will be always changed on refresh of draw() ellipse(xVal, yVal, 50,50); //draw the ellipse using the new variable values! }
Code language: JavaScript (javascript)

The comments point out a few things. First, the variables xVal and yVal have global scope because they are created outside of the function blocks. This means that you can access them in draw() as well as anywhere else you’d need!

The variables are then used in place of the x and y parameters in ellipse(). The values of 100 are used for both since that’s what’s stored in each variable.

Putting the background() command in to the draw() function makes p5 call that function whenever draw() is called. Remember, draw() repeats at a default rate of 60 times per second, meaning that your background is continually redrawn. Go ahead and experiment with removing background() from draw().

Manipulating Variables

You can use math operators to manipulate variable values. For example, change the ellipse() line to the following:
ellipse(xVal, yVal, xVal*2,yVal*2);

Before running the sketch, can you predict what will happen?

Remember, p5 has built in variables such as width and height. These will be useful as you experiment with creating your sketch. What do you think will happen with the following code:

let xVal = 100; let yVal = 100; function setup() { createCanvas(640,480); } function draw() { background(255,0,100); //now the background will be always changed on refresh of draw() fill(255,255,255); ellipse(width/2, height/2, 100,100); }
Code language: JavaScript (javascript)

Before running the new code, try to predict what you think that width/2 and height/2 will do. Run it and see if you’re correct!

Activity: Draw Some Lines

Understanding how to manipulate the width and height variables will save you lots of time. Lines are a great way to test your understanding!

Remember, the syntax for drawing a line: line(x1, y1, x2, y2);

The line is drawn from the first x and y pair (x1, y1) to the second x and y pair (x2, y2). Think about the following code from function draw():

function draw() { background(255,0,100); //now the background will be always changed on refresh of draw() line(0,0,width,height); line(width,0,0,height); }
Code language: JavaScript (javascript)

Think back to the lesson about the coordinate grid and see if you can predict what this will draw!

Changing Variables While Drawing

Another key strength of variables is that they can be updated while your sketch runs. This is crucial for designing interactive programs such as browser games. Imagine if a score variable couldn’t be updated! Take a look at this example:

let x = 10; // set the initial x value function setup() { createCanvas(680,480); } function draw() { background(255,0,100); line(x, 0, x, height); // draw the line with the initial value x = 20; // change the x value. x is now 20! line(x, 0, x, height); x = 30; line(x, 0, x, height); x = width/2; line(x, 0, x, height); }
Code language: JavaScript (javascript)

As the sketch runs, the x variable is changing! The program code runs top to bottom, drawing each new line with the updated value.

Experiment with changing some variables and draw create interesting line drawings!

Code Short Cuts

So far you’ve changed the value of x by assigning a completely new value. What if you wanted to update the original value instead?

Think about how a score works. Each time you gain an item, +1 is added to the original value. This could be represented like this:

let score = 0;

(Something happens in your sketch…)

score = score + 1;

This works perfectly well, but there’s some shorthand that is even faster! You can use the following instead:

score += 1;

This is an even shorter way of saying score +=1, but ++ only works for adding 1.

If you want to subtract, you could use:

score -= 1;

This does the exact same thing. Go ahead and test out these new shortcuts!

Review and Discussion

Make sure to review these concepts throughout the remainder of the course. Understanding the differences between var, let, and const and when to use each is a core JavaScript skill.


Additional Resources