Scope in JavaScript
What is Scope? Why do we need it? And how can it help us write less error-prone code?
Scope simply allows us to know where we have access to our variables. It shows us the accessibility of variables, functions, and objects in some particular part of the code.
Why would we want to limit the visibility of variables and not have everything available everywhere in our code?
Firstly, it provides us with some level of security to our code. Secondly, it helps to improve efficiency, track bugs and reduce them. It also solves the problem of naming variables.
We have three types of scopes:
Global Scope
Local Scope
Block Scope (only with let and const)
Variables defined inside a function are in local scope while variables defined outside of a function are in the global scope. Each function when invoked creates a new scope. There are rules about how scope works, but usually you can search for the closest { and } braces around where you define the variable. That “block” of code is its scope.
Global Scope
When you start writing in a JavaScript document, you're already in the Global scope.
const name = 'Abdullah';
Variables written inside the Global scope can be accessed by and altered in any other scope.
const logname = () => {
console.log(name);
};
logname();
Advantages of using Global variables
You can access the global variable from all the functions or modules in a program.
It is ideally used for storing "constants" as it helps you keep consistency.
A Global variable is useful when multiple functions are accessing the same data.
Disadvantages of using Global Variables
Too many variables declared as global, then they remain in the memory till program execution is completed. This can cause of Out of memory issues.
Data can be modified by any function. Any statement written in the program can change the value of the global variable. This may give unpredictable results in multi-tasking environments.
If global variables are discontinued due to code refactoring, you will need to change all the modules where they are called.
Local Scope
Variables defined inside a function are in the local scope.
// Global Scope
const functionOne = () => {
// Local Scope #1
const functionTwo = () => {
// Local Scope #2
};
};
Advantages of using LocaI VariabIes
The use of local variables offers a guarantee that the values of variables will remain intact while the task is running.
They are deleted as soon as any function is over and release the memory space which it occupies.
You can give local variables the same name in different functions because they are only recognized by the function they are declared in.
Disadvantages of using LocaI VariabIes
- They have a very limited scope.
This isn't necessarily a disadvantage, but if you ever find yourself needing to use that variable in a parent scope, just declare it there. Let me use the above example to show you what I mean. If you need to use a variable only inside the functionTwo
function, just declare it there.
// Global Scope
const functionOne = () => {
// Local Scope #1
const functionTwo = () => {
// Local Scope #2
};
};
If for some reason, you need to use it both in the functionOne
and functionTwo
functions, declare it in the functionOne
.
And if you need to use it everywhere across the file, declare it in the global scope.
Block Scope
Block statements like if or for and while loops, unlike functions, don't create a new scope.
Variables defined inside of a block statement will remain in the scope they were already in.
if(true){
// this 'if' conditional block doesn't create a new scope
var name = 'Abdullah';// name is still in the global scope
}
console.log(name); // logs 'Abdullah'
That is only true with the var
Variables defined with const or let have something called Block scope. That means that they will be available only inside of the block of code you create them in.
if(true){
// this 'if' conditional block doesn't create a scope
// name is in the global scope because of the 'var' keyword
var name = 'Abdullah';
// likes is in the local scope because of the 'let' keyword
let likes = 'Programming';
// skills is in the local scope because of the 'const' keyword
const skills = 'JavaScript';
}
console.log(name); //logs 'Abdullah'
console.log(likes); // Uncaught ReferenceError: likes is not defined
console.log(skills); // Uncaught ReferenceError: skills is not defined
If a variable or other expression is not "in the current scope," then it is unavailable for use.
What is more useful?
The local and global variables are equally important while writing a program in any programming language.
KEY DIFFERENCE
Local Scope | Block Scope | Global Scope | |
Definition | Variables declared inside a function or block. | Variables declared inside a block enclosed by curly braces. | Variables declared outside any function or block. |
Access | Limited to the function or block in which they are declared. | Limited to the block in which they are declared. | Accessible from any part of the program. |
Lifetime | Created when the function or block is invoked and destroyed when it completes execution. | Created when the block is entered and destroyed when it is exited. | Created at the start of the program and persists until the program terminates. |
Shadowing | Variables in an inner scope can have the same name as variables in outer scopes, effectively hiding the outer variables. | Variables in an inner block can have the same name as variables in outer blocks, effectively hiding the outer variables. | Variables cannot be redeclared in global scope. |
Impact | Changes to local variables do not affect variables in other scopes. | Changes to block-scoped variables do not affect variables in outer blocks. | Changes to global variables are visible in all scopes. |
Never memorize something that you can look up. -Albert Einstein
Subscribe to my newsletter
Read articles from Muhammad Abdullah directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Muhammad Abdullah
Muhammad Abdullah
Welcome to my programming blog! I am a passionate Javascript developer with a deep-rooted love for coding who's just getting started with blogging. Let's learn together and build some excellent web applications along the way.