1

I'm new to javascript and I have a trouble to understand the following javascript code. So is it possible for you guys to shed me the light on what is the purpose of having multiple functions nested inside the return. What is it for, why we need it and when we should use it.

Many thanks in advance

function create() {
   var counter = 0;
   return {
      increment: function() {
         counter++;
      },

      print: function() {
         console.log(counter);
      }
   }
}
var c = create();
c.increment();
c.print();
newbie
  • 79
  • 1
  • 7

1 Answers1

0

To understand this you need to understand two key concepts:

  1. In JavaScript functions are first class objects
  2. closures.

The create function returns an object that has two fields who's values are actually functions and that both have a closure that contains the counter variable. So the c variable is assigned an object (which is created by the create function) and that object has two functions that you can simply call that both reference the same counter variable.

Community
  • 1
  • 1
Koen Peters
  • 12,798
  • 6
  • 36
  • 59