Scope

So far, we’ve only declared our variables at the top of the program. While this is sufficient for now, we may want to be more specific about where are variable can be accessed from.

Global Variables

When we declare a variable at the top of our program, we are, in fact, making a global variable. This means that we can use this variable anywhere in our program.

Local Variables

While global variables are great, sometimes we only need to use the variable in one particular code block (the stuff inside of {}). Local variables are declared in exactly the same way, except instead of declaring them at the start of the program, we declare them inside of the code block.

ACK! What happened? Line 7: Uncaught ReferenceError: x is not defined But we defined it in setup()! Welcome to the debugging console! Debugging is a critical part of coding. It’s rare that your code runs perfectly the first time. Luckily the programmers of JavaScript and p5.js thought about this and gave us some ways to figure out what’s going wrong. In this case the variable x is only defined for the code within the code block setup() .

In order to solve this problem we need to either create a global variable or define a new variable inside draw(). If these two variables are related in some way it probably makes sense to define it globally. e.g. If we want the x position of the to be at 1/10 of the canvas. But we want the x position of the rectangle to be at 10 and the y position to be twice that we should declare a new variable inside of draw().

Notice that we can use the same variable name in both setup() and draw() because each time we use x it’s localized to the code block. We’ll see the importance of this more as we progress, but for now it’s important to understand the difference between locally and globally defined variables.


Previous section:
Next section: