What is scope?
Scope is the set of rules that decides where a variable can be seen; JavaScript has global scope, module scope, function scope and block scope, and it resolves names lexically, by where code is written.
The scopes
- Global scope: variables visible everywhere. In browsers,
varat the top level of a classic script also becomes a property ofwindow. - Module scope: each ES module has its own top-level scope. Nothing leaks into the global scope unless you export it.
- Function scope: variables declared inside a function (with any keyword) are only visible inside it.
- Block scope:
let,constandclassinside{ }(if, for, plain blocks) are only visible in that block.
The scope chain
When code reads a variable, the engine looks in the current scope, then the enclosing one, and so on outward to the global scope. If it finds nothing it throws a ReferenceError. Inner scopes can read outer variables; outer scopes cannot see inner ones.
Lexical scoping
Scope is decided by where the function is defined, not where it is called. This is what makes closures work.
Shadowing
Declaring a variable with the same name in an inner scope hides the outer one inside that scope.
Good habits
Keep variables in the smallest scope that works, prefer const/let, and use modules instead of globals.
Code example
1const appName = "DevQnA"; // module/global scope23function outer() {4 const role = "admin"; // function scope56 if (true) {7 const temp = "only in this block"; // block scope8 console.log(appName, role, temp); // all visible here9 }1011 function inner() {12 const role = "viewer"; // shadows outer `role`13 console.log(role, appName); // viewer DevQnA14 }15 inner();16 console.log(role); // admin17 console.log(typeof temp); // "undefined" - block variable is gone18}19outer();2021// Lexical scope: decided where the function is written22const x = "global x";23function readX() {24 return x;25}26function caller() {27 const x = "caller x";28 return readX();29}30console.log(caller()); // "global x"
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.