Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing a named function after declaring it

Tags:

javascript

I know that this can be done for anonymous functions

(function toBeExecutedImmediately() {
    // Code
}());

I have a function that I wish to use in other places, but should also be executed immediately. Is it possible to do it with one statement instead of the following? The return value isn't needed.

function toBeExecutedImmediately() {
    // Code
};

toBeExecutedImmediately();
like image 584
xiankai Avatar asked Nov 03 '13 11:11

xiankai


1 Answers

Is it possible to do it with one statement instead of the following?

No. As you've found, the named function expression (your first example) doesn't add the name to the containing scope (except on broken engines — I'm looking at you, IE8 and earlier), so you can't call the function elsewhere without doing something to make that possible, and of course with the function declaration (your second example), you have to give the name twice.

Your best bet is probably to just go ahead and do the declaration and the separate call (your second example).

We could probably come up with something convoluted that would technically meet the definition of "a single statement," but it's unlikely to be shorter.

If brevity is your goal, this is two statements, but brief:

var f = function() {
    // Code
}, toBeExecutedImmediately = f;
f();

But while relatively brief, I'd say clarity suffers. :-)

Of course, anything is possible if you add a helper function. For instance:

// The helper
function defineAndExecute(f) {
    f();
    return f;
}

// using it
var toBeExecutedImmediately = defineAndExecute(function() {
    // Do work here
});

The function is technically anonymous, but you can call it via the var. (You could use a named function expression here too, but of course that would defeat the goal — not repeating the name — as I understand it.)


Side note: Your first example is not "an anonymous function". The function has a proper name, it's a named function expression. It's just that with named function expressions, unlike function declarations, that name isn't added to the containing scope.

like image 61
T.J. Crowder Avatar answered Oct 10 '22 00:10

T.J. Crowder