-
Notifications
You must be signed in to change notification settings - Fork 0
Section 3: Variables & Scope
We've talked about some built in variables that we have available to us, but wouldn't it be neat if we could make our own variables? Turns out we can. Variables are a way that we can reserve a small part of the computer's memory to store data. We reserve a name for it in our program so that we can either refer back to it, and in some cases even modify it's value later on.
In computer programming, a variable or scalar is a storage location paired with an associated symbolic name (an identifier), which contains some known or unknown quantity of information referred to as a value. The variable name is the usual way to reference the stored value; this separation of name and content allows the name to be used independently of the exact information it represents. The identifier in computer source code can be bound to a value during run time, and the value of the variable may thus change during the course of program execution.
Variables in programming may not directly correspond to the concept of variables in mathematics. The value of a computing variable is not necessarily part of an equation or formula as in mathematics. In computing, a variable may be employed in a repetitive process — assigned a value in one place, then used elsewhere, then reassigned a new value and used again in the same way (see iteration). Variables in computer programming are frequently given long names to make them relatively descriptive of their use, whereas variables in mathematics often have terse, one- or two-character names for brevity in transcription and manipulation. - Wikipedia
Because p5js is javascript, we get to use javascript syntax for declaring and using our variables. Something that is unique to scripting languages like javascript is that when we declare variables, we don't necessarily have to worry about what data type the variable is.
To create a new variable we have to declare it, much the same way that we declare our setup and draw functions.
- var
- var is for declaring variables of any type in the global scope of our program – this means anywhere outside of our
setup()
anddraw()
functions as well as any functions that we might create on our own.
- var is for declaring variables of any type in the global scope of our program – this means anywhere outside of our
- let
- let is the same as var, but it is for declaring variabes inside local functions – meaning, if we declare a variable inside of the draw loop, it is important to declare it using let instead of var. We'll go into this in more detail in the next section.
- const
- Const is kind of a special variable that we may not use very much in this class. Unlike var and let, once defined, const is not updatable. These are special variables that if we know that for some reason we always want to define use a fixed value by name we can.
We declare our variables, and then we use the equal symbol to tell the computer that we want the variable to hold that particular value. This is different than a logical equals which we'll talk about in the next section.
declaration | name of variable | = | value to be stored |
---|---|---|---|
var | x | = | 99; |
let | y | = | "ninty-nine"; |
const | z | = | "99"; |
We can name our variables anything we want, except things that are reserved by javascript, or p5js. It is impossible to know what all those things are – usually the debugger will complain if you've used something like year
or pi
.
- You can use single letters (although there are only 26 of them so be careful)
- You can use words if they are not reserved by the system
- You can't use numbers by themselves, but you can include them
Readability
Well-chosen identifiers make it significantly easier for developers and analysts to understand what the system is doing and how to fix or extend the source code to apply for new needs.
For example, although the statement
a = b * c;
is syntactically correct, its purpose is not evident. Contrast this with:
weekly_pay = hours_worked * pay_rate;
which implies the intent and meaning of the source code, at least to those familiar with the context of the statement. - Wikipedia
When we declare a variable with global scope, that means we are giving every part of our program access to that variable. To define a variable with global scope, we use either var
or const
and we declare them outside of the setup()
and draw()
functions. Typically this is done at the top of the program for readability.
If we need to declare a variable inside of function, we absolutely can, and often we will need to. That is the time to use let
as our declaration.
Here's an example that is mostly complete, but it will break:
var x = 99;
const z = "99";
function setup(){
let y = "ninety-nine";
console.log("y = " + y);
}
function draw(){
console.log("x = " + x);
console.log("y = " + y);
console.log("z = " + z);
}
You should two lines of our program that output successfully like this:
ninety-nine 99
Followed by an error like this:
Uncaught ReferenceError: y is not defined at draw (section_3b.js:11) at p5.redraw (p5.js:50266) at p5.<anonymous> (p5.js:44917) at p5.<anonymous> (p5.js:44812) at new p5 (p5.js:45103) at _globalInit (p5.js:46862)
The reason for this is because when we declare let y = "ninety-nine";
in setup()
we only have access to it in setup()
. At line 11 when we try to print the value of y in the draw()
loop, our code breaks because it doesn't have access to anything called y.
W3Schools Full Reference on Javascript Data Types
Intergers can be any whole number, no decimals, we can declare them as such:
* var x = 2;
var some_year = 1983;
* let y = 5;
let some_year = 300;
* const z = 26;
const my_favorite_number = 711;
* they can also be negative var my_other_favorite = -7;
Float is short for floating-point is can be any number, including decimal places
* var/let/const x = 23.97
* var short_pi = 3.14159265359
- string: can be any letter/character or phrase/characters Note the quotation marks around the contents when we declare strings below
-
var s = "a"
orlet message = "Hello World!"
-
"<div id='my_div'> <p>Hello World!</p> <p>My favorite color is green!</p> </div>"
- tricky thing to note, is that a string can be a number:
var s = "37"
- even trickier, if you use math on an interger and a string, javascript will treat the number as a string.
- tricky thing to note, is that a string can be a number:
-
- boolean: True or False statements – we'll talk more about these.
var logical_test_1 = "true"; //string that will return true if tested var logical_test_2 = 1; //integer that will return true if tested var logical_test_3 = true; //bool that will return true if tested var logical_test_4 = "false"; //string that will return false if tested var logical_test_5 = 0; //integer that will return false if tested var logical_test_6 = false; //bool that will return false if tested
- arrays
- how the DOM intereperets
To create a canvas that fills your webpage and stays in the background, add this to your code:
var canvas; // declare canvas globally so you can use it everywhere
function setup() {
canvas = createCanvas(windowWidth, windowHeight);
canvas.position(0,0); // put the canvas at the top
canvas.style('z-index', '-1'); // put it behind the page content
}
You may have noticed me doing this a little already... any time two slashes are used, everything after it will be commented out.
-
//this is a comment
it could also look like this://var my_variable = 100;
var my_variable = 400; //this is a comment that starts after valid code
- comments can also span multiple lines:
var my_variable = "I am a string, not a comment!";
/* <-- begins a comment block
anything
in
here
is
a
comment!
nothing will get excecuted here.
ends the comment --> */
var my_other_variable = "I am totally variable!";