0

If I place a self-executing JavaScript function inside a 'normal' function, when is it executed?

function normalFunction() {
    var a = 1;

    (function() {
        var b = 2;
        var c = 3;
    })();

    var d = 4;
}
2
  • What you expecting to hear? a will be seen in self-executing function. b and c won't be seen outside self-executing function. Commented Apr 4, 2013 at 14:45
  • I've rewritten the question to make it clearer that the OP was enquiring about when the function is executed Commented Apr 4, 2013 at 14:55

2 Answers 2

2

The IIFE will only be invoked if you call normalFunction. Even though the function block will be parsed at load time, the invocation doesn't happen until the enclosing function runs, and then the IIFE gets called with the empty parameter block - ()

It's almost identical to what would happen if you had written:

function normalFunction() {
    var tmp = function() {
        ...
    };

    tmp();
}

where clearly tmp() only happens during calls to the enclosing function.

Sign up to request clarification or add additional context in comments.

1 Comment

So var b = 2; var c = 3; will executing even if i don't call normalFunction() ?
2

Where a self executing function is placed has very little to do with how it executes. This function will create 2 local variables with initial values, exit and won't have an effect on the enclosing function scope (other than to waste CPU cycles)

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.