1

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?

asked Mar 1, 2013 at 7:02
2
  • 1
    You need to call the function after creating it. as you are doing in second code. Commented Mar 1, 2013 at 7:06
  • This is not really a closure issue. It's just an issue of using a function object. Commented Mar 1, 2013 at 7:22

6 Answers 6

3

Try calling the function returned

counter()(); 
answered Mar 1, 2013 at 7:05
Sign up to request clarification or add additional context in comments.

Comments

2

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

answered Mar 1, 2013 at 7:04

Comments

2

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.

answered Mar 1, 2013 at 7:04

Comments

0

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.

answered Mar 1, 2013 at 7:05

Comments

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

This would fire

answered Mar 1, 2013 at 7:05

1 Comment

so by counter()(), the alert would be fired.
0

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.

answered Mar 1, 2013 at 7:07

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.