JavaScript variable scope: Global, local, and module bindings
Scope in JavaScript determines where code can read or change a variable by name. Global names are available across code in the same environment, while local names are available within their function or block and its nested scopes.
Use the same name outside and inside a function
In the first example, the inner message hides the outer name. This is called shadowing. Reading it returns the inner value without changing the outer one.
const message = 'Outside';
function readInside() {
const message = 'Inside';
return message;
}
console.log(readInside()); // 'Inside'
console.log(message); // 'Outside'
If a function assigns to an outer let without declaring a new variable, the assignment changes that outer variable. Pass information in as arguments and return a result when callers should control changes to shared state.
let total = 5;
function addOne() {
total += 1;
}
addOne();
console.log(total); // 6
Compare let and const with var
let and const are scoped to the block. In this function, the var declaration remains visible after the if block. Uncommenting the final console.log(modern) throws a ReferenceError. Restore the comment afterward. Use let when reassignment is needed and const when it is not.
function checkBlock() {
if (true) {
let modern = 'Block';
var legacy = 'Function';
console.log(modern); // 'Block'
}
console.log(legacy); // 'Function'
// console.log(modern); // ReferenceError
}
checkBlock();
How a closure keeps a local variable accessible
A closure is a function together with the surrounding scope it can access. The returned function can still read and update count after createCounter() has finished. A separate call to createCounter() creates a separate counter.
function createCounter() {
let count = 0;
return () => ++count;
}
const next = createCounter();
console.log(next()); // 1
console.log(next()); // 2
Compare classic scripts with modules
A global name and a global object property are different. On a fresh page, a top-level classic-script var adds a property on globalThis, while top-level let and const remain accessible by name without adding properties. See the global environment rules.
Save this file as script-scope.html in UTF-8, open it, and read the browser console. The first module logs 1 2 3 4, then true false false false. A second module logs undefined because it cannot see the first module’s top-level declaration. See the module environment rules. Run the HTML itself since interactive developer consoles can evaluate declarations differently.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Script scope</title>
</head>
<body>
<script>
var scopeDemoClassic = 1;
let scopeDemoLet = 2;
const scopeDemoConst = 3;
</script>
<script type="module">
var scopeDemoModule = 4;
console.log(scopeDemoClassic, scopeDemoLet, scopeDemoConst, scopeDemoModule); // 1 2 3 4
console.log(
Object.hasOwn(globalThis, 'scopeDemoClassic'),
Object.hasOwn(globalThis, 'scopeDemoLet'),
Object.hasOwn(globalThis, 'scopeDemoConst'),
Object.hasOwn(globalThis, 'scopeDemoModule')
); // true false false false
</script>
<script type="module">
console.log(typeof scopeDemoModule); // undefined
</script>
</body>
</html>
Test scope and lifetime in a complete example
Save the complete counter as scope-example.html and open it. The outer and inner labels differ. Click the increase button twice to reach 2 without changing the outer label. Reset creates a new counter at 0.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Compare global and local scope</title>
</head>
<body>
<h1>Check variable scope</h1>
<button id="increase" type="button">Increase counter</button>
<button id="reset" type="button">Reset</button>
<pre id="output" aria-live="polite"></pre>
<script>
const label = 'Outside';
function labelInside() {
const label = 'Inside';
return label;
}
function createCounter() {
let count = 0;
return () => ++count;
}
let nextCount = createCounter();
let currentCount = 0;
const output = document.querySelector('#output');
function show() {
output.textContent = `Outer label: ${label}\nFunction label: ${labelInside()}\nCounter: ${currentCount}`;
}
document.querySelector('#increase').addEventListener('click', () => {
currentCount = nextCount();
show();
});
document.querySelector('#reset').addEventListener('click', () => {
nextCount = createCounter();
currentCount = 0;
show();
});
show();
</script>
</body>
</html>




