Closures — a function keeps the variables it was born with¶
Level: 201 · for anyone who has returned a function from a function
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: A closure keeps the variable, not a copy of its value: a function made before greeting changes sees the new value, and two functions returned by one call share one count, while a second call gets a fresh one.
Keywords: closure, lexical scope
What the finished page will answer¶
- When a function reads a variable that changes after the function is made, which value does it see?
- Do two functions returned from one call share their captured variables, and does a second call create new ones?
- Can any code outside the function reach
count, and how does that privacy compare with a#privatefield? - Does a closure keep a large object alive when the function never uses it, and what do
--expose-gcand aWeakRefshow?
Examples it will need¶
-
closures_counter_js.js— two counters from one factory incremented separately, and a function that sees a variable change after it was made -
closures_shared_scope_js.js— two closures from one call writing and reading the same variable
See also¶
- Closures in loops — the loop where capturing the variable matters most
- Higher-order functions — functions that take and return functions
- Memory leaks — what a closure keeps alive
- Private fields —
#private, the other way to hide state - Rust: What a closure is ↗ — a Rust closure is a struct holding what it captured
- Rust: The
movekeyword ↗ — in Rust you choose whether a closure borrows or moves