When to Use Nested Functions
Tags: javascript, programming, beginners
Published: 2023-05-14 08:58:30

---
title: When to Use Nested Functions
published: true
date: 2023-05-14 08:54:02 UTC
tags: javascript, programming, beginners
canonical_url: https://evgenii.info/nested-functions/
---

> Warning: the word function appears more often than you are probably used to. Sorry.

 ![When to Use Nested Functions](https://evgenii.info/content/images/2021/06/yash-jain-BCixU5xjRy0-unsplash--1-.jpg)

Alright, let's begin: nested <u>functions</u> are <u>functions</u> defined inside other <u>functions</u> (promised and delivered). You saw them in many forms, like this one:

![When to Use Nested Functions](https://evgenii.info/content/images/2021/06/pow-1.png)

Here, the function `multiply` is defined inside its parent, `pow`, although it does not have to be this way.

Or does it? If nothing else uses multiply, are there any reasons to move it out?

![When to Use Nested Functions](https://evgenii.info/content/images/2021/06/button.jpg)<figcaption>Tough choice</figcaption>

This topic regularly ignites lengthy bike-shedding conversations regardless of the programming language ([stack overflow about python](https://stackoverflow.com/questions/4831680/is-nested-function-a-good-approach-when-required-by-only-one-function), [reddit about swift](https://www.reddit.com/r/swift/comments/4f4kb5/does_nested_function_promote_clean_code/)), so I want to jump in and list some more pros and cons which you can apply for your needs.

## Why you should **<u>not</u>** use nested function

### Nested functions reduce readability

The bigger a function is, the harder it is to read it.  
Look at this example:

![When to Use Nested Functions](https://evgenii.info/content/images/2021/06/show-news-1.png)

By defining three additional functions inside `showNews`, you make the reader's job harder: they have to scan all of them before reaching the part with actual logic.

It might be much shorter:

![When to Use Nested Functions](https://evgenii.info/content/images/2021/06/show-news-2.png)

The reader still can jump to any functions to see how they work, but now it's optional.

### Nested functions influence future growth

One may argue that not all nested functions affect readability.

In the previous example, you had three big helpers — pretty bad. What if there was only one?

![When to Use Nested Functions](https://evgenii.info/content/images/2021/06/with-error.png)

Does having `loadNews` inside the primary function cause any harm? After all, it is just several extra lines.

The danger of this approach shows itself when someone needs to add more functionality. You should not be surprised when your colleagues follow the same style and add other nested functions next to the existing one. After all, they just follow the rules you defined as an author.

> All it takes to degrade a good codebase is one example of a poor pattern and people's intent to maintain the code style.   
>   
> Check the article about "[Reckless Reuse"](https://evgenii.info/reckless-reuse/) for more examples of how code becomes unmaintainable without anyone noticing.

## When nested functions are <u>good</u>

Now you may have an idea that all nested functions are evil and should be avoided by any means.

This is not true.

In some cases, they bring some benefits that can outweigh the disadvantages.

### Sometimes you do not want others to use your functions

Yes, functions are meant to be reused. But you may not want it, e.g. if a function handles your particular case but is not suitable for everyone:

![When to Use Nested Functions](https://evgenii.info/content/images/2021/06/is-equal-1.png)

There are many cases in which `isEqual` returns an unexpected result:

![When to Use Nested Functions](https://evgenii.info/content/images/2021/06/wow.png)

But it may be the exact behaviour you need.

In this case, it will be safer to define this function inside `saveNews` so that nobody has to deal with its peculiarities.

### Sometimes you need access to an outer scope

Many languages give nested functions access to the variables from the parent scope and even allow to modify them. You may need to explicitly declare such variables (Python) or capture them by reference (C++), but the benefits are the same:

![When to Use Nested Functions](https://evgenii.info/content/images/2021/06/handle-error.png)

In this case, the alternative would be passing all arguments to `reportError` every time we call it, using `Function.prototype.bind` or wrapping it into a factory. While I prefer different things depending on the situation, I see why somebody may use nested functions here.

### Some implementation details are helpful

From the reader's point of view, there are few things worse than jumping between functions to understand how the whole thing works.

Try to understand this piece:

![When to Use Nested Functions](https://evgenii.info/content/images/2021/06/no-details.png)

The functions `onSuccess` and `onError` do not only hide implementation details but also obscure their purpose. You know something happens, but you don't know what exactly.

In this case, it would be better to define `onSuccess` and `onError` within the primary function so that the reader knows _what_ is happening without leaving it:

![When to Use Nested Functions](https://evgenii.info/content/images/2021/06/more-context.png)

Two things to note here:

- Implementation details are still hidden: you know _what_ is happening but not _how_
- Try to avoid situations like this by better naming and defining better APIs. The downsides of nested functions are still there.

## So, what to do?

I usually try to avoid nested functions because they make their parents bigger and, as a result, harder to read. Even if a nested function is concise and the impact is negligible, it can potentially become a slippery slope and serve as a bad example for adding similar ones.

But, as you can see, there are some situations when going this path does worth the downsides.

I hope that now you can defend any side in this holy war and justify the style you prefer. Happy coding!

* * *

As always, you can [subscribe to Resilient Systems](https://evgenii.info/#/portal/signup) and receive new articles by email if you haven't done it yet.   
You also can [find me on Twitter](https://twitter.com/_elergy_) or somewhere else – I am always happy to chat :-)