Is this really possible.
Yes.
function a(x) { // <-- function
function b(y) { // <-- inner function
return x + y; // <-- use variables from outer scope
}
return b; // <-- you can even return a function.
}
console.log(a(3)(4));
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Answer from kennytm on Stack OverflowIs this really possible.
Yes.
function a(x) { // <-- function
function b(y) { // <-- inner function
return x + y; // <-- use variables from outer scope
}
return b; // <-- you can even return a function.
}
console.log(a(3)(4));
Run code snippetEdit code snippet Hide Results Copy to answer Expand
The following is nasty, but serves to demonstrate how you can treat functions like any other kind of object.
var foo = function () { alert('default function'); }
function pickAFunction(a_or_b) {
var funcs = {
a: function () {
alert('a');
},
b: function () {
alert('b');
}
};
foo = funcs[a_or_b];
}
foo();
pickAFunction('a');
foo();
pickAFunction('b');
foo();
How to use the same function (which is created inside a function) inside another function?
javascript - Should I place functions that are only used in one other function, within that function? - Software Engineering Stack Exchange
Using a function in another function
JavaScript Nested function - Stack Overflow
Hello everyone.
I am asking because I am curious (not that I need the answer right now ((as I managed to solve my problem by using the parent function instead of using the child function))).
Let's say you have a function inside a function but you want the use the same inner(child) function inside a another function. As this inner function has the function scope (instead of global scope) you won't be using this inner function directly inside another function. Soo, what are the possible methods for this?
Example:
function outerFunction () {
function innerFunction();
}
function anotherFunction () {
function innerFunction();
}
I'm generally in favor of nested functions, especially in JavaScript.
- In JavaScript, the only way to limit a function's visibility is by nesting it inside another function.
- The helper function is a private implementation detail. Putting it at the same scope is akin to making a class' private functions public.
- If it turns out to be of more general use, it's easy to move out, because you can be confident the helper is currently only used by that one function. In other words, it makes your code more cohesive.
- You can often eliminate parameters, which makes the function signature and implementation less verbose. This is not the same thing as making variables global. It's more like using a class member in a private method.
- You can give the helper functions better, simpler names, without worrying about conflicts.
- The helper function is easier to find. Yes, there are tools that can help you. It's still easier to just move your eyes up the screen a bit.
- Code naturally forms a sort of tree of abstraction: a few general functions at the root, branching out into several implementation details. If you use an editor with function folding/collapsing, nesting creates a hierarchy of closely-related functions at the same level of abstraction. That makes it very easy to study the code at the level you need and hide the details.
I think a lot of opposition comes from the fact that most programmers were either brought up in a C/C++/Java tradition, or were taught by someone else who was. Nested functions don't look natural because we weren't exposed to them much when we were learning to program. That doesn't mean they aren't useful.
You should put it at global scope, for several reasons.
Nesting a helper function into the caller increases the length of the caller. Function length is almost always a negative indicator; short functions are easier to understand, to memorize, to debug and to maintain.
If the helper function has a sensible name, reading that name is enough without needing to see the definition nearby. If you do need to see the helper definition in order to understand the caller function, then that caller is doing too much, or is working on too many levels of abstraction simultaneously.
Having the helper globally available allows other functions to call it if it turns it to be generally useful after all. If the helper isn't available, you're tempted to cut and paste it, or to forget it and reimplement it, poorly, or to make another function longer than it has to be.
Nesting the helper function increases the temptation to use variables from the caller's scope without declaration, so that it becomes unclear what the inputs and outputs of the helper are. If a function doesn't clearly state what data it operates on and what effects it has, it is usually a sign of unclear responsibilities. Declaring the helper ass a standalone function forces you to know just what it actually does.
Edit
That turned out to be a more controversial question than I thought. To clarify:
In JavaScript, big file-spanning functions often fulfill the role of classes because the language doesn't provide any other scope-limiting mechanism. Certainly helper functions should go inside such quasi-classes, not outside them.
And the point about easier reuse presupposes that if a subroutine does become more widely used, you are willing to move it out of place altogether and put it in appropriate place, e.g. a string utility library or into your global configuration registry. If you don't want to order your code like that, then you might as well nest the subroutine, just like you would do with a normal Method Object in a more "blocky" language.
Functions are another type of variable in JavaScript (with some nuances of course). Creating a function within another function changes the scope of the function in the same way it would change the scope of a variable. This is especially important for use with closures to reduce total global namespace pollution.
The functions defined within another function won't be accessible outside the function unless they have been attached to an object that is accessible outside the function:
function foo(doBar)
{
function bar()
{
console.log( 'bar' );
}
function baz()
{
console.log( 'baz' );
}
window.baz = baz;
if ( doBar ) bar();
}
In this example, the baz function will be available for use after the foo function has been run, as it's overridden window.baz. The bar function will not be available to any context other than scopes contained within the foo function.
as a different example:
function Fizz(qux)
{
this.buzz = function(){
console.log( qux );
};
}
The Fizz function is designed as a constructor so that, when run, it assigns a buzz function to the newly created object. That is, you'd use it like this:
const obj = new Fizz();
obj.buzz();
or more concisely (if you don't need to keep the object after calling buzz):
new Fizz().buzz();
It is called closure.
Basically, the function defined within other function is accessible only within this function. But may be passed as a result and then this result may be called.
It is a very powerful feature. You can see more explanation here:
javascript_closures_for_dummies.html mirror on Archive.org
Yes, what you have there is right. Some notes:
baris created on every call to the functionfoo, but:- On modern browsers this is a very fast process. (Some engines may well only compile the code for it once, and then reuse that code with a different context each time; Google's V8 engine [in Chrome and elsewhere] does that in most cases.)
- And depending on what
bardoes, 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.
- The performance impact, if any, of having
barcreated every time will vary widely between JavaScript engines. Ifbaris trivial, it will vary from undetectable to fairly small. If you're not callingfoothousands of times in a row (for instance, from amousemovehandler), 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. barwill 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.- Note that because you've used a function declaration, it doesn't matter where you put the declaration (top, bottom, or middle — as long as it's at the top level of the function, not inside a flow control statement, which is a syntax error), it gets defined before the first line of step-wise code is run.
This is what closures are for.
var foo = (function () {
function bar() {
// perform task 3
};
function innerfoo (a) {
if (/* some cond */ ) {
// perform task 1
bar();
}
else {
// perform task 2
bar();
}
}
return innerfoo;
})();
Innerfoo (a closure) holds a reference to bar and only a reference to innerfoo is returned from an anonymous function which is called only once to create the closure.
Bar is not accessible from the outside this way.