Scope is the part of the code where a variable is visible. Code can only use a variable that is in scope.
Global scope
A variable declared outside any function or block is global: every part of the script can use it.
const appName = "Notes"; // global
function show() {
console.log(appName); // → Notes
}
show();
Too many globals make large programs fragile, because any code can change them. Keep variables as local as possible.
Function scope
A variable declared inside a function exists only inside it.
function calculate() {
const secret = 42;
return secret * 2;
}
console.log(calculate()); // → 84
console.log(typeof secret); // → undefined
Block scope
let and const are limited to the nearest { } block (an if, a loop, or a plain block). var ignores blocks, as shown in var and Hoisting.
for (let i = 0; i < 2; i++) {
const message = "round " + i;
console.log(message);
}
console.log(typeof i, typeof message); // → undefined undefined
Lexical scope
JavaScript uses lexical scope: where a function is written decides which variables it can see, not where it is called from. An inner function can read variables of the outer ones around it.
const greeting = "Hello";
function outer() {
const name = "Maya";
function inner() {
console.log(`${greeting}, ${name}`); // sees both
}
inner();
}
outer(); // → Hello, Maya
The scope chain
When JavaScript looks for a variable, it starts in the current scope, then goes outward one level at a time until it finds it or reaches the global scope.
const x = "global";
function a() {
const x = "a's own";
function b() {
console.log(x); // → a's own (the nearest x wins)
}
b();
}
a();
An inner variable with the same name shadows the outer one. It is legal but can confuse readers, so avoid reusing names.
Why it matters
Scope explains many “variable is not defined” errors, and it is the foundation of closures, the next lesson.
Keep scopes small
const. Smaller scopes mean fewer places for bugs to hide.