Scopes and Closure

JavaScript is a flexible and strong programming language, but some ideas can be hard to grasp, especially for beginners. Two important ideas are scopes and closures. Understanding these is key to writing better, easier-to-maintain, and error-free code. In this blog, we'll explore scopes and closures, learn how they function, and look at practical examples.
What is Scope in JavaScript?
In JavaScript, Scope refers to the visibility and accessibility of variables, functions, and objects in your code during runtime. It determines where you can access a variable. It follows the concept of lexical scope. In lexical scope, the visibility of variables and functions are determined by the context in which the variables and functions are defined.There are three main types of scopes in JavaScript:
1. Global Scope
Variables declared outside of any function or block are in the global scope. These variables are accessible from anywhere in your code, including inside functions and blocks.
let globalVariable = "Global scope";
function logScope(){
console.log(globalScopeVariable);
}
logScope(); //Output: 'Global scope'
console.log(globalScopeVariable); //Output: 'Global scope'
Here, as we see that we can access ‘globalVariable’ in both inside and outside a function.
2. Function Scope
Variables declared inside a function are local to that function. They cannot be accessed outside the function.
function logScope(){
let functionScope = 24;
console.log(functionScope * 2)
}
doubleNum(); // Output: 48
console.log(functionScope); // Error: functionScope is not defined
Here, as we can see we can access functionScope while calling the function but if we try to console.log() the variable it would show an error that it is undefined.
3. Block Scope
Curly braces - {}, denote a code block. Variables declared within these curly braces cannot be accessed outside the curly braces.
function logScope() {
if (true) {
let blockScope = 10;
console.log(x); // Output: 10
}
console.log(x); // Error: blockScope is not defined
}
exampleFunction();
Here, as we can see we can access blockScope inside curly braces of if statement but as soon as we come out of the braces we cannot access the variable even though it is in the same function.
What is a Closure in JavaScript?
A closure is the combination of a function and its lexical scope. In other words, a closure is a function defined in another function that remembers its lexical environment. Remembering its lexical environment means that closure function has access to variables declared within the parent function, even after the parent function has finished executing.
How Closures Work
When you define a function inside another function, it creates a closure with the outer function's scope which allows the inner function to access the outer function's variables, even after the outer function has completed.
function x(){
var a=10;
function y(){
console.log(a);
}
y();
}
x();
Here, as we can see variable ‘a’ is not defined in function y so while giving an output it will try to find the address of ‘a’ when it does not find it in inner function it will try to find it in outer function were ‘a’ is defined an initialized so it will give Output: ‘10’ .
Common Pitfalls with Closures
While closures are powerful, they can also lead to unexpected behavior if not used carefully.
Debugging - Closures can make debugging more difficult due to the complexity of the scope chain. When a bug occurs, it can be challenging to trace the source of the problem through multiple layers of nested functions and scopes.
Memory Leaks - Closures can cause memory leaks if they capture variables that are no longer needed. This happens because closures keep references to the variables in their scope, preventing the garbage collector from freeing up memory.
Performance issues - Overusing closures or using them inappropriately can lead to performance issues. Since closures keep references to variables in their scope, they can prevent garbage collection, leading to increased memory usage and potential slowdowns.
In summary, scopes determine where a variable can be accessed. Scopes determine the visibility and lifetime of variables, while closures allow functions to retain access to their lexical scope, even when executed outside that scope.
Scope can be divided into three: global, local, and block scopes.
Closures are functions inside a function. Closure functions have access to parent function variables, even after the parent function has returned. Closure is a crucial part of asynchronous JavaScript.
By mastering these concepts, you can write more efficient, maintainable, and bug-free code. Whether you're creating private variables, handling asynchronous operations, or building function factories.
Subscribe to my newsletter
Read articles from Kevin Gandhi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
