Javascript Functions (from a closure)

javascript closure interview question
javascript closures in depth
what is closure in javascript and what is its use
advantage of closure in javascript
javascript closure practice
why we need closure in javascript
javascript interview closures
callback and closure in javascript

I have this code (given below) and when I write c1 = count(); I call the function count() (my current understanding), so the closure will memorize c=1 after the first call.

Later, if I call c1() the result is 1. How comes that the result is 1, if when I called this function once by writing c1=count(), c was already incremented to 1? Shouldn't the value be 2?

function count() {
    var c = 0 ;
    return function() {
        c += 1 ;
        return c ;
    };
}

If not,

Why when I write this function, my output is 'A!'? That means that by writing var x=a() I call the function, the same logic should be used in the function above, shouldn't it?

function a() {
  alert('A!');
  return function() {
    alert('B!');
  };
};
var x = a();

here is your function,

function count() {  
 var c = 0 ;
 return function() {
   c += 1 ;
   return c ;
 };
}

first time when you call the function count() it does 2 things,

  1. Initialising var c
  2. returns a function which contains a reference to the variable c which was declared in outer scope. (Learn more about closure: This is a good article https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36)

Now return value of count() i.e a return function is assigned to the variable c1. c1 is a function which when you call increments the value of variable c.

when you do,

var c1 = count(); // c = 0 & a function is assigned to c1
c1(); // c + 1 i.e 1
c1(); // c = 2

and so on..

Now next case,

function a() {
  alert('A!');
  return function() {
    alert('B!');
  };
};
var x = a();

when you call a()

  1. alert('A!')
  2. returns a function and assigning it to x;

next time when you call x() it will always alert('B!')

Hope this helps.

JavaScript Function Closures, The reason is that functions in JavaScript form closures. A closure is the combination of a function and the lexical environment within which that  In JavaScript, closures are created every time a function is created, at function creation time. A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment).

When you call count then you return the inner function from count which you store in c1:

return function() {
  c += 1 ;
  return c ;
};

But at that time you haven't called that returned function, so c is still 0.

When you now call the returned function you stored in c1 by writing c1 then c is incremented by 1, so for the first call of c1 you get 1.

function count() {
  console.log('var c=0')
  var c = 0;


  console.log('return function () { ...  }')
  return function() {
    console.log('c += 1')
    c += 1;
    console.log('return c')
    return c;
  };
}

console.log('var c1 = count()')
var c1 = count();

console.log('c1()')
console.log(c1())
console.log('c1()')
console.log(c1())

Closures, As we can see the variables within the closure in the scope section. Definition of Closure: In programming languages, closures (also lexical closures or function  Introduction to Closures in JavaScript. A closure is a combination of a function bundled together with references to its surrounding state i.e. the lexical environment. In other words, a closure provides you access from an inner function to an outer function’s scope. Most of the Developers use closures in JavaScript consciously or unconsciously.

function count() {

   var c = 0 ;
   return function() {
     c += 1 ;
     return c ;
    };
}

Every time you call that function, you set the value to 0 - so it's alway going to return one. Instead call it increment count, and pass the value to be incremented in:

function incrementCount(valToInc) {
   return valToInc += 1;
}

incrementCount(4); //returns 5

Closure in JavaScript, A closure is a function that has access to its outer function scope even after the outer function has returned. This means a closure can  A function in JavaScript is not just a reference to a set of instructions (as in C language), but it also includes a hidden data structure which is composed of references to all nonlocal variables it uses (captured variables). Such two-piece functions are called closures. Every function in JavaScript can be considered a closure.

Understanding Closures in JavaScript, A closure is a function that remembers its outer variables and can access them. In some languages, that's not possible, or a function  A closure is a function that remembers its outer variables and can access them. In some languages, that’s not possible, or a function should be written in a special way to make it happen. But as explained above, in JavaScript, all functions are naturally closures (there is only one exclusion,

Variable scope, Here is the awesome thing about closures: they allow you to write functions with an intermediate step that can capture data from your site at a  When you declare a variable in a function, you can only access it in the function. These variables are said to be scoped to the function. If you define any inner function within another function, this inner function is called a closure. It retains access to the variables created in the outer function.

JavaScript Closures Explained by Mailing a Package, A closure is a function which has access to the variable from another function's scope. This is accomplished by creating a function inside a function. Of course, the  Closure is simply a function defined inside an object anonymously. We all know that Function is an Object, closure will have access to the variables of the object(ie., function) it defined.

Comments
  • "I called this function once by writing: c1=count()" -- no, you didn't. count() and createsreturns an anonymous function that you store in c1 but it doesn't call it. Then you call it using c1().
  • I believe he wants to increment a number, but thinks that functions retain some sort of memory
  • In the second snippet you're just alerting A directly, there's no closure over any variable in a function. Calling x() alerts B.
  • @DMcCallum83 There is a sort of memory: the variable is stored in closure. Confusion seems to only regard to when function calls happen. Besides, I believe Claire is usually a female name.
  • One more important thing about closures. If you'll assign the result of count for a second time, to another variable, this call will create a new closure, and c1 calls will continue to count c from its current value, i.e. it is not reset.
  • What happens when I have only this : c1 = count(); ?
  • @Claire c=0 and the return of the function you define within count but that function is not called at that time. Check the logs messages of the runnable snippet.
  • So that means that in the second function if i do : x(), the result will be 'B!' ?
  • @Claire Well, what does it show if you do so? I mean it would be faster to test that your self then asking it as a question.
  • No, it won't be always 1. The call of count will return a function and never 1, and if you then call this returned function, it will increment c every time it is called: fiddle demo