forum

home / developersection / forums / what is meant by closure in javascript?give an example.

What is meant by Closure in Javascript?Give an example.

Amrita Bhattacharjee 416 28-Mar-2023

Closure refers to a feature which is used to allow any function for remembering and accessing the lexical scope of it in time of execution of it outside of that scope as well. This means that any function which can be used to maintain the access to the variables as well as parameters from the parent function and after the complete execution of that parent function as well.

An example of closure in JavaScript is as follows:

function outerFunction() {
  var outerVariable = "I am outside!";

  function innerFunction() {
    var innerVariable = "I am inside!";
    console.log(outerVariable);
    console.log(innerVariable);
  }

  return innerFunction;
}

var innerFunc = outerFunction();
innerFunc();

Here in the mentioned example the outerFunction is used to return the innerFunction as a output. When the call of outerFunction takes place then it creates variable called as outerVariable and a specific function called as innerFunction. This innerFunction is used to create innerVariable.

The execution of innerFunction logs the value of outerVariable as well as innerVariable to the console. The innerFunction is used to maintain the access to the outerVariable because of closure.


Updated on 28-Mar-2023

I'm a code enthusiastic final year student pursuing B.Tech in ECE currently in final year and final semester.However, I've done relevant internships as well in the domain of software development and content writing.


Message
Can you answer this question?

Answer

1 Answers

Liked By