What are closures and how are they useful?

devquora
devquora

Posted On: Jan 02, 2023

 

In JavaScript, a closure is a function that has access to the variables and functions defined in its outer scope, even after the outer function has returned.

Here is an example of a closure in JavaScript:

function outerFunction() {
  let outerVariable = 'I am the outer variable';

  function innerFunction() {
    console.log(outerVariable);
  }

  return innerFunction;
}

let myClosure = outerFunction();
myClosure();  // logs "I am the outer variable"


    Related Questions

    Please Login or Register to leave a response.

    Related Questions

    Mean Stack Interview Questions

    What is the Mean Stack?

    Mean stack is combination four popular JavaScript-based technologies MongoDB, Express, AngularJS and Node that allows d..

    Mean Stack Interview Questions

    What is Express?

    Express is lightweight web framework for Node.js.It provides robust and scalable solutions to build single and multi-pa..

    Mean Stack Interview Questions

    Explain Mongoose?

    Mongoose is a MongoDB Object Data Modeling (ODM) library for MongoDB and NodeJS.It provides a straight-forward, schema-..