Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

JS
JavaScript
0/12 completed
Beginner
What is JavaScript?Variables and data typesOperators and expressionsMaking decisions: if and switchLoops
Intermediate
FunctionsArrays and array methodsObjects
Advanced
Scope and closuresClasses and OOPPromises and async/await
Pro
The event loop
Tracks / JavaScript / Advanced

Scope and closures

Scope decides where a variable can be seen. Closures are what happens when a function remembers the variables around it, even after the outer code has finished. Closures power React hooks, event handlers, debouncing, and private data. They're one of the ideas that separate beginners from pros.

Block scope

let and const live only inside the nearest { ... } block.

JavaScript · editable

Function scope and the scope chain

A function can see its own variables, then its parent's, then its grandparent's, all the way out to the global scope. This lookup path is called the scope chain.

JavaScript · editable

Lookups only go outward: outer cannot see lesson.

Closures

When a function is created, it captures a reference to its surrounding variables. If you return that function, it keeps them alive.

JavaScript · editable

makeCounter has finished running, yet count still exists, because the returned function closes over it. Nothing outside can touch count directly. That's data privacy.

Practical closure: function factories

JavaScript · editable

Practical closure: memoization

Caching expensive results is a classic closure use:

JavaScript · editable

The classic loop trap

JavaScript · editable

Practice

Write createBankAccount(initial) that returns an object with deposit(amount), withdraw(amount) and getBalance(). The balance must be private (not a property on the object), and withdrawing more than the balance should return 'Insufficient funds'.

JavaScript · editable
✎ Check your understanding

1.What is a closure?

2.Why does the var loop example print [3, 3, 3]?

← Objects