Everything You Need to Know About JavaScript Scope

This article contains an explanation about JavaScript Scope and it’s special cases

Ravindu Senaratne
May 18 · 4 min read
Photo by Lucas van Oort on Unsplash

What is Scope?

The scope is an important concept that determines the accessibility of variables, functions, and objects. In JavaScript, there are two types of scopes

  • Local Scope
  • Global Scope

Let’s demonstrate how the scope works:

You can see the output of the variable in the next line after the declaration.

Now, Let’s see what happen if move the declaration of msg inside an if block:

You will see JavaScript throws a ReferenceError because of the if block initiate a Scope for msg variable and it will only be accessed within that scope.

1. Local Scope

Variables that can be used in a specific part of the code are considered to be in a local scope. And these variables are called Local Variables.

There are two types of local scope in JavaScript,

  • Block Scope
  • Function Scope

1.1 Block Scope

Block scope is an area within conditions (if or switch) or loops (for and while) or whenever you see {} it is a block. In a block, you can declare variables using const and let keywords. These variables exist only within the corresponding block.

The first console.log(msg) works because the variable is declared inside if block, therefore the msg accessed from the scope where it is defined.

The second console.log(msg) throws a reference error because the variable is accessed outside of its scope.

The code blocks of if, for, while and standalone also delimit a scope.

Keyword var is not block scoped

1.2 Function Scope

When you declare a variable in a function, that variable is only visible within the function.

call() function body creates a scope. The variable msg is only accessible within the function scope and if we try to access it outside of its scope then it'll throw an error.

2. Global Scope

The global scope is the outermost scope and the variables can be accessed from any inner(Local) scope.

Variables declared inside the global scope is named Global Variables, these variables can be accessed from any scope.


Lexical Scope

When a function is defined inside another function, the inner function can access the variables of the outer function. This operation is called Lexical scoping.

The inner function is lexically bound to the execution context of its outer function.


4 Special Cases Where JavaScript Scope Behave Differently

1. Declaring variables using ‘var' inside a for-loop

When you declare a variable using var keyword, it scoped only by a function body and not from a code block. If you consider the i variable that declared using let keyword, let variables are block-scoped therefore it can only accessible within the scope of for-loop. You can fix this by changing the letdeclaration to var .

2. Function parameters scope

When you invoke the run() function it will throw an error because the function parameters have their unique scope. In other words, the parameter a = a + 1is equal to let a = a + 1.

You can simply fix this by renaming the variable let a = 0 or function parameter a = a + 1.

3. Declaring function inside code blocks

This code will run but in the older version (ES2015) this will throw a Reference Error.

4. Variable scope in a try-catch block

But if you go through the code line by line you will see the output should be 'Hello', 2 , the reason you get a different out is that the catch parameter is block-scoped. It cannot be accessed outside the block as same as the variables inside cannot be overridden even with the same name.


Chrome and Firefox’s DevTools make it simple for you to debug variables you can access in the current scope. Browsers will temporarily pause the JavaScript execution when you add debugger in your code.

Conclusion

That’s the end of this article. Scopes are not hard to understand once you see them in use. Thank you and stay safe!

Frontend Weekly

It's really hard to keep up with all the front-end…

Thanks to Sunil Sandhu

Ravindu Senaratne

Written by

Undergraduate at University of Moratuwa 🇱🇰 ravindu.17@itfac.mrt.ac.lk

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

Ravindu Senaratne

Written by

Undergraduate at University of Moratuwa 🇱🇰 ravindu.17@itfac.mrt.ac.lk

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store