DEV Community

Sandeep Nautiyal
Sandeep Nautiyal

Posted on

Understanding Lexical Scope and Closure in JavaScript

Intro:

In programming, scoping refers to the accessibility of variables and functions within different parts of your code. It essentially defines where you can use a certain variable or function and where you can't.

Lexical scope:

Lexical scope is a specific way of determining this accessibility based on the physical location of the code.

To put it simply scoping means which variable or functions can be accessed in which part of your code understanding this will help you to write better code. Js Uses lexical scoping during execution to check if the variable we are calling in our function or if the function we are trying to call is even accessible or not. there are three types of scope in js

  1. Global Scope.
  2. Local Scope.
  3. Block Scope.

Global Scope.

Variables and functions declared outside of any function or a block {} are in global scope and can be accessed by any method.

var a = 10;
function sum(b){
return a+b;
}
console.log(sum(20))
//print's 30 as a is declared in global scope it can be accessible by any Method.
Enter fullscreen mode Exit fullscreen mode

Local Scope

If a variable is being declared inside a function then it can only be accessed inside that function that is a local scope or a functional scope.

function sum(b){
     var a = 10;
 // will give you 10 as it will first check for 
 // local context where it will get it's value 
 // then it will be printed
     console.log(a)
     return a+b;
}
sum(10)
console.log(a) // it will give you an err as console.log will check for the variable in global context as it is not inside the function.
Enter fullscreen mode Exit fullscreen mode

Block Scope

Now let's talk about block Scope in ES6 two new keywords were introduced const and let these two goes one step further in scoping as these two are block scope what I mean by that is if you declare any variable with these two keywords inside a block {} they will be discoverable inside that block only.

to give you a better understanding here is a code snippet.

if(true){
    var a = 10;
    let b = 20;
// this will print 10 20
    console.log(a,b);
}
// throws err saying b not defined.
console.log(a,b)
Enter fullscreen mode Exit fullscreen mode

I hope this will help you understand better what Scopes are in js.

Scope Accessibility Summary:

Global Scope: Variables and functions declared outside of any function are accessible from anywhere in the code.

Local Scope (Function Scope): Variables declared within a function are only accessible within that function.

Block Scope (let & const): Variables declared with let or const within a block (like if statements or loops) are only accessible within that block.

Closure

In JavaScript, closures allow inner functions to access variables from their enclosing function's scope, even after the outer function has finished executing. This happens because the inner function remembers the reference to the outer function's variables at the time it's created. It's like the inner function "closes over" the outer function's scope, hence the term "closure."

function createUserInfo(name) {
  let userName = name; // Local variable to `createUserInfo`

  function greetUser() {
    console.log("Hello, " + userName + "!");
  }

  return greetUser;
}

const greetJohn = createUserInfo("Sandeep");
greetJohn(); // Output: Hello, Sandeep!

const greetJane = createUserInfo("Aarush");
greetJane(); // Output: Hello, Aarush!

Enter fullscreen mode Exit fullscreen mode

createUserInfo takes a name as input and creates a local variable userName.

An inner function greetUser is defined that uses userName.

The outer function returns the greetUser function, effectively hiding the userName variable.

Now, calling createUserInfo with different names ("John" and "Jane") creates separate closures. Each closure remembers its own private copy of userName. This way, you can greet different users without worrying about variable conflicts.

And there you have it! By mastering lexical scope and closures, you'll be well on your way to crafting clean, maintainable, and organized JavaScript code. These concepts empower you to safeguard variables from accidental changes, establish privacy within functions, and build modular, reusable code blocks.

So next time when you met an err with a variable you know exactly what went wrong.....

Hope this helps! 😁😁

Top comments (0)