Functions · Lesson 17 of 45
Scope and closures
Who can see a variable, and how a function remembers values.
Scope is where a variable is available. A let or const exists only inside the { } where it was declared, and inside anything nested in it. An inner function can see the outer function's variables, but not the other way round.
const site = "SeaCode" // global
function show() {
const page = "Lessons" // only inside show
if (true) {
const tab = "JS" // only inside this if
console.log(site, page, tab)
}
console.log(typeof tab) // undefined: tab is gone
}
show()Closures
A closure is when a function remembers the variables around it at the moment it was created, even after the outer function has finished. It lets you keep private state nobody outside can touch.
- 1function makeCounter() {
- 2 let count = 0
- 3 return () => {
- 4 count++
- 5 return count
- 6 }
- 7}
- ▶const next = makeCounter()
- 9console.log(next())
- 10console.log(next())
Variables
—
Output
We call makeCounter().
What's the output?
function outer() {
const x = 5
return () => x * 2
}
const f = outer()
console.log(f())What will this code print?
Spot the bug
One line throws a ReferenceError. Which?
Exercise
Write makeMultiplier(n) returning a function that multiplies by n. Print makeMultiplier(3)(7) (21).
Expected output: 21
Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.