Scope in Javascript

Shivam PandeyShivam Pandey
3 min read

What is Scope ?

Scope is an Area of exeuction in Which Variable or function are Visiable or can be refered to use, A Scope have Three Area of Availibility to Execute

  • Global Scope :- This Scope is Created for Every .js file even if it's not have any code inside it, so The Question Arise What does this Global hold or store inside it, Global Store Two thing's inside it First one is Memory and second one is Call stack (code:- code is the time when we assign value to the variable's)

Globalscope.png

  • function Scope :- This Scope is created for the use of variable inside a function which will be not accessible form outside the function. In simple way we can say that a variable which is declared under the function can have a scope inside function only
let name = "Gourve"
  function fn()
{ 
const name ="shivam" 
console.log(name);
//output would be shivam
}
console.log(name);
//output would be Gourve

This is perfect example of function scope const name ="shivam" is not visiable outside its function

  • Block Scope :- This Scope is created by the use of "{ //inside the braces}" and we use Const and let to declare variable's inside the braces We don't use bar due to the reason being var is not a block scoped, The scope of These Variable is only inside the "{}" braces and outside it has not visiablity what so every. ( A block can reside inside a function )

Frame 1.png

Image above will print the Hitesh due to the reason being var fname="Hitesh" is a global available variable and the other fname have a scope of block level

There is another type of scope Which we called Module Scope its

Lexical Scoping in javascript

  • Lexical Scope is the ability for a funciton scope to access variables from the parent scope. we Call the child function to be lexically bound by that of th eparent function.

lexicalscope.png

What is Closure

  • A Closure is the combination of a function and lexical environment within which that function was declared. The environment consist of any local variables that were in-scope at the time the closure was created. In this case sco() is reference to the instance of function *abcd that is created when abc is run. The instance of abcd maintains a reference to its lexical environment within which the variable name exists.

function abc() {
  let name = "shivam";
  function abcd() {
    console.log(name);
  }
  return abcd;
}

var sco = abc();
sco();

Example:-

function makeAdder(x) {
  return function (y) {
    return x + y;
  };
}

const add5 = makeAdder(5);
const add10 = makeAdder(10);

console.log(add5(2)); // 7
console.log(add10(2)); // 12
//MDn Web Docs
0
Subscribe to my newsletter

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

Written by

Shivam Pandey
Shivam Pandey