Computer Programming : Scope
If you’re new to programming, you’ve likely ran into the topic of scope by now: Why can’t I access this variable? Is this variable in scope? What is scope???
When it comes to computer programming, scope is a way of binding a name (such as a variable) to an entity (such as an object, function, block, class, etc). In other words, it’s a way to explain if you have access to a variable from the location you’re trying to access it.
Here’s an analogy that could be useful, think of the levels of government from local to federal government. When it comes to resources, your local government (city/town/etc.) can have access to state resources, and the state can turn around and have federal resources.
Consider the picture above; similar to local have access to state and federal, any line of code would have access to the level above it. For example, a line of code in a particular block would have access to any variable declared in the parent function, as well as Global scope. However, this access to variables only works going up, not down or adjacent.
In the example above, there are lines of code that would return and answer, but some would be undefined (because it’s trying to access variables that are out of scope):
- c = a+b would return 3 — both a (global) and b (function) are within scope above
- d = a + b would return 3 (same as Block 1)
- e = b + c would return undefined — it has access to b (above) but not c (adjacent). In order for e to return an answer, c would have to be defined at the function level.
- f = c + d would return undefined — it’s unable to access either c or d from the blocks below and both would have to be defined at the function level to be valid.
As you can see, variables are said to be “in scope” if they are declared at a level higher than where they are accessed, but not below or adjacent.