JavaScript: Scope

Before we start

Before we even start with JavaScript’s scope, we need to have a shared understanding. JavaScript is often described as a interpreted language because of it’s dynamic typing, however, many developers are unaware that it falls better into the compiled language category. Believe it or not, JavaScript actually needs to be compiled in the browser before it runs just like C++ or Java. Now don’t get me wrong, the compilation is much faster than others but the whole process is there. JavaScript compilation is done in milliseconds (it has to on the web!) so therefore it’s engine is not able to optimize the code like other languages can.

Typical compilation process includes:

Tokenizing: Often called a lexical analysis, is where strings of characters are broken up and put into characters. For example, a typical variable assignment, var x = 4; will be broken down into 4 parts (var, x, =, 4)
Parsing: Taking the table of tokens from the first step and sets them up into a nested tree called Abstract Syntax Tree. The purpose of this step is to decide the structure of the program
Code Generation: Essentially in this step, the code engine takes the AST and turns it into executable code.
This is a simple breakdown of the compilation process. While JS’s process is much more complex, it is based on this common system. Now back to the subject at hand.

What is Scope?

Just like in any language, a scope is basically the set of rules that determine of where and how a variable can be looked up. JavaScript’s scope works very similarly to many C-based languages.

If a variable is not accessible in its current scope then it can not be used. Scopes from functions and blocks contains variables meaning that you may not access the variable from outside the bubble.

Example: Function Scope

function myFunc(){
var outOfScope = 4;
}

console.log(outOfScope); // reference error
In this example, outOfScope is insde of the myFunc bubble and therefore does not exist outside of it. However, inside of a bubble, you may access varaibles outside.

Example:

var outOfScope = 4;

function myFunc(){
console.log(outOfScope);
}
When it gets slightly more complicated is the thought of nested scopes. Essentially the core concept is the same. You can access things outside the bubble but not inside.

 

Thomas Nguyen

 

Leave a Reply

Your email address will not be published. Required fields are marked *