Lesson 6
Scope & purity
Build a practical mental model for scope & purity and use it in working JavaScript.
By the end, you will be able to…
- Explain scope & purity in your own words
- Use scope & purity in a small program
- Recognize and debug a common failure mode
Build the mental model
Scope determines which variables a piece of code can see: global, then function, then block, each nested inside the last. A pure function only reads its parameters and returns a new value, never reaching outside its own scope to change something.
Global scope
Function scope
Syntax and working example
Read the code from inputs to output. Predict what it prints, then run it and change one value.
Why this matters
Pure functions are trivially testable and safe to reuse anywhere, because calling them twice with the same input always gives the same output with zero side effects.
Real-world example
Redux and other state-management libraries require pure 'reducer' functions specifically so state changes stay predictable and testable.
Common mistakes
- Reaching outside a function to mutate a shared variable instead of returning a new value
- Assuming a variable declared inside a block is visible outside it
- Shadowing an outer variable with an inner one of the same name by accident
Try it yourself
Challenge
Rewrite incrementGlobal as a pure function that takes the current count and returns the next one.
Knowledge check
What makes a function 'pure'?
Summary
Prefer pure functions that only depend on their parameters; understand global/function/block scope nesting.