The Scoop on Scopes JavaScript

·

3 min read

Okay so you have declared your variable and you are ready to put it in use!

You have an error. It's saying ReferenceError: (your variable) is not defined. That makes no sense you have declared it with a const. You're looking right at the variable. When this happens this is a scoping problem. You're probably thinking wait what is the Scope? In MDN the scope is defined as:

"The scope is the current context of execution in which values and expressions are "visible" or can be referenced."

The scope is boundary lines for our variables and expressions. The scope does protect us from bugs. In JavaScript, we have four scopes: Global, Local, Function, and Block Scope. Here is how I see it global is the parent of local, local is the parent function, and function is the parent of block. Parent scopes can not reach into their child scopes for variables, but child scopes can reach into any parent scope for variables. I will mention if we have two functions on the local scope we can not reach into the first function from the second function scope for a variable and vice versa. I'll explain the above example.

Let's take a look at our scope boundary lines.

On line 10 inside my function scope, I declared a variable. If I were to call for that variable in my global scope would the variable answer? If you answered No, you are correct. Remember our parent scope can not reach into the child scope for variables or expressions. Line 13 inside my block scope I call for the variable. My block scope is reaching into the parent parent scope for the variable [funVar]. Now if my condition comes back false my function will [console.log] [funVar] or run the [else] block. Lets take a look.

Sweet it worked as planned! Let's take another look at the same example.

Declaring [globalVar] and [globalVar1] in my Global scope made those two variables accessible to my Local, Function, and Block Scope. In my block scope on line 17, I reached out from my block scope into the global scope for [globalVar]. If my condition comes back as true. The function will [console.log] my global scope variable [globalVar]. Let's see if this was successful:

Sweet! Success no errors!

Here is an example of a parent scope reaching into a child scope:

In my function scope on line 11, I am reaching into block scope for my variable [loud]. JavaScript does not like this. My function scope is the parent of my block scope. Let's see what our results will be:

When we reach into a child scope from a parent scope the variable will come back as not defined. So if ever this happens to you check your scoping.

When declaring variables or expressions my advice is to declare everything you are going to use multiple times in the global scope. That way you do not have to declare the same element or expression multiple times.

Hopefully, you have found this helpful. Leave a comment if you have any questions.