惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cisco Talos Blog
Cisco Talos Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
爱范儿
爱范儿
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Jina AI
Jina AI
雷峰网
雷峰网
The Register - Security
The Register - Security
The Cloudflare Blog
博客园 - 【当耐特】
M
MIT News - Artificial intelligence
I
InfoQ
博客园 - 三生石上(FineUI控件)
H
Help Net Security
博客园 - 司徒正美
Vercel News
Vercel News
WordPress大学
WordPress大学
S
SegmentFault 最新的问题
云风的 BLOG
云风的 BLOG
B
Blog
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
L
LangChain Blog
人人都是产品经理
人人都是产品经理
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
T
Tailwind CSS Blog
aimingoo的专栏
aimingoo的专栏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Recorded Future
Recorded Future
小众软件
小众软件
Martin Fowler
Martin Fowler
罗磊的独立博客
Stack Overflow Blog
Stack Overflow Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
酷 壳 – CoolShell
酷 壳 – CoolShell
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Apple Machine Learning Research
Apple Machine Learning Research
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - Franky
Hugging Face - Blog
Hugging Face - Blog
Y
Y Combinator Blog
V
Visual Studio Blog
F
Fortinet All Blogs
Microsoft Azure Blog
Microsoft Azure Blog
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
N
Netflix TechBlog - Medium
V
V2EX
Blog — PlanetScale
Blog — PlanetScale

Kent C. Dodds Blog

Implementing Hybrid Semantic + Lexical Search Simplifying Containers with Cloudflare Sandboxes Migrating to Workspaces and Nx Offloading FFmpeg with Cloudflare Building Semantic Search on my Content Helping YOU ask ME questions with AI How I used Cursor to Migrate Frameworks The Dow's Start on the Covenant Path 2025 in Review The next chapter: EpicAI.pro AI is taking your job How I increased my visibility Launching Epic Web 2023 in Review Stop Being a Junior RSC with Dan Abramov and Joe Savona Live Stream Fixing a Memory Leak in a Production Node.js App 2022 in Review My Car Accident I Migrated from a Postgres Cluster to Distributed SQLite with LiteFS I'm building EpicWeb.dev A review of my time at Remix Remix: The Yang to React's Yin How I help you build better websites Why I Love Remix The State Initializer Pattern How to React ⚛️ Get a catch block error message with TypeScript Building an awesome image loading experience How Remix makes CSS clashes predictable Introducing the new kentcdodds.com How I built a modern website in 2021 How to use React Context effectively Static vs Unit vs Integration vs E2E Testing for Frontend Apps The Testing Trophy and Testing Classifications Array reduce vs chaining vs for loop Don't Solve Problems, Eliminate Them Super Simple Start to Remix Super Simple Start to ESModules in Node.js JavaScript Pass By Value Function Parameters How to write a Constrained Identity Function (CIF) in TypeScript How to optimize your context value How to write a React Component in TypeScript TypeScript Function Syntaxes Listify a JavaScript Array Build vs Buy: Component Libraries edition Using fetch with TypeScript Wrapping React.useState with TypeScript Define function overload types with TypeScript 2020 in Review Business and Engineering alignment Hi, thanks for reaching out to me 👋 useEffect vs useLayoutEffect Super simple start to Firebase functions Super simple start to Netlify functions Super Simple Start to css variables Favor Progress Over Pride in Open Source Testing Implementation Details How getting into Open Source has been awesome for me useState lazy initialization and function updates Use ternaries rather than && in JSX Application State Management with React Use react-error-boundary to handle errors in React JavaScript to Know for React How I structure Express apps What open source project should I contribute to? When I follow TDD AHA Programming 💡 How I Record Educational Videos Should I write a test or fix a bug? Stop mocking fetch Intentional Career Building Improve test error messages of your abstractions Tracing user interactions with React Eliminate an entire category of bugs with a few simple tools Common mistakes with React Testing Library Super Simple Start to React Stop using client-side route redirects The State Reducer Pattern with React Hooks Function forms Replace axios with a simple custom fetch wrapper How to test custom React hooks React Production Performance Monitoring Should I useState or useReducer? Stop using isLoading booleans Make Your Test Fail Make your own DevTools An Argument for Automation Fix the "not wrapped in act(...)" warning Super Simple Start to ESModules in the Browser Implementing a simple state machine library in JavaScript 2010s Decade in Review Why users care about how you write code Don't call a React function component Why your team needs TestingJavaScript.com Inversion of Control Understanding React's key prop How to Enable React Concurrent Mode How to add testing to an existing project Profile a React App for Performance
Why I avoid nesting closures
2019-12-13 · via Kent C. Dodds Blog

Watch "Reduce cognitive load for readers of your code by avoiding nesting of closures" on egghead.io

If I come across code like this:

function getDisplayName({ firstName, lastName }) {
	const upperFirstCharacter = (string) =>
		string.slice(0, 1).toUpperCase() + string.slice(1)

	return `${upperFirstCharacter(firstName)} ${upperFirstCharacter(lastName)}`
}

Chances are, I'll refactor it to this:

const upperFirstCharacter = (string) =>
	string.slice(0, 1).toUpperCase() + string.slice(1)

function getDisplayName({ firstName, lastName }) {
	return `${upperFirstCharacter(firstName)} ${upperFirstCharacter(lastName)}`
}

I tend to put functions as close to the left side of the screen as reasonably possible. By that I mean, I like to reduce nesting of closures. A closure is what is created when a function is created. It allows the function to access all variables defined external to itself. And that's actually the reason I like to avoid nesting closures: So I don't have to think about as many variables when I'm working in a single function.

In our first code sample (where upperFirstCharacter is nested in getDisplayName), it's possible for my function to access the firstName and lastName variables. This means that while I'm working with it, I'm uncertain whether I need to keep their values in mind. In addition to that, I have to consider that it could access module-level definitions as well (imports/variables/functions).

However, when I move it out (in the second example), I don't have to worry about those variables because it's impossible to access them anyway (I'll probably not even give it a moment's notice or thought). The only thing that function can access is what's defined within it as well as what is defined at the module-level (imports/variables/functions).

In this simple example, it's not a big deal because it's such a small function, but in more complex scenarios the cognitive load can be a problem (and sometimes you even have trouble with variable shadowing which can increase cognitive load as well).

There are other arguments for doing this kind of thing as well:

  1. Performance: not having to re-create the closure every time getDisplayName is called. This argument doesn't really hold water in typical scenarios. Unless you're calling that one billions of times then you're probably fine.
  2. Testing: we could export upperFirstCharacter and test it in isolation. In this situation I wouldn't bother and I'd test getDisplayName instead. But sometimes if the code is complicated this can be useful.

In general, I'm interested in reducing the amount of trivial things my brain has to think about so I can reserve my brain space for more important things and that's my biggest argument for avoiding nesting of closures. That said, I'm not religious about it and don't feel super strongly about this. It's just a tendency I have.

Also, sometimes it's just unavoidable because you really need access to those variables. For example:

function addThings(additive, ...numbers) {
	const add = (n) => n + additive
	return numbers.map(add)
}

addThings(3, 1, 2, 3, 4)
// ↳ [4, 5, 6, 7]

In this case we can't move add out of addThings because it depends on the additive parameter. We could extract add and accept an additional argument and sometimes that can be useful for more complicated functions, but like I said, I'm not religious about the "avoid nesting closures" rule so I think this code is simpler the way that it is now and I'll probably leave it as-is.

I've had some conversations about this on twitter that have been interesting and I think the most interesting insight so far has been from a thread where Lily Scott described a side-effect which Jed Fox summed up well in what is now a protected tweet.

So yes, this concept has nuance and there are trade-offs. I think I still prefer extracting things because most of the time my files are only a few hundred lines at most, so pulling something out does not increase the number of things that can depend on it and I also feel like it's easier to think about "what can depend on this thing" than "what can affect this thing." But again, it's too nuanced to make a rule for.

Finding ways to offload thinking of trivial things is one skill that I'm always trying to develop (automation plays a big role in that). I really don't want anyone to make an ESLint rule about this idea (please don't do that), but it's something to think about when you're trying to simplify some complicated code. Try pulling things over to the left of the screen a bit. Good luck!