Let’s talk about Scopes Baby…

Scopes are one of the most important concepts you can learn in the Javascript language, or any language to be honest. If you find that your Javascript functions aren’t working the way you would like them to there is a strong possibility the culprit is your scoping.

So what is a Scope?

A scope has to do with where functions and variables are accessible within the program that is being executed. I’m going to tackle the two most import types of scopes that will aid in proper functional Javascript programming with a third more advanced concept to follow in a future post.

Global Scope

The Global scope is the main window or window object, any variable or function that is declared within the global scope is accessible anyplace in your code. For example, think of the global scope as a fish tank, within the fish tank there is a castle (function) and two fish (variables). You as a human can access anything within the fish tank and manipulate it however you please.

Local Scope

Now that we have an understanding of global scope we can now apply the same logic to the local scope. The keyword is ‘Local’ which means the lexical environment has been scaled down, so instead of the javascript engine looking at the lexical environment of the window it more concerned with what is contained within a function. Going back to the fish tank example from before, the castle (function) within the fish tank has its own environment that cannot be seen by anything OUTSIDE the castle. Now the fish can swim inside the castle or swim outside the castle but anything that is SPECIFICALLY within cannot leave the environment.

Below is code snippet that ties my fish tank example and code together.

Screen Shot 2016-03-02 at 12.09.56 AM.jpg

Keep in mind you cannot see the window object (fish tank) but it’s there.

Now there is one more Scope that is a little more involved when it comes to it’s understanding and that is the infamous Closure Scope. I will be covering this concept more in depth in another post, just to make sure I get to all the ins and outs of the subject.

If you have any questions about this specific example please feel free to contact me or leave a comment.

 

Leave a comment