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, var at the top level of a classic script also becomes a property of window.
  • 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, const and class inside { } (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

js
1const appName = "DevQnA"; // module/global scope
2
3function outer() {
4 const role = "admin"; // function scope
5
6 if (true) {
7 const temp = "only in this block"; // block scope
8 console.log(appName, role, temp); // all visible here
9 }
10
11 function inner() {
12 const role = "viewer"; // shadows outer `role`
13 console.log(role, appName); // viewer DevQnA
14 }
15 inner();
16 console.log(role); // admin
17 console.log(typeof temp); // "undefined" - block variable is gone
18}
19outer();
20
21// Lexical scope: decided where the function is written
22const 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.

Open in study app