-
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, we give them a name, and then we use the equal symbol to tell the computer that we want the variable to hold that particular value. e.g. var x = 99;
This is different than a logical equals which we'll talk about in the next section. It is also possible declare a variable for use later without setting a value – e.g. var x;
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.
//we assert that x is a variable that our entire program has access to
var x;
function setup(){
//we assert that x should hold the value 99;
x = 99;
}
function draw(){
//we print the value of x;
console.log("x = " + x);
//we increment the value of x;
x++;
}
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
JavaScript numbers are always stored as double precision floating point numbers – this means they can have decimals or not. This is different from most other languages that define int
and float
as two different things, but in javascript land... it is a lot more loosey goose.
//all of the variables below are whole numbers
var x = 2;
var some_year = 1983;
let y = 5;
let another_year = 1300;
const Z = 26;
const MY_FAVORITE_NUMBER = 711;
//they can be negative numbers
var OTHER_FAVORITE_NUM = -7;
//they can also be decimals
var a_decimal_value = 23.97;
let a_radio_station = 107.7;
const A_COOL_NUMBER = 1.0;
//you can go fairly deep in decimal places (~17 places)
var short_pi = 3.14159265359
//also can be negative numbers
var neg_pi = -3.14159265359
A string: can be any letter/character or phrase/characters Note the quotation marks around the contents when we declare strings below
var s = "a"
let message = "Hello World!"
let my_html = "<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"
There are many horrible truths about javascript, and unexpected things happening by combining types is one of them.
take for example the following code:
function setup(){
}
function draw(){
let my_number = 37;
let my_string = "47";
console.log(my_number+my_string);
console.log(my_number*my_string);
noLoop();
}
the console will produce the following output:
3747 1739
In the case of the first output, javascript assumes we want to recast my_number
to a string and concatenate it with my_string
[37][47]. But when multiplying, it recasts the my_string
to a number and multiplies it with my_number
giving us the new number: 1,739
. Don't worry – you are right to be confused and angry.
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
}
In order for this to work however, we need to add the DOM library to our project. This is pretty easy – we just go back to our index.html
page and add in this line:
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.16/addons/p5.dom.js"></script>
<head>
<title>Snippets!</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.15/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.16/addons/p5.dom.js"></script>
<link href="style.css" rel="stylesheet">
</head>
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!";