
Full Stack Developer • Technical Writer • JavaScript • Python • Django.
Designing amazing projects on the Frontend and solving problems.
As a developer, writing clean, bug-free code is essential, and understanding how scopes work is crucial to achieving that.
If you have ever written a line of code,then you have definitely used any of JavaScript scopes without probably knowing it.
Scopes determine how our codes run,how they interact with each other and therefore understanding how they work is crucial.
In this article,I will walk you through what scopes are, levels of scopes we have in Javascript and how understanding them makes us write good,clean code.
Let's GOOOO 🚀
How do scopes work?
In Javascript and probably every other programming language out there, codes run within some set of scopes.
You can think of scopes as a block of curly braces that divides various sections of your code.
Scopes also determine what variables your code has access to and how new variables interact with the rest of your code.
Consider the following code block:
const outerVariable = "outer";
function checkScope(){
const innerVariable = "inner";
console.log(outerVariable,innerVariable);
// Logs out: "outer" , "inner"
}
checkScope();
console.log(outerVariable,innerVariable);
// Reference Error: innerVariable is not defined
In the above example, we have a code block containing two variables, one inside of a function and the other outside.
Then we log out both variables to the console from inside and outside the function. This works perfectly from inside the function but throws an error from the outside. This is because we do not have access to the innerVariable, which is inside the scope of the function.
Now, a simple explanation for the above code is that any variable declared within a function is only accessible within it or nested functions within it; therefore, innerVariable cannot be accessed, hence the error.
We will explain this in more detail later; let's move on for now.
Levels Of Scopes
As I have mentioned earlier, there are different levels of scope in Javascript, and understanding how each of them works is crucial to writing good, clean, and bug-free code.
There are four different levels of scopes in Javascript and they are:
1. Global Scope.
2. Block Scope.
3. Function Scope.
4. Module Scope.
We will explain each of them and understand how they work.
Let's dive in.
Global Scope
Any variable declared at the beginning of a file, that is, outside of any function or curly braces, is in global scope and can be accessed anywhere in our application. This is how global scope functions.
Also, that variable is considered a global variable.
This global access makes writing codes simpler since we don't have to worry about variables being restricted by different scopes.
Now consider the same block of code as in our previous example:
const outerVariable = "outer";
function checkScope(){
const innerVariable = "inner";
console.log(outerVariable,innerVariable);
// Logs out: "outer" , "inner"
}
checkScope();
console.log(outerVariable,innerVariable);
// Reference Error: innerVariable is not defined
In the above example, outerVariable is declared outside of a function and is a global variable, which makes it accessible throughout our entire code.
Also, innerVariable is declared inside of the function checkScope and is what we call a local variable.
Now if we try to access innerVariable outside of the function by logging it out on the console, we get a reference error. Why, might you ask?
This is because it is declared within a function and can only be accessed within it.
Block Scope
Block scopes are not the ones to avoid because we use them all the time in our program.
Block scopes are easy to understand. Anytime you have code within the curly brace {}, you have a block scope, as easy as that.
Therefore, things like if-else statements, loops, switch cases, functions, etc. all have block scopes.
Consider this simple code block:
{
const x = 20;
}
console.log(x);
// Reference Error: x is not defined
The above example throws a reference error because x is declared within a block scope and cannot be accessed anywhere else except within the block.
If the code block were like this:
{
const x = 20;
console.log(x);
}
// Prints out : 20
20 will be logged out on to the console because the variable x can now be accessed and then logged out.
Let's consider a more complex code block:
function check() {
const myName = "Adam";
if (true) {
const myLanguage = "JavaScript";
console.log(myName, myLanguage);
// "Adam", "JavaScript"
}
console.log(myName, myLanguage);
// Reference Error: myLanguage is not defined
}
We have two block scopes in the example above.
Each block scope is the code between the curly braces and has access to all the variables inside of each but not the ones outside.
The check scope has access to all the variables within the check function that are not nested in another set of curly braces, which means that it only has access to the myName variable.
Because the if scope is a child scope of the check scope, the if block gets access to the variables myLanguage and myName.
One important thing to note about block scope is that anytime you have curly braces, you have defined a new block scope.
That block scope only has access to all the variables inside it and not the ones outside it, except if they are written inside another block scope like the example we have above.
The code block above threw a reference error because we tried accessing the myLanguage variable, which is declared within the if scope, so our computer could not recognize it, hence the error.
Also, the values of both the myName and myLanguage variables get logged out on the console because the if scope has access to all the variables within the check scope because it is within it and is a child scope to the check scope.
The block scope is a bit difficult to comprehend; take your time to go over it again and make sure you understand it properly.
Onto the next 🚀
Function Scope
The difference between the function scope and the block scope is that variables are declared in the function scope using the var keyword.
Moreover, variables declared using the var keyword are only recognized at the function level and not the block level, meaning that they are scoped at the function level.
Simply said, they are just interested in the curly braces of functions.
Consider the same block code as in the previous example:
function check(){
var myName = "Adam";
if (true) {
var myLanguage = "JavaScript";
console.log(myName, myLanguage);
// "Adam", "JavaScript"
}
console.log(myName, myLanguage);
// "Adam", "JavaScript"
}
The code block is exactly the same, except that our variables are declared with the var keyword.
Also, another important notice is that even though the myLanguage variable is declared within the if scope, the function scope doesn't care; it gets access to the myLanguage variable and prints it out to the console,the reason being that both variables are declared under the same function.
Now this is one of the many reasons the var keyword is not recommended to use and that it is best practice to stick to the let and const keywords.
Module Scope
You might not really understand the module scope without having prior knowledge of modules.
I recommend reading an article or watching a video on it before continuing with this article.Nevertheless, I will give you a brief explanation of modules.
A JavaScript module is simply a package of code that provides functionality for other modules to use. This allows for sharing and reusability with other code.
Now, let's move on to the module scope.
In the global scope, any variable declared outside of any function or block is accessible all through our entire application, that is, it can be accessed by multiple files.
In module scope, there is quite a difference.Any variable declared outside of a function is hidden and only available within the file in which it is declared; it is not available to other modules unless exported.
Let's assume we have two JavaScript files:
main.js file:
<script src="main.js"></script>
index.js file:
<script src="index.js"></script>
Write the following code in the main.js file:
const myName = "adam"; // feel free to add your name here
console.log(myName);
// adam
Now in the index.js file, write the following code:
console.log(myName);
In the index.js file, our program is able to recognize the variable myName , which is declared in the main.js file because it is a global variable and accessible all through our entire application.
Now if this were in a module scope,the files would look like this:
main.js file:
<script src="main.js" type="module"></script>
index.js file:
<script src="index.js" type="module"></script>
Note the change in how the scripts is written now.
I added "type="module" to each of the scripts to enter/activate the module scope.
Now let's consider the files again.
// main.js file
const myName = "adam";
console.log(myName);
// adam
// index.js file
console.log(myName);
// Reference Error : myName is not defined
The error occurred because we switched to module scope, and any variable declared within a module is only accessible within it; thus, myName cannot be accessed because it is not declared within the index.js file.
Conclusion
As I mentioned earlier, comprehending JavaScript scopes can assist us in writing more maintainable code and preventing bugs.
Therefore,with our understanding,we can now write better codes.
Please remember to "like" this article if you found it helpful and, if you have any questions, feel free to post them in the comments section.
I appreciate you reading.
You can reach out to me on twitter.


