Scope and Closure

Jivan ParatpureJivan Paratpure
2 min read

What is Scope in JavaScript.

Let's understand the concept of scope with a simple example.

Imagine you are living in a PG (paying guest accommodation) in Bengaluru. You have permission to access your own room, so you can enter it without any issues. However, you cannot enter someone else's room because you don’t have the key. If you try, you'll get a "key error."

On the other hand, the owner of the PG has access to all the rooms because they have all the keys.

  • You represent a block of code.

  • The key you have represents a local variable, which is accessible only within that block.

  • The owner represents the global scope.

  • The keys the owner has represent global variables, which can be accessed from anywhere in the code.

Types of Scope

Global scope

In programming, global scope means a variable can be used anywhere in the code. A global variable is declared outside any function or block, so all parts of the program can access it.

//global scope
let myName = "I am global";// glbal declrattion 
function printName(){
    console.log(myName) // this is accesible 
}

console.log(myName);

//expected output 
//I am global

Local Scope

Local scope means a variable can only be used inside the function or block where it is declared. It cannot be accessed from outside.

//Local scope
function printStatus(){
     function square(num){
         return num*num;
        }
     let myname ="I am local access me inside it only not outside";//declared inside printstatus function
     console.log(myname);
}
console.log(myname);
//you cant access myname outside of the function

Closure in JavaScript

A closure is a function that remembers the variables from its outer function even after the outer function has finished execution. Closures allow functions to have private variables.

//closure 
function family(){
     let familyIncome = 80000;
     function printIncome(){
          console.log(familyIncome);
          familyIncome = familyIncome*2;
    }
}
console.log(printIncome());
// it will give us 80000 as output 
// next to it the familyIncomme will be

let's understand with a new example that the student can access the marks inside the function.

function studentMarks(marks) {
  return function () {
    console.log(`Student's marks: ${marks}`);
  };
}

const getMarks = studentMarks(85);
getMarks(); // Output: Student's marks: 85

javascript is friend if you treat it as friend otherwise it is language only ,let treat as friend and understand it .

0
Subscribe to my newsletter

Read articles from Jivan Paratpure directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jivan Paratpure
Jivan Paratpure