JS-coder
JS-coder

Reputation: 3271

JavaScript closures issue

Why this doesn't fire:

var counter = function () {

    return function() {
        alert('Fire!');
    }
}

counter(); 

but this does:

var counter = function () {

    return function() {
        alert('Fire!');
    }
}

var test = counter(); 
test();

It seems like assigning function to a variable makes difference but why?

Upvotes: 1

Views: 78

Answers (6)

nefarianblack
nefarianblack

Reputation: 802

In your code

var counter = function () {

    return function() {
        alert('Fire!');
    }
}

counter(); 

you are simple getting a function in return of counter(). It is like calling a function which returns a value and you are not catching it.

You have to catch the return function and then call it as you have done it in second code.

Upvotes: 0

nurettin
nurettin

Reputation: 11736

Try calling the function returned

counter()(); 

Upvotes: 3

Jacob
Jacob

Reputation: 4021

var counter = function () {
        alert('Fire!');
}

counter();

This would fire

Upvotes: 0

SReject
SReject

Reputation: 3936

Ok with your first example, you are assigning

function() {
    alert('Fire!');
}

to the variable. But aren't asking for it's value. In your second example, you assign the function to the variable as above, then you call are calling it.

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191729

count() returns a function. It does fire, it just doesn't call the function that it returns. In the second example, you are returning the inner function, then firing it via test(). If you want the examples to be similar, change test = count() to test = counter.

Upvotes: 2

Fdr
Fdr

Reputation: 3714

You are returning a function. You have to call it also.

Upvotes: 2

Related Questions