Variable Scope!
Goals:
- Gain a deeper understanding of how variables and functions relate to each other
- Learn about the challenges and opportunities associated with the concept of variable scope.
Coding Snippets:
- This snippet program crashes when it reaches line 8. The problem is that the variable
d
isundefined
at that point of the program, when it is passed tosee
. - Variables declared as function arguments exist only inside the function.
Math and Computer Concepts:
- A variable's scope is the extent to which it is visible in a program. Being "visible" means it can be referenced and the data it points to can be accessed. The snippet example illustrates one of many ways that issues of scope can impact your program.
- Scope is determined by function definitions. Variables that you reference outside of any custom function definition are visible everywhere in your code. We will call this top level scope. For example,
size
can be referenced anywhere in this program, even directly within the definition of the functiondrawCenteredCircle
(though doing so is considered poor style). - The variables with the broadest, so-called global scope, are properties of the global window object. These are the built-in Pencil Code variables, such as the colors, as well as the sprite constructors. Formally, you can access these variables with the object reference
window
, such aswindow.red
. As long as you don't assign a value to that variable name, (such asred = "a nice color"
) you can simply refer to these properties of the global object by their name, i.e.,red
(which is what we have been doing all along). - Variables
declared
as an argument of functions have a more limited, so-called local scope. These variables are accessible only within that function. - The limited scope of local variables is useful, because it provides a means to create variables without worrying about overwriting an existing variable in the rest of your program.
Activities:
Save each of the following in a folder called .