1

I'm very new to JavaScript, so my apologies if this answer is glaringly obvious or I'm barking up the wrong tree!

What's the difference in the following code snippets:

function primeAddNum(innerHTML) {
    return function() {
        addNum(innerHTML);
        return false;
    };
}
var func = primeAddNum(innerHTML);

The second one:

var func = function() {
        return function() {
            addNum(innerHTML);
            return false;
        };
}();

The top one works the way I'd like it to, but not the bottom, but that's not overly important to me. What I want to know is the logic behind each block, because I just can't see the difference!

1
  • I know this is not the question but having anonymous functions return another anonymous function is pretty incestual. Commented Dec 4, 2012 at 17:43

3 Answers 3

2

The problem with the second block is that innerHTML is undefined there, since you're not passing it. They will become equivalent if you change it to:

var func = function(innerHTML) {
    return function() {
        addNum(innerHTML);
        return false;
    };
}(innerHTML);
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, it makes much more sense now. Can't believe I've been pulling my hair out over this one now I've seen the answer.
Also consider what Esailija said: the second style, with the self-invoking function, is for one use only. You can't create new functions without repeating the whole thing. So, if you plan on reusing primeAddNum, use the first version.
This will not make it un-undefined if it really was undefined, you are just capturing innerHTML instead of relying on an outside reference. Which is of course good but depending on the code not necessary.
@Esailija I'm assuming innerHTML was just an example, not a global var (or anything in scope). The first snippet (which works according to OP) passes that as a parameter to the outer function. I just adjusted the second one to do the same, as I can't see any reason why it wouldn't work otherwise (again, OP states that the second version did not work).
Correct, I should have specified this. It is not a global variable but rather one that loops and changes dependent on a user event. Thanks to both anyway.
1

Well with the second one you can only create a func once. But with first one, you can create many:

var func1 = primeAddNum(innerHTML);
var func2 = primeAddNum(someOtherInnerHTML);

Comments

-1

there is no difference, you can use both without any problems

Comments

Your Answer

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.