Front-end and full stack · Chapter 2
Scope, hoisting and closures: how a function remembers
About this chapter
Many JavaScript surprises come from not knowing which names a line of code can see. This chapter explains scope at three sizes, the differences between var, let and const, what hoisting really does and why a name can exist but be unusable, and how a closure holds on to variables once the function that created them has returned. It ends with three patterns you will write and the mistakes that recur.
Who it is for: Front-end and full-stack developers who write JavaScript daily and want to answer closure and hoisting questions with examples instead of definitions.
You will be able to
- Say which names a given line can use, from the file level down to a single block.
- Choose between var, let and const and explain the differences that change behaviour.
- Explain hoisting and the dead zone with a short example.
- Explain a closure and predict what a loop that creates callbacks will print.
- Write a function that runs only once, using a closure.
The key idea: A function carries its surroundings with it. Where a function was written decides which names it can reach, which is why a callback made inside a loop can still see the loop's variable long after the loop has finished.
In this chapter
- The shop this track builds
- Where a name can be seen: scope
- var, let and const
- Hoisting and the dead zone
- Closures: a function that keeps its surroundings
- Three patterns you will write
- Mistakes that recur
Locked: needs a plan
You can read chapter 1 free. Chapter 2 is the next one.
What you can do now, free: re-read chapter 1 and try its problems.
What a plan gives you: all chapters of the track you pick and their checks. Professional, one role is ₹329 a month or ₹2,299 a year. It renews until you cancel, and you can cancel any time. Paid plans open at launch.
Why is this locked?
Chapter 1 of every track is free, so you can see how the track reads. The rest of a track and its checks come with a plan, or open as you pass each chapter's check.
The price is for one period, a month or a year. A plan renews until you cancel.