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?
You cannot invoke a function declaration. The pair of parentheses following the declaration will do nothing at all. You could do something like this:
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:
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:
I really can’t see any reason why you would need to combine the declaration and invocation into one.