Javascript

Variables

Javascript in an untyped language. This means that you don’t have to declare the type of a variable. You can just create a variable and assign a value to it. The type of the variable will be determined by the value you assign to it.

var vs let

var and let are both used to declare variables. The difference between them is that var is function scoped and let is block scoped. This means that variables declared with var are available in the whole function and variables declared with let are only available in the block they are declared in.

Using var:

// this will work
function setup(){
    var x = 10;
    x = x + 1;
}
function draw(){    
    x = x + 1;
}

Using let:

// this will not work
function setup(){
    let x = 10;
    x = x + 1;
}
function draw(){    
    x = x + 1;
}

Global variables

Frowned upon by many but quite handy for quick hacks. Variables exist and can be shared between functions.

// variables xPosition and yPosition can be called in each function
let xPosition = 30;
let yPosition = 60;

void draw(){
    circle(xPosition, yPosition, 200);    
}

// this will now work.
void updatePosition(){
    xPosition+=10;
    yPosition-=40;
}

p5 defined variables

Variable Purpose
width The width of the window
height The height of the window
mouseX The x-coordinate of the mouse
mouseY The y-coordinate of the mouse
pmouseX The previous x-coordinate of the mouse
pmouseY The previous y-coordinate of the mouse
mousePressed Wether a mouse button is pressed
mouseButton The last mouse button pressed
key the last key pressed
keyCode the last key pressed, also for non-character keys