Scope in JavaScript
Scope determines where variables are accessible in your code. It defines the 'visibility' and lifetime of variables – whether you can use a variable in a certain part of the program.
JavaScript has three main types of scope: global, function, and block. The rules changed with ES6 (let and const introduce block scope).
Global Scope
Variables declared outside any function or block are global – accessible everywhere in the code.
Global variables should be used carefully – they can cause conflicts in larger programs.
Function Scope
Variables declared with var inside a function are function-scoped – visible only inside that function.
Block Scope (let and const)
Variables declared with let or const inside {} braces (blocks like if, for, while) are block-scoped – only accessible inside that block.
var does NOT have block scope – it leaks out.
Scope Chain
When looking for a variable, JavaScript checks the current scope first, then the parent scope, up to global.
Quick Quiz
We have reviewed and checked the materials, but errors may still occur. The content is provided for educational purposes only, so use it at your own responsibility and verify with other sources if needed.
✨ Ask Lara — your AI study partner
Unlock personalized learning support. Lara can explain lessons, summarize topics, and answer your study questions — available from the Go plan and above.
Lara helps you learn faster — exclusive to ReadyTools Go, Plus, and Max members.
