top of page

Closure In JavaScript - Get Projects Help

A function with its lexical scope along with its parents scope even after the parent function is closed is known as closure.


Lexical Scope

let name = 'Abhi';

function greeting() { 
    let message = 'Hi';
    console.log(message + ' '+ name);
}
greeting()


Output

Hi Abhi

name variable is not declared in greeting but inside greeting function we can access value of name variable.


Closure

function  greeting() 
  {   
  let message = 'Hi';
      function sayHi()
 {         console.log(message);     }  
    return sayHi;
 }
 let hi = greeting(); 
hi(); 

Output

Hi

greeting function is called when it is assigned in hi variable and after that greeting function is closed. and after that hi function is invoked, then function can still remember the message variable.

This known as Closure which means it preserves the outer scope in its inner scope.


Are you new to javascript or Just started learning and struggling with javascript project? We have team of javascript developer to help you in javascript project, assignment and for learning javascript at affordable price.


Comentários


bottom of page