Do I need to override a nested function?

For architecture and name purposes, I want to do this:

function outer (arr) { function inner(arrElement) { return doStuffTo(arrElement); } var results = []; arr.forEach(element, index, array) { results.push(inner(element)); } return results; } 

So basically the function is inside the function. Simple things. But outer() is what a lot will be done. Does this mean that the overhead of defining a function (on top of its evaluation) will be applied each time outer() is called? For this to be effective, do I have to define inner() outside?

+4
source share
1 answer

You can use closure:

 var outer = (function() { function inner(arrElement) { return doStuffTo(arrElement); } return function (arr) { var results = []; arr.forEach(element, index, array) { results.push(inner(element)); } return results; } }()); 

inside is held in closure and remains "private" external, and is created only once when the external is initialized.

+4
source

Source: https://habr.com/ru/post/1394100/


All Articles