DEV Community

Cover image for The Ins and Outs of JavaScript Scope: Variable Edition
Debraj Roy
Debraj Roy

Posted on

The Ins and Outs of JavaScript Scope: Variable Edition

Scope of Variables

  • Scope refers to the environment in which variables are declared and can be accessed.
  • It determines where a variable can be seen and how long it exists.

Let's consider an example:

function greet() {
  let user = "Jonathan";
  console.log(`Hello ${name}`); // Hello Jonathan
}
greet();
console.log(user); // Reference Error: `user` is not defined
Enter fullscreen mode Exit fullscreen mode

In this example, within the function greet(), we declared a variable named user and printed its value. However, when we try to access user outside the function, it leads to a reference error. This happens because the user variable is confined within the function's scope, denoted by the curly braces { ... }.

Types of scopes

  • Global Scope
  • Local Scope
  • Block Scope

Global Scope

In JavaScript, the global scope represents the outermost environment where variables are accessible throughout the script. Any variable declared outside of curly braces {...} belongs to this global scope.

Variables declared in the global scope can be accessed anywhere within the script, including inside functions and nested blocks.

let globalVariable = "global string";

function showGlobals() {
  console.log("inside a function", globalVariable);
}

showGlobals();

if (true) {
  console.log("inside a conditional", globalVariable);
}

console.log("global scope", globalVariable);
Enter fullscreen mode Exit fullscreen mode

In this example, the variable globalVariable is declared in the global scope, allowing it to be accessed inside the showGlobals() function, within the conditional block, and directly from the global scope itself.

Disadvantages of Global Scope

  1. Variable Overwriting: Since variables declared in the global scope are accessible from anywhere within the script, there's a risk of accidentally overwriting them. This can lead to unexpected behavior and bugs in the code, especially in larger projects where multiple developers may be working simultaneously. It also increases the security issues of our code as it is exposed to the outside world.
  2. Name Collisions: When variables in different parts of the codebase have the same name and are declared in the global scope, it can lead to name collisions. This makes code maintenance and debugging more difficult, as it's challenging to track down where a variable was modified or accessed.
  3. Performance Degradation: Accessing variables from the global scope can be slower compared to accessing variables from a more localized scope. This is because the JavaScript engine has to traverse the scope chain to find the variable, which can impact performance, especially in complex applications.

Local Scope or Function Scope

Local scope refers to the visibility of a variable within a function. When a variable is declared inside a function, it is said to be in the local scope of that function. This means that the variable can only be accessed from within the function in which it is declared. It cannot be accessed from outside the function.

function greetDev() {
  let localVariable = "Local string";
  console.log(localVariable);
}
greetDev();
console.log(localVariable); // ReferenceError : localVariable is not defined
Enter fullscreen mode Exit fullscreen mode

Variable shadowing

If a local scoped variable has the same name as the variable declared in the outer scope and we are trying to access that variable then the local variable will overshadow the outer scoped variable. This phenomenon is called variable shadowing..

let message = "Hey";
function showMessage() {
  let message = "Hi";
  console.log(message); // Hi
}
showMessage();
console.log(message); // Hey
Enter fullscreen mode Exit fullscreen mode

Advantages of Local Scope

  1. Encapsulation: Local scope allows for encapsulation of variables and promotes modular pattern. This helps in organizing code and preventing unintended access or modification of variables from other parts of the program.

  2. Prevents Name Collisions: Variables declared in local scope are only accessible within their respective blocks. This prevents naming conflicts that may arise when variables with the same name are used in different parts of the program.

  3. Memory Efficiency: Variables declared in local scope have a shorter lifetime compared to global variables. Once the block of code in which they are declared completes execution, they are automatically removed from memory. This can help in efficient memory management.

  4. Improved Performance: Accessing variables from local scope is generally faster than accessing global variables. Since the scope chain is shorter, the JavaScript engine can resolve variable references more quickly, leading to improved performance.

  5. Easier Debugging: Local scope makes it easier to debug code by narrowing down the scope of variables. It's easier to identify the specific block of code where the problem lies, leading to faster debugging and troubleshooting.

Block Scope

Variable in JavaScript are block scoped when they exist within a pair of curly braces { ... }, such as if statements, loops, and the new let and const are blocked scoped. Variables declared within a block scope are only accessible within that specific block and any nested blocks within it.

if (true) {
  let blockVariable = "Blocked String";
  console.log(blockVariable);
}

console.log(blockVariable); // Reference Error: blockVariable is not defined
Enter fullscreen mode Exit fullscreen mode

The examples show that the variable blockVariable declared inside the if statement is only accessible inside the if statement but it can't be accessible outside of the if block.

Difference between Local and Block Scope

Category Local Block
Definition It refers to the scope in which variables are defined within a specific function It scope refers to the scope in which variables are defined within a pair of curly braces { ... }, such as those used in if statements, loops, and block-scoped declarations introduced with let and const.
Accessibility Variables declared in local scope are accessible only within the function in which they are defined, as well as nested functions. Variables declared in block scope are accessible only within the block in which they are defined, as well as any nested blocks within it. They are not accessible outside of the block.
Lifetime Variables declared in local scope exist only for the duration of the function in which they are defined. Once the function completes execution, these variables are destroyed and their memory is freed. Variables declared in block scope exist only for the duration of the block in which they are defined. Once the block completes execution, these variables are destroyed and their memory is freed.
Example Variables declared with the var keyword are function scoped. Variables declared with let and const keywords are block scoped.

Scope Chain

Before understanding what is scope chain we have to understand one thing lexical environment which is also comprised of two things first is the lexical scope of a variable and another thing is the reference to the outer scope.

The lexical scope of a variable means where the variable is located or declared inside our code instead of from where we are trying to access it.

Let's consider an example:

function outerFunc() {
  let localName = "Jimmy";
  console.log(`hello ${localName}`);
}
outerFunc();
Enter fullscreen mode Exit fullscreen mode

From the above example, we can see that there is a variable localName which is inside of the outerFunc() function. So the lexical environment of the variable localName is its scope which is in this case local scope inside outerFunc() and the reference to the outer scope of the outerFunc() function which is in this case global scope.

So basically scope chain is the hierarchy of scopes. When we try to access or reference a variable, the javascript engine first checks that variable in the innermost scope and then traverses toward the outer scopes. And how he can do that because of the lexical environment which is just the scope of a variable along with its outer scope. This traversing through the inner scope to the outer scope creates a chain of scopes in a proper hierarchical manner.

That's the reason why variable shadowing happens cause JavaScript first finds a targeted variable in the innermost scope, if it fails to find it then it goes outwards.

Summary:

What we have learned from this article:

  • What is Scope?
  • What are the types of Scope in JavaScript?
  • Each scope what it does and the pros and cons of them
  • Scope Chain and lexical environment

Conclusion:

If you are still with this article please don't forget to support it by giving this article a hear and leave comments and give feedback how do you like about this article.
It will help me to grow as a developer and also teach and learn in public.

Happy coding! 🚀✨

Top comments (0)