The Complete Javascript Scope Guide (Beginner + Advanced)

I still remember It was the last week of December. The weather was extremely cold. I got up at five as usual, and wrote my first line of code.

As soon as I advanced through my career, I realized that good understanding of scope boosted my bugs tracking skills and reduced error chances.

If you understand Scope, you’ll easily be able to determine what’s really happening to your code.

And when your code has a bug, or when a variable throws an unexpected value,

you can instantly debug it because you know where it is and why it is.

Why is Scope Important?

1- Avoiding Namespace Collision— Namespace collisions occur when two or more variables share the same name.

2- Application Security — Variables are only accessible when they are needed.

(Example– Allowing Employee only basic administration of App and grant full access when needed.)

What is Scope:

In layman’s term, it simply means where a variable is sitting in your code.

In addition to that, scope also specifies whether you have access to the variable or not.

Basically, there are two types of scopes in JavaScript, global scope and local scope.

Global Scope: When a variable is sitting outside of a function, it becomes a global scope. (Note- Entire application can access global scope)

// Declare a Global variable buffet

var buffet = "I'm sitting outside of function";

//Find out if we can Access the global variable buffet inside functionBezos

function functionBezos() {
   console.log(buffet);
}
functionBezos();
// Yes we can, Expected Output = "I'm sitting outside of function"

Local Scope: When a Variable is sitting inside a function, it becomes a local scope. (Note- It can only be accessed from within the function.)

// find out if we can access, variable buffet outside of the functionBezos   

function functionBezos() {
    var buffet = "sitting inside function";  
}
console.log(buffet);  // No we can't, Expected Output = buffet is not defined

Here is 3 Important concepts :

  1. First, Local Variables Have Priority Over Global Variables when declared inside Functions.
  2. Second, If you assign a value to the local variable without first declaring with the var keyword, it is automatically added to the global scope.
  3. Third, All global variables you declare are attached to the window object.so it can be accessed on the window object.
Execution Context:

It is a wrapper to help manage the code That is running, and it works in two phases, Creation and Execution.

In the creation phase JavaScript Engine (Browser) puts function and variable declarations into its memory before it executes any line of code.

In the execution phase javascript Engine (Browser) executes your code line by line and memory allows Javascript Engine to execute your code before its even declared.

If you want to know more about execution context, Read my Blog on Javascript Hoisting Where I have explained it in detail.

Execution Context Stack:

Execution stack is a stack of execution context with a LIFO (Last in, First out) structure.

How the Execution Context stack Works:-

First, Whenever the javascript engine encounters a function invocation, it creates a new execution context for that function and pushes it to the top of the stack.

Second, the Javascript engine executes the execution context and pops it out from the top of the stack.

This Process gets Keep repeating until all the execution context gets popped out. See image below to clearly understand the whole process-

What is Scope Chain:

A scope chain is a simply stack of currently accessible scopes.

Let’s look at the example below, what happens if we call function b().

function a() {
   console.log(myVar);
}
function b() {
   var myVar = 2;
   a();
}
var myVar = 1;
b();

// Expected Output = 1

Some of you thought it might be two, because we called a() from function b, But the output will be 1. Why ?

Because every execution context has a reference to its outer environment. So, what is the outer environment?

You can simply think, Where is my code sitting, If my code is sitting inside the function, my outer environment will be local scope.

Whereas if my code is sitting outside of a function, my outer environment will be global Scope.

So, In the example Above where does function a() is sitting?

It’s not sitting inside function b, it’s sitting right there at the same level as that last line where myVar = 1.

Closing Notes:

If you really want to become master of javascript, and wants to write clean code, which I think you certainly want to do (otherwise you would be chasing women)

You have to always keep in mind that it is a bad practice to create too many variables in the global scope.

Thanks for reading, If you still didn’t understand JavaScript scope after reading this blog post, please ask questions in the comments below.

I will personally answer all the questions, or alternatively, you can Dm me on Facebook too.

If this post was helpful, help me back by clicking the Share button.

More Articles:-

The Ultimate guide to become a full stack web developer in 3 easy step

7 Amazing Array Methods to Boost your Javascript Skills Today

3 weird ways to create javascript objects (Learn my tricks Now)

Who Else Wants to Clear confusion about Javascript Hoisting [Step-by-Step]

Learn More About Scope Here

Tanisk Jha

Mission-Driven Self taught Software Developer with a passion for thoughtful UI Design, collaboration and writing.

One thought on “The Complete Javascript Scope Guide (Beginner + Advanced)

Leave a Reply

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