Variables

A variable is a memory location with an associated symbolic name, which contains some kind of value.

A third feature of variables is their type which defines the kind of data they contain: integer number, floating point number, string, object etc.

Javascript is a weakly typed language, meaning it doesn’t require you to specify a type and it won’t generally give you an error if you use a variable of the wrong type (although the results may be incorrect).

Let’s have some fun with variables:

//declaration
var myDiameter = 10;

function setup()
{
  createCanvas(500, 500);
  noStroke();
}

function draw()
{
  background( 0, 0, 0);
  ellipse(250, 250, myDiameter, myDiameter);
}

I use a var for the radius so I don’t have to type the number every time i want to adjust it.

Since it’s a variable it can be changed:

myDiameter = myDiameter+1;

or

myDiameter++;

What if I want the resizing to be slower?

What if I wanted to stop at a 100?

What about the other parameters of the ellipse?
Try to use variables there too!

Give them meaningful names.

Now use that variable to make the circle move from the left to the right!

wrap around the screen! (if)
go back and forth!

Print function
Often variables don’t have a visual representation but you may want to check their content for debugging and testing purposes. print() is the p5.js function to use:

print(myVariable);

print(myVariable+1);
//+-*/%

//this is actually a string concatenation, we'll get into strings later
print("My variable is "+myVariable+1);

The output will be visible only in the browser console and in the p5.js editor, and it’s not meant to be seen by the user.

Scoping

Some “temporary” variables can be declared inside functions and blocks. Note: these variables won’t be “visible” outside that block (scoping).

function draw()
{
  background( 0, 0, 0);

  var dx = mouseX - posX;
  var dy = mouseY - posY;

  posX += dx/10;
  posY += dy/10;

  ellipse(posX, posY, myDiameter, myDiameter);
}

Let’s analyze this.

How can we make the circle faster?

How can you make the circle follow the mouse pointer only when the mouse button is down?

Posted in