Give an example of closure in JavaScript?

1 Answer(s)

Following example shows how the variable counter is visible within the create, increment, and print functions, but not outside of them −

function create() {
   var counter = 0;
   return {
      increment: function() {
         counter++;
      },
  
      print: function() {
         console.log(counter);
      }
   }
}
var c = create();
c.increment();
c.print();     // ==> 1
Supporter Answered on August 15, 2019.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.