Skip to content

Section 3: Variables & Scope

Eric Beug edited this page Dec 9, 2017 · 21 revisions

Section 3a Variables for storage, reuse, and more

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.

Declarations

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() and draw() functions as well as any functions that we might create on our own.
  • 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";

Naming (is hard):

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

Section 3b: The scope of the variable

Global Scope

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++;
}

Local Scope

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.

Section 3c: Data Types

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

Okay but what do I need a variable for?

The answer is most likely everything. We've been using numbers a lot so far, and we've been able to produce some pretty nifty results. But for even niftier results we can replace the hard coded numbers with variables, so that we can change them over time, or not have to remember them. In theory at least, this has the added benefit of making our code easier to understand if someone else is looking at.

For the most basic example

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";

For manipulating and processing strings, javascript has many built in methods that we can use. See the W3 Schools reference to read more about string methods.

A warning about types: Beware when using strings and numbers together:

Javascript is a "weakly typed" language. While that may sound like people with brittle and over-sensitive fingers are the ones who write it, that is not the case. Rather, it means that variable types are allowed to be combined in various ways. While other programming languages strongly enforce that you can't do things like combine a string and a number, in javascript you can – but you have to be careful.

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 creating a new string: [37][47]. But when we use the multiply operator, 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 (AKA True or False)

In programming it is incredibly useful to be able to measure things in a binary fashion. A boolean is just that: True or False statements – we'll talk more about these in the next section.

var logical_test_1 = true;
var logical_test_2 = false;

The words true and false used without quotations are keywords, and are thus syntax highlighted. But, something to note here about "weakly typed" language is that using strings or numbers as booleans can often produce the same result. Booleans can actually be represented by numbers or strings.

var logical_test_1 = "true";	//string that will return true if tested
var logical_test_2 = 1;		//number 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;		//number that will return false if tested
var logical_test_6 = false;	//bool that will return false if tested

Arrays are variables that are more like a group of multiple variables, separated by commas. In JavaScript,

var my_num_array = [0,1,2,3,4];
var my_str_array = ["zero", "one", "two", "three", "four"];

Arrays are wonderful things – by default, you can access any part of an by it's index. The most important thing to remember is that the indices start at number 0.

index: 0 1 2 3 4
my_num_array 0 1 2 3 4
my_str_array zero one two three four
let array_of_nums = [0,45,37,33,6,4];
let array_of_strings = ["a", "b", "c", "lazy", "dog"];
let array_of_nums_n_strings = [1, "bath", 300, "hats"];
let multidimensional_array = [[1,2],[3,4,5],["clam", "bake"]];
index: 0 1 2 3 4 5
array_of_nums 0 45 37 33 6 4
array_of_strings a b c lazy dog
array_of_nums_n_strings 1 bath 300 hats
multidimensional_array array[1,2] array[3,4,5] array["clam", "bake"]

To access a value at a specific index of an array, we use the variable name followed by the desired index in square brackets e.g. array_of_nums[4] (for the 5th index). Remember, indices start with 0. In this case we'd get a 6 back.

console.log(array_of_nums_n_strings[1]);

will output:

> bath

In this case "bath" is the value in the index that corresponds to 1.

console.log(array_of_nums_n_strings[1]);

will output:

> bath

If we try to access a value of an index that does not exist, our program will return: undefined

console.log(array_of_nums_n_strings[5]);

will output:

> undefined

if we want to access a single value in a multidimensional array the syntax is as follows: multidimensional_array[1][0], where the first number in brackets is will return the value of the outer index (which will be an array), and the second number in brackets will return the value of the inner index.

let multidimensional_array = [[1,2],[3,4,5],["clam", "bake"]];
console.log(multidimensional_array[1][1]); //we want to access that number four
console.log(multidimensional_array[2][0]); //we want to access that clam

output:

> 4
> clam

Section 3d: Let's use some variables starting to make a full page canvas

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>

here in the

section of our page, right after we load our p5js file
  <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>

Section 3 Bonus: Comments & Comment Blocks

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!";
Clone this wiki locally