This really depends on how much nesting you use. After all, you are allowed to use function results directly in expressions to improve readability. Both, code that does not use nested expressions (like assembler code), and code that uses too much nested expressions is hard to read. Good code tries to strike a balance in between the extremes.

So lets look at some examples. The one you gave in your question seems quite legit to me, so nothing to worry here. However, a line like

foo(bar(baz(moo, fab), bim(bam(ext, rel, woot, baz(moo, fab)), noob), bom, zak(bif)));

would definitely not be tolerable. Likewise, code like

double xsquare = x*x;
double ysquare = y*y;
double zsquare = z*z;
double xysquare = xsquare + ysquare;
double xyzsquare = xysquare + zsquare;
double length = sqrt(xyzsquare);

would not be very readable as well. sqrt(x*x + y*y + z*z) is much easier to understand, even though it combines a total of six different operation in one expression.

My advice is to pay attention to what expressions you can still parse in your head easily. The moment you need to take a second look to grasp what a single expression does, it's time to introduce an additional variable.

Answer from cmaster - reinstate monica on Stack Exchange
🌐
Reddit
reddit.com › r/learnjavascript › when is nesting functions considered bad form, and why? (example given)
r/learnjavascript on Reddit: When is nesting functions considered bad form, and why? (example given)
August 9, 2016 -

Hey peeps,

I've been using js for a while now, but it only occurred to me recently that I should probably check that one of my habits isn't horrendously bad form or causing me memory/efficiency problems etc.

SO, here's the dilemma :

function setupExample(){

	var button1 = document.getElementById("button1");
	var button2 = document.getElementById("button2");
	var button3 = document.getElementById("button3");

	button1.addEventListener("click", toggleExampleOne);
	button2.addEventListener("click", toggleExampleTwo);
	button3.addEventListener("click", toggleExampleThree);

	function toggleExampleOne(){
		button1.classList.toggle("activated");
	}//END toggleExampleOne

	function toggleExampleTwo(event){
		event.srcElement.classList.toggle("activated");
	}//END toggleExampleTwo
	
}//END setupExample

function toggleExampleThree(event){
	event.srcElement.classList.toggle("activated")
}//END toggleExampleThree

Now, I use a structure like this quite regularly - I tend to use example 1 in this case - but my concern now is that by referencing values outside the function called by the click event, the entirety of 'setupExample' would be kept in memory when all I actually need is the toggle functions!

Are example 2 or 3 better in this case, or am I worrying about nothing and there is absolutely no difference between the three?

Thanks in advance, peeps!

-P

Top answer
1 of 5
3

Why do you think that nesting functions is bad form? Modern Javascript is often written in a class-like block structure, to make for ease of exporting.

As other commenters have observed, nested functions are "private" in the sense that you won't be able to access them directly. This is a feature, not a bug. It's really the cornerstone of object-oriented programming: by nesting related functions into the same shared block structure, you can vastly reduce the complexity of your code base.

This is the way I write JS code by default:

var basketModule = (function () {

  // privates

  var basket = [];

  function doSomethingPrivate() {
        //...
  }

  function doSomethingElsePrivate() {
        //...
  }

  // Return an object exposed to the public
      return {

          // Add items to our basket
          addItem: function( values ) {
              basket.push(values);
          },

          // Get the count of items in the basket
          getItemCount: function () {
              return basket.length;
          },

          // Public alias to a private function
          doSomething: doSomethingPrivate,

          // Get the total value of items in the basket
          getTotal: function () {

              var q = this.getItemCount(),
                  p = 0;

              while (q--) {
                  p += basket[q].price;
              }

              return p;
          }
     };
 })();

This is similar to what in other languages is called a class.

2 of 5
3

What you're doing here is utilizing closures.

function toggleExampleOne(){
    button1.classList.toggle("activated");
}//END toggleExampleOne

This is closing over the variable button1 in the outer scope. This will cause the function to be evaluated with this context every time it is called, which can be inefficient. There's a process you can do called lifting which flattens the closure - this is what your example three does.

However, I would largely not be too concerned about inefficiencies here. Micro-optimizations can quickly consume you: do what works best for making a maintainable application, then if you have performance problems, measure, and optimize your hot paths (the parts of your application that are used the most often). Especially so since most javascript engines are really quite optimized and will know how to transform your code in subtle ways to improve performance (like doing that lifting for you).

If you're worrying about cluttering up your global namespace though, look into modules or namespaces.

Nested functions Aug 16, 2024
r/C_Programming
2y ago
Is it always best to avoid nesting if possible. Sep 18, 2021
r/learnpython
5y ago
Making code readable: tell me why nesting is bad Jun 5, 2016
r/learnpython
10y ago
CSS modules; nesting? Mar 1, 2021
r/reactjs
5y ago
More results from reddit.com
🌐
Medium
medium.com › re-stacked › are-python-nested-function-calls-a-bad-practice-35aa133af7e4
Are Python nested function calls a bad practice? | by Kyle Pastor | RE:Stacked | Medium
February 21, 2023 - Nested function calls are not inherently bad practice in Python or in programming in general. In fact, nested function calls can often make code more concise and easier to read.
Top answer
1 of 5
17

This really depends on how much nesting you use. After all, you are allowed to use function results directly in expressions to improve readability. Both, code that does not use nested expressions (like assembler code), and code that uses too much nested expressions is hard to read. Good code tries to strike a balance in between the extremes.

So lets look at some examples. The one you gave in your question seems quite legit to me, so nothing to worry here. However, a line like

foo(bar(baz(moo, fab), bim(bam(ext, rel, woot, baz(moo, fab)), noob), bom, zak(bif)));

would definitely not be tolerable. Likewise, code like

double xsquare = x*x;
double ysquare = y*y;
double zsquare = z*z;
double xysquare = xsquare + ysquare;
double xyzsquare = xysquare + zsquare;
double length = sqrt(xyzsquare);

would not be very readable as well. sqrt(x*x + y*y + z*z) is much easier to understand, even though it combines a total of six different operation in one expression.

My advice is to pay attention to what expressions you can still parse in your head easily. The moment you need to take a second look to grasp what a single expression does, it's time to introduce an additional variable.

2 of 5
10

The concept underlying your question is so important I feel it needs another answer rather than just a comment (as I had started to do).

The other 3 answers thus far provide some useful points of consideration on whether a given situation merits using what you call "nested function calls". But perhaps a more important point is hidden in the comments under your question: in case you missed the subtlety in what those erudite folks are suggesting, Carl, you have discovered for yourself the topic actually called functional programming. If you have never seen the term, you might not have thought it was really a "thing" in @HighPerformanceMark's comment.

But indeed it is! Functional programming has been written about for decades, since John Hughes' seminal paper Why Functional Programming Matters. There are some languages that are functional languages (i.e. they only let you write in a functional programming style), languages like Erlang, Lisp, OCaml, or Haskell. But there are many more languages that are hybrid imperative/functional languages. That is, they are traditionally imperative languages but offer some support for functional programming as well, including Perl, C++, Java, C#, and many more. Wikipedia's entry on functional programming provides a nice section showing a comparison of functional style vs. imperative style for a number of languages.

There is much to say on the differences between imperative and functional styles, but the key starting point is that with functional programming, functions or methods have no side effects, making it in general easier to both understand and debug programs.

For further reading, you might also take a look at Reginald Braithwaite's Why "Why Functional Programming Matters" Matters and another interesting post here on SO, Why functional languages?

🌐
Quora
quora.com › Is-it-a-bad-practice-to-nest-functions-in-JavaScript
Is it a bad practice to nest functions in JavaScript? - Quora
Answer (1 of 3): No. This is how closures are born. With the popularity of jQuery, this pattern is becoming very common: [code js] $(document).ready(function () { // stuff here }); [/code] If that "stuff here" code included a function declaration, you'd end up with a nested function. This i...
🌐
Towards Data Science
towardsdatascience.com › home › programming › should you use nested functions to encapsulate logic?
Should you use nested functions to encapsulate logic? | Towards Data Science
November 17, 2020 - Anyone who programmed in python has tasted the double edged sword of minimizing noise by eliminating brackets (hint: brackets are not noise...). As for the multitude of names, without training, humans can juggle 1–2 balls in the air. With some consistent training they can do 3. Some talented ones can do 5, but it's vey rare for someone to go that far. We should program with that limitation in mind. To make it into a rule of thumb - there shouldn't be more than 3 names I'm carrying around in my mind when looking at a scope. In the nested function case when reading the scope of bar I now have to carry a, b and c in mind, needlessly.
🌐
Colinsblog
colinsblog.net › 2023-08-05-nesting-functions
Better Code Organization by Nesting Functions - Colin's Notes
August 5, 2023 - Extensive sub-classing can help “organize” behavior but often creates fragmentation and is a well-known bad practice when applied widely. You may create a few classes without state to group helper and main functions together, with all the helpers declared private.
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › when not to use nested functions?
r/learnpython on Reddit: When not to use nested functions?
November 28, 2019 -

I may be calling this wrong, but all I mean is:

def func1():
    
    def func2():

I've seen posts explaining when you should use this, but I haven't found much against using it. I seem to be unintentionally using quite a few.

Is using a nested function best practice? Is it 'efficient'?

 

I only ask as my code seems to be running a little slow at the beginning, so trying to see if I can improve that

🌐
Julia Programming Language
discourse.julialang.org › general usage
Nested functions pros and cons - General Usage - Julia Programming Language
January 9, 2019 - I’ve learned that nested functions are useful in Matlab to avoid passing tons of arguments to external functions when optimizing/fitting some data. Is this still true in Julia? Since lambda functions are very cheap, is …
🌐
Quora
quora.com › When-are-nested-functions-in-JavaScript-an-acceptable-use-and-when-should-they-be-avoided
When are nested functions in JavaScript an acceptable use, and when should they be avoided? - Quora
Answer (1 of 4): The short answer is do what makes the code easier to read and maintain. So much of the time we do things because we think it’s such a clever solution. For .001ms gain when the page runs, we will make something that could be clear and easy to read confusing and tough to follow.
🌐
Real Python
realpython.com › inner-functions-what-are-they-good-for
Python Inner Functions: What Are They Good For? – Real Python
2 weeks ago - The examples of inner functions that you’ve seen so far are ordinary functions that happen to be nested inside other functions. Unless you need to hide your functions from the outside world, there’s no specific reason to nest them.
🌐
Reddit
reddit.com › r/learnpython › is it bad practice to have functions nested in your main function?
r/learnpython on Reddit: Is it bad practice to have functions nested in your main function?
June 11, 2023 -

So, I am writing a main function (so that I can say if name == "main" because that is good practice). And my main file accesses a lot of classes that are not inside of the main function. This is all fine, but then there is a function in a number of different classes that I want to call at once. Think of it like: reset_box(), reset_circle(), reset_triangle() or whatever.

Under certain conditions I want to just hit all these at once. So, it would be nice to have a function I can call that just does them all at once rather than writing them all out each time.

It would be easiest to do this in the main function, to just add in another function that resets everything. Or is this bad code? Should I take the function out of main and call it that way? The downside of this is that I have to pass it every object that I want to reset which will make it look a little ugly?

What are people's thoughts? Is it better to have a little function inside main that I can call to reset a bunch of objects. Or does it seem better to have the function out of main and just pass in every object that I need to?

Top answer
1 of 9
40
You can just make a function that calls all of them def all(): class.method_1() class_two.method_2() class.method_3() Then when you want to cal all three at once you you just call “all()” generally the rule of thumb is if you have to do something more then twice it should probably be it’s own function. We cal this DRY Don’t Repeat Yourself code as opposed to WET We Enjoy Typing code. We are going to need some code to really understand you problem. main() should be calling everything as usually it’s the only thing that is actually running.
2 of 9
4
I'm not a Python programmer per se, I spend more time with C so I may be missing something, but I think that in languages that support it it is NOT a bad practice (at all) to define functions within the scope where they are used. It's a form of encapsulation, and it can serve as a way to keep your code organised and tidy. If your inner function is never called outside of the main function, it makes sense to define it within that main function - making it invisible to anything else. But if I were building something in Python I think I would go one step (OK, a few steps) further and implement the whole application in a class. Then I could just do something like this: if __name__ == "__main__": application = Application() application.run() Of course, any methods of the Application class could also have nested functions within them. You can take this as far as you like. In any case I don't think you really need a function called main(), that's just a leftover convention from C. In Python, anything after if __name__ == "__main__": could be considered the "main" part of your program.
🌐
Envato Tuts+
code.tutsplus.com › home › javascript
Stop Nesting Functions! (But Not All of Them) | Envato Tuts+
October 19, 2011 - That in and of itself isn't a bad thing, but it's the second characteristic that hinders performance: the nested function is repeatedly created due to repeated calls to the outer function.
🌐
Reddit
reddit.com › r/learnprogramming › nested function best practices (python)
r/learnprogramming on Reddit: Nested Function Best Practices (Python)
April 24, 2019 -

I have been writing a class which resembles a binary tree and have been looking to clean up my code a bit and found my way to nested functions. I understand the basic logic behind them and what not, my question is more on how they are used within custom objects.

For example, if i am trying to print the tree in-order and i do something like:

def print_inorder(self):
    def display(node, level):
        if not node:
            return 
        display(node.left_child, level + 1)
        print('\t' * level, node)
        display(node.right_child, level + 1)
   display(self.root, 0)

Would this be correct best practices? The thing that is somewhat confusing to me is switching from using 'self.' for functions relating to the object, to an inner function that doesn't need a 'self.' even though an object is technically calling it. is this already best practice or should I still be using the 'self.'? or is there a better convention to use all together? Thanks.

🌐
Quora
quora.com › The-GCC-compiler-allows-nested-functions-Would-it-be-a-bad-practice-to-nest-functions-inside-of-main
The GCC compiler allows nested functions. Would it be a bad practice to nest functions inside of main? - Quora
Answer (1 of 7): Here’s the question as it appeared when I answered it: > “The GCC compiler allows nested functions. Would it be a bad practice to nest functions inside of main?” This is a classic case of “just because you can do something doesn’t be you should do it.” You’re ...