Variables

Resources:

Shiffman - 2.1 Variables in p5.js - p5.js

Data Types

What is data? What does it look like to us? How about to computers? A variable is a container for storing data. Variables consist of a name and a value (and often a type).

Many programming languages, including Processing, require using data types to create a variable. These indicators, like int, float, or boolean tell us what kind of data is being stored in that variable. But, with JavaScript and p5, we don't have to worry about such things! We simply use the data type var for everything! (At least for now). This makes things easier, but it can also get us into trouble. You can say that Processing is more "strongly typed" than JavaScript. Some examples of data types are below:

data types

Variables

Variables must be declared before they’re used, though this can be done in the same line.
Variables can be reassigned many times, but only declared once!
Variables should have names that describe their content.
When you enter parameters into the createCanvas() function, p5 automatically saves them as "width" and "height". You can reuse them! Try making your own composition using only factors of width and height.

Especially as our code gets more complex and includes more functions, we'll need to pay attention to variable scope. Variables have a global or function "scope". For example, variables declared within either the setup() or draw() functions may be only used in these functions. Global variables, variables declared outside of setup() and draw(), may be used anywhere within the program. If a function variable is declared with the same name as a global variable, the program will use the function variable to make its calculations within the current scope.