Lovya Bird Hasse801 Lovya Bird Hasse801 - 4 years ago 112
Javascript Question

Invoking functions multiple times, but the first time it would print something weird

function counter() {
var n = 0;

return function counter() {
n += 1;

return n;
}
}



var count = counter();

console.log('counter() returns: ' + count);
console.log('invoking the function returns: ' + count());
console.log('invoking the function returns: ' + count());
console.log('invoking the function returns: ' + count());


This function returns a single number and every time it is invoked, the function returns a number that is "one" number higher than the one before.

The problem with this code is this:

console.log('counter() returns: + count);


This would print the actual code of inner function of a counter which is printed
function counter(){ n+= 1; return n; }

instead of 0. Is there anyway to fix it? The other console statements print correctly, which prints out 1 2 3

Answer Source

In the first case the output you get is the function definition ,since you are returning the function to a varibale by assigning var count = counter(). You need to call count like count() so that it executes the function definition

console.log('counter() returns: ' + count());

If you want to print 0 you need to initialize var n = -1 because otherwise your result is will start from 1 as it value is incremented and then returned

function counter() {
    var n = -1;

    return function counter() {
        n += 1;

        return n;
    }
}



var count = counter();

console.log('counter() returns: ' + count());
console.log('invoking the function returns: ' + count());
console.log('invoking the function returns: ' + count());
console.log('invoking the function returns: ' + count());

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download