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

推荐订阅源

C
Check Point Blog
AI
AI
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
U
Unit 42
Vercel News
Vercel News
Stack Overflow Blog
Stack Overflow Blog
P
Proofpoint News Feed
Microsoft Security Blog
Microsoft Security Blog
The GitHub Blog
The GitHub Blog
WordPress大学
WordPress大学
Martin Fowler
Martin Fowler
博客园 - 【当耐特】
B
Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
F
Full Disclosure
Google DeepMind News
Google DeepMind News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Help Net Security
Recorded Future
Recorded Future
N
News and Events Feed by Topic
雷峰网
雷峰网
V
Vulnerabilities – Threatpost
Schneier on Security
Schneier on Security
aimingoo的专栏
aimingoo的专栏
S
Schneier on Security
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
O
OpenAI News
Project Zero
Project Zero
罗磊的独立博客
G
GRAHAM CLULEY
腾讯CDC
P
Privacy International News Feed
V
V2EX
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Hugging Face - Blog
Hugging Face - Blog
爱范儿
爱范儿
H
Heimdal Security Blog
L
LINUX DO - 热门话题
Forbes - Security
Forbes - Security
美团技术团队
MongoDB | Blog
MongoDB | Blog
Security Latest
Security Latest
M
MIT News - Artificial intelligence
T
Tor Project blog
Cisco Talos Blog
Cisco Talos Blog
宝玉的分享
宝玉的分享
T
Threat Research - Cisco Blogs
TaoSecurity Blog
TaoSecurity Blog

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 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 Why I avoid nesting closures 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
JavaScript Pass By Value Function Parameters
2021-03-23 · via Kent C. Dodds Blog

Why doesn't this work?

function getLogger(arg) {
	function logger() {
		console.log(arg)
	}
	return logger
}

let fruit = 'raspberry'
const logFruit = getLogger(fruit)

logFruit() // "raspberry"
fruit = 'peach'
logFruit() // "raspberry" Wait what!? Why is this not "peach"?

So, to talk through what's happening here, I'm creating a variable called fruit and assigning it to a string 'raspberry', then I pass fruit to a function which creates and returns a function called logger which should log the fruit when called. When I call that function, I get a console.log output of 'raspberry' as expected.

But then I reassign fruit to 'peach' and call the logger again. But instead of getting a console.log of the new value of fruit, I get the old value of fruit!

I can side-step this by calling getLogger again to get a new logger:

const logFruit2 = getLogger(fruit)
logFruit2() // "peach" what a relief...

But why can't I just change the value of the variable and get the logger to log the latest value?

The answer is the fact that in JavaScript, when you call a function with arguments, the arguments you're passing are passed by value, not by reference. Let me briefly describe what's going on here:

function getLogger(arg) {
	function logger() {
		console.log(arg)
	}
	return logger
}

// side-note, this could be written like this too
// and it wouldn't make any difference whatsoever:
// const getLogger = arg => () => console.log(arg)
// I just decided to go more verbose to keep it simple

When getLogger is called, the logger function is created. It's a brand new function. When a brand new function is created, it looks around for all the variables it has access to and "closes over" them to form what's called a "closure". This means that so long as this logger function exists, it will have access to the variables in its parent's function and other module-level variables.

So what variables does logger have access to when it's created? Looking at the example again, it'll have access to fruit, getLogger, arg, and logger (itself). Read that list again, because it's critical to why the code works the way it does. Did you notice something? Both fruit and arg are listed, even though they're the exact same value!

Just because two variables are assigned the same value doesn't mean they are the same variable. Here's a simplified example of that concept:

let a = 1
let b = a

console.log(a, b) // 1, 1

a = 2
console.log(a, b) // 2, 1 ‼️

Notice that even though we make b point to the value of variable a, we were able to change the variable a and the value b pointed to is unchanged. This is because we didn't point b to a per se. We pointed b to the value a was pointing to at the time!

I like to think of variables as little arrows that point to places in the computer's memory. So when we say let a = 1, we're saying: "Hey JavaScript engine, I want you to create a place in memory with the value of 1 and then create an arrow (variable) called a that points to that place in memory."

Then when we say: let b = a, we're saying "Hey JavaScript engine, I want you to create an arrow (variable) called b that points to the same place that a points to at the moment."

In the same way, when you call a function, the JavaScript engine creates a new variable for the function arguments. In our case, we called getLogger(fruit) and the JavaScript engine basically did this:

let arg = fruit

So then, when we later do fruit = 'peach', it has no impact on arg because they're completely different variables.

Whether you think of this as a limitation or a feature, the fact is that this is the way it works. If you want to keep two variables up-to-date with each other, there is a way to do that! Well, sorta. The idea is this: instead of changing where the arrows (variables) point, you can change what they're pointing to! For example:

let a = { current: 1 }
let b = a

console.log(a.current, b.current) // 1, 1

a.current = 2
console.log(a.current, b.current) // 2, 2 🎉

In this case, we're not reassigning a, but rather changing the value that a is pointing to. And because b happens to be pointed at the same thing, they both get the update.

So, let's apply this solution to our logger problem:

function getLatestLogger(argRef) {
	function logger() {
		console.log(argRef.current)
	}
	return logger
}

const fruitRef = { current: 'raspberry' }

const latestLogger = getLatestLogger(fruitRef)

latestLogger() // "raspberry"
fruitRef.current = 'peach'
latestLogger() // "peach" 🎉

The Ref suffix is short for "reference" which is to say that the value the variable points to is simply used to reference another value (which in our case is the current property of an object).

Conclusion

There are naturally trade-offs with this, but I'm glad that the JavaScript specification calls for function arguments to be passed by value rather than reference. And the workaround isn't too much trouble when you have the need (which is pretty rare because mutability makes programs harder to understand normally). Hope that helps! Good luck!