Declares a new variable.
A variable is a container for a value. For example, a variable might contain a creature's x-coordinate as a Number
or its name as a String
. Variables can change value by reassigning them as follows:
// Declare the variable x and assign it the value 10.
let x = 10;
// Reassign x to 50.
x = 50;
Variables have block scope. When a variable is declared between curly braces {}
, it only exists within the block defined by those braces. For example, the following code would throw a ReferenceError
because x
is declared within the setup()
function's block:
function setup() {
createCanvas(100, 100);
let x = 50;
}
function draw() {
background(200);
// x was declared in setup(), so it can't be referenced here.
circle(x, 50, 20);
}
Variables declared outside of all curly braces {}
are in the global scope. A variable that's in the global scope can be used and changed anywhere in a sketch:
let x = 50;
function setup() {
createCanvas(100, 100);
}
function draw() {
background(200);
// Change the value of x.
x += 10;
circle(x, 50, 20);
}
Examples
Related References
stringify
From the MDN entry: The JSON.stringify() method converts a JavaScript object or value to a JSON string.
log
Prints a message to your browser's web console.
===
The strict equality operator === checks to see if two values are equal and of the same type.
Array
A list that keeps several pieces of data in order.