Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which Javascript function placement is better?

I'm trying to build a game and I noticed that for organization it might be better to place some functions inside other functions because they are used in the original function exclusively. For example:

function fn1()
{
    fn2();

    function fn2()
    {
        //Stuff happens here
    }
}

fn1 gets called many times, and fn1 will call fn2 several times in its execution. When fn1 is called, does fn2 have to be re-processed (for lack of a better word) every time? Am I losing out in terms of performance because of this? Should I place fn2 after fn1 instead, like this?

function fn1()
{
    fn2();
}

function fn2()
{
    //Stuff happens here
}
like image 788
Rstevoa Avatar asked Aug 26 '13 18:08

Rstevoa


People also ask

Where should functions be placed in JS?

JavaScript in head: A JavaScript function is placed inside the head section of an HTML page and the function is invoked when a button is clicked. JavaScript in body: A JavaScript function is placed inside the body section of an HTML page and the function is invoked when a button is clicked.

Does function placement matter in JavaScript?

There is actually no difference at all where you declare the function (it always behaves as if the declaration is on the beginning).

What is a function when is it good practice to use a function in JavaScript?

JavaScript functions are essential when writing JavaScript programs if you want to execute a block of code as many times as you want without having to write the same block of code repeatedly in your program. We can simply say the function is a saved algorithm given to a program to work with when called upon.


1 Answers

You can do this to achieve similar scoping, but only create one copy of fn2:

//Initiliaze before you call `fn1`:  
var fn1 = (function(){

    // This is the function assigned to fn1
    return function(){
        fn2();
    }

    function fn2()
    {
        //Stuff happens here
    }
})();

Compare the console output of these to fiddles, the former of which creates an extra copy of fn2, since a locally scoped fn2 is created for each call to fn1: http://jsfiddle.net/A2UvC/3/ and http://jsfiddle.net/A2UvC/3/

There are advantages to the additional copys of fn2 however. They may have access to different variables like in the following situation:

function fn1(x){

    // Return an object exposing fn2 to the caller's scope
    return {fn2: fn2};

    // Each call to fn1 creates a new fn2 which has access 
    // to the closured `x` from the call to fn1 that created it
    function fn2(){
        console.log(x);
    }

}

var ex1 = fn1(1);
var ex2 = fn1(2);

ex1.fn2 == ex1.fn2; // true
ex1.fn2 == ex2.fn2; // false, because they are two distinct copies

ex1.fn2(); // 1
ex2.fn2(); // 2
ex2.fn2(); // 2
ex1.fn2(); // 1
like image 93
Paul Avatar answered Oct 03 '22 17:10

Paul