user1477955
user1477955

Reputation: 1670

JS - function declared inside a function

Is it ok regarding performance and efficiency to declare a function inside a function that is called on each AnimationFrame? Is A) as ok as B) ?

A)

function update() {
    function do () { ...}
}

B)

function update() {
   do();
}

 function do () { ...}

Upvotes: 0

Views: 64

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

No, it's not a good idea because you're making it redeclare the same function over and over.

A better pattern would be:

(function() { // this is your closure
    var genericVariableOne = 123,
        genericVariableTwo = 456;
    function genericFunctionOne() {...}

    // now do stuff here
})();

This way you are only declaring functions once within the closure. For variables, declaring them outside may or may not be a good idea depending on how they are used.

Upvotes: 2

Y123
Y123

Reputation: 977

Yes - it is ok to declare functions inside functions and in fact desirable in many situations. They are called closures. All major JavaScript APIs depend on this concept heavily from jQuery, to AngularJS to Dojo. Older versions of MSIE discouraged it's use but all modern browsers use JavaScript engines that are very efficient and can give you good performance with closures.

Upvotes: 1

Related Questions