Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self execute and call a function in JS

I would like to have a function, which would be accessible to call it by other functions and should self execute when declared.

Like:

function some(var_one, var_two)
{
    // do something
}(var_one, var_two); // declare and execute (doesn't work)

function add_pair()
{
    // do something
    some(James, Amber);
}

What is a proper syntax to do this?

like image 1000
James Avatar asked Oct 23 '25 10:10

James


1 Answers

You cannot invoke a function declaration. The pair of parentheses following the declaration will do nothing at all. You could do something like this:

var some;
(some = function (var_one, var_two) {
    console.log(var_one, var_two);
})("a", "b");

​some("b", "c");​​​​

The above example will log "a, b", followed by "b, c". But that looks a bit messy. You could just stick with what you have and call the function like normal:

function some(var_one, var_two) {
    console.log(var_one, var_two);
}
some("a", "b");

Update

Note that by changing the function declaration to an expression (which is what happens in my first example above) you remove the ability to call the function before it appears to be declared in the source, since declarations are hoisted to the top of the scope in which they appear, and assignments happen in place. With a function declaration, the following example works perfectly:

some("a", "b"); // Call it before it appears to be declared
function some(var_one, var_two) {
    console.log(var_one, var_two);
}

I really can't see any reason why you would need to combine the declaration and invocation into one.

like image 64
James Allardice Avatar answered Oct 25 '25 23:10

James Allardice