Will the inner function be declared every time I call the outer function?
Yes. However, this isn't really that inefficient, and is well optimised by engines.
If it is declared everytime, is there a way to make the code more performant without using global variables?
Don't make your code more complicated than it needs to be. If it works and is maintainable as currently written, leave it as it is. outer
may be called often, many times, but unless it's a really hot path and you did identify this as a performance bottleneck via benchmarks, there's no need to take action. Premature optimisation is the root of all evil.
But back to your question: Yes, there is a way to avoid the recreation of the function without using global variables. Just pass the values that inner
needs as arguments to every call:
function inner(a,b){
console.log(a[b]);
}
function outer(a,b){
inner(a,b);
}
Assuming that the inner function doesn't assign to the closure variables this works well.
If you want to avoid putting inner
in the global scope, just use the module pattern to create outer
.