function foo(a) { if (/* Some condition */) { // perform task 1 // perform task 3 } else { // perform task 2 // perform task 3 } }
I have a function whose structure is similar to the above. I want to abstract task 3 into a function, bar()
, but I wish to limit the access of this function to only within the scope of foo(a)
.
To achieve what I want, is it right to change to the following?
function foo(a) { function bar() { // Perform task 3 } if (/* Some condition */) { // Perform task 1 bar(); } else { // Perform task 2 bar(); } }
If the above is correct, does bar()
get redefined every time foo(a)
gets called? (I am worrying about waste of CPU resource here.)
A function defined inside another function is called a nested function. Nested functions can access variables of the enclosing scope. In Python, these non-local variables are read-only by default and we must declare them explicitly as non-local (using nonlocal keyword) in order to modify them.
A nested function is a function inside another function. We can create the nested function in the same way we create the normal JavaScript function, But inside another function. In the following example, we create the logToConsole function inside the addNum function.
Yes, what you have there is right. Some notes:
bar
is created on every call to the function foo
, but: bar
does, some engines may determine that they can "inline" it, eliminating the function call entirely. V8 does this, and I'm sure it's not the only engine that does. Naturally they can only do this if it doesn't change the behavior of the code.bar
created every time will vary widely between JavaScript engines. If bar
is trivial, it will vary from undetectable to fairly small. If you're not calling foo
thousands of times in a row (for instance, from a mousemove
handler), I wouldn't worry about it. Even if you are, I'd only worry about it if I saw a problem on slower engines. Here's a test case involving DOM operations, which suggests that there is an impact, but a trivial one (probably washed out by the DOM stuff). Here's a test case doing pure computation which shows a much higher impact, but frankly even, we're talking a difference of microseconds because even a 92% increase on something that takes microseconds to happen is still very, very fast. Until/unless you saw a real-world impact, it's not something to worry about.bar
will only be accessible from within the function, and it has access to all variables and arguments for that call to the function. This makes this a very handy pattern.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With