(This page just shows code similar to what was used in class. The lecture slides have a more systematic explanation of variable scope and shadowing.)

Scope

You can define a variable inside a function, or at the “top level” of the program (outside of any function).

Variables that are defined inside a function are local to that function. Variables that are defined at the top level are global variables.

(The code that defines a variable is the code that uses the word let, var, or const.)

let x = 10;  // x is a global variable

function setup() {
	let y = 20; // y is local to setup()
}

Code in a function can use local variables and global variables. But code in one function can't see local variables that are defined in another function.

let x = 10;

function setup() {
	createCanvas(windowWidth, windowHeight);
	let y = 20;
	circle(x, y, 10); // this works
}

function draw() {
	square(x, 0, 10); // this works
	square(0, y, 10); // this produces an error.
	// There is no variable named y in this function, and there is no global
	// variable named y.
}

Code in one function can't even see variables in a function that is calling it.

function setup() {
	createCanvas(windowWidth, windowHeight);
}

function draw() {
	let x = 10;
	myShape();
}

function myShape() {
	square(x, 0, 10);  // error. No local or global variable named x
}

Use a parameter to get a variable one function to another.

function setup() {
	createCanvas(windowWidth, windowHeight);
}

function draw() {
	let x = 10;
	myShape(x);
}

function myShape(x) {
	square(x, 0, 10);
}

Or make the function global.

let x = 10;

function setup() {
	createCanvas(windowWidth, windowHeight);
}

function draw() {
	myShape();
}

function myShape() {
	square(x, 0, 10);
}

Shadowing

If there is a local variable and a global variable, the variable name refers to the local variable. It can't “see” the global variable.

let x = 10;

function draw() {
	let x = 20;
	square(x, x, 10);  // draws a rectangle at (20, 20).
}

P5 provides a function named scale.