JavaScript Function Scope: Local vs Global Scope
Learn how scope works in JavaScript functions. Covers global scope, local scope, block scope, lexical scope, scope chain, variable shadowing, closures, and common scoping mistakes with practical examples.
Scope determines where variables are accessible in your code. JavaScript has three main types of scope: global scope (accessible everywhere), function scope (accessible only inside a function), and block scope (accessible only inside a {} block). Understanding scope is essential for avoiding variable conflicts, managing memory, writing secure code, and understanding closures.
What is Scope?
Scope is the area of your program where a variable exists and can be referenced. Think of scope as a set of rules the JavaScript engine uses to look up variables:
const globalVar = "I am global";
function myFunction() {
const localVar = "I am local";
console.log(globalVar); // "I am global" (accessible)
console.log(localVar); // "I am local" (accessible)
}
myFunction();
console.log(globalVar); // "I am global" (accessible)
console.log(localVar); // ReferenceError: localVar is not definedGlobal Scope
Variables declared outside any function or block are in the global scope. They are accessible from anywhere in your code:
// Global scope
const appName = "MyApp";
let userCount = 0;
var apiUrl = "https://api.example.com";
function showApp() {
console.log(appName); // accessible
}
function incrementUsers() {
userCount++; // accessible and modifiable
}
if (true) {
console.log(apiUrl); // accessible
}The Global Object
In browsers, global variables become properties of the window object. In Node.js, they become properties of globalThis:
// Browser
var browserVar = "hello";
console.log(window.browserVar); // "hello"
// let and const do NOT attach to window
let modern = "world";
console.log(window.modern); // undefined
// Implicit globals (no declaration keyword)
function oops() {
leaked = "I am global!"; // no var/let/const
}
oops();
console.log(window.leaked); // "I am global!"Avoid Global Variables
Global variables create naming conflicts, make code harder to test, and increase coupling between unrelated parts of your program. Minimize global variables by using functions, modules, and block scope.
Problems with Global Scope
// File: module-a.js
var counter = 0;
function increment() { counter++; }
// File: module-b.js
var counter = 100; // Overwrites module-a's counter!
function reset() { counter = 0; }
// Both files share the same global scope
// counter conflicts cause unexpected behaviorFunction Scope
Variables declared inside a function are only accessible within that function. This applies to var, let, and const:
function calculateTotal(price, taxRate) {
// All of these are function-scoped
var subtotal = price;
let tax = subtotal * taxRate;
const total = subtotal + tax;
console.log(total); // accessible inside the function
return total;
}
calculateTotal(100, 0.08);
// None of these are accessible outside
console.log(typeof subtotal); // "undefined"
console.log(typeof tax); // "undefined"
console.log(typeof total); // "undefined"Function Parameters are Function-Scoped
Parameters act as local variables:
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Alice"); // "Hello, Alice!"
console.log(typeof name); // "undefined" (not accessible outside)Nested Functions
Inner functions can access outer function variables, but not vice versa:
function outer() {
const outerVar = "I belong to outer";
function inner() {
const innerVar = "I belong to inner";
console.log(outerVar); // "I belong to outer" (accessible)
console.log(innerVar); // "I belong to inner" (accessible)
}
inner();
console.log(outerVar); // "I belong to outer" (accessible)
console.log(typeof innerVar); // "undefined" (NOT accessible)
}
outer();Block Scope
let and const are block-scoped. A block is any code between { }:
if (true) {
let blockLet = "I am block-scoped";
const blockConst = "I am also block-scoped";
var functionVar = "I am function-scoped (leaks out!)";
}
console.log(typeof blockLet); // "undefined"
console.log(typeof blockConst); // "undefined"
console.log(functionVar); // "I am function-scoped (leaks out!)"var vs let/const in Blocks
This is the key difference between var and let/const:
// var: function-scoped (ignores block boundaries)
function varExample() {
if (true) {
var x = 10;
}
console.log(x); // 10 (var leaks out of if block)
}
// let: block-scoped
function letExample() {
if (true) {
let y = 10;
}
console.log(y); // ReferenceError: y is not defined
}Block Scope in Loops
// var: shared across all iterations
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Output: 3, 3, 3 (all share the same i)
// let: unique binding per iteration
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log(j), 100);
}
// Output: 0, 1, 2 (each iteration gets its own j)| Keyword | Scope type | Re-assignable | Re-declarable | Hoisted |
|---|---|---|---|---|
var | Function | Yes | Yes | Yes (initialized as undefined) |
let | Block | Yes | No | Yes (temporal dead zone) |
const | Block | No | No | Yes (temporal dead zone) |
The Scope Chain
When JavaScript encounters a variable, it searches for it starting from the current scope and moving outward through each containing scope until it reaches the global scope:
const global = "global";
function outer() {
const outerVar = "outer";
function middle() {
const middleVar = "middle";
function inner() {
const innerVar = "inner";
// Scope chain: inner -> middle -> outer -> global
console.log(innerVar); // found in inner scope
console.log(middleVar); // found in middle scope
console.log(outerVar); // found in outer scope
console.log(global); // found in global scope
}
inner();
}
middle();
}
outer();Scope Chain Lookup Order
inner scope (innerVar) ✓
↓ not found? look up...
middle scope (middleVar)
↓ not found? look up...
outer scope (outerVar)
↓ not found? look up...
global scope (global)
↓ not found?
ReferenceError!
Lexical Scope
JavaScript uses lexical (static) scope. This means a function's scope is determined by where it is written in the source code, not where it is called:
const x = "global";
function printX() {
console.log(x); // uses the x from where printX was DEFINED
}
function wrapper() {
const x = "wrapper";
printX(); // still prints "global", not "wrapper"
}
wrapper(); // "global"printX was defined in the global scope where x is "global". Even though wrapper has its own x, printX does not see it because lexical scope is based on the code's position, not the call location.
Variable Shadowing
A variable in an inner scope can have the same name as one in an outer scope. The inner variable "shadows" the outer one:
const color = "blue"; // global
function paint() {
const color = "red"; // shadows global color
console.log(color); // "red"
function detail() {
const color = "green"; // shadows paint's color
console.log(color); // "green"
}
detail();
console.log(color); // still "red" (this scope's color)
}
paint();
console.log(color); // "blue" (global is unchanged)Avoid Shadowing When Possible
Variable shadowing makes code harder to read and debug. Use descriptive, unique variable names instead of reusing the same name across scopes.
Intentional Shadowing
Sometimes shadowing is acceptable, especially in short callback functions:
const items = [{ name: "A" }, { name: "B" }, { name: "C" }];
// "item" is a clear, local name for the callback parameter
const names = items.map((item) => item.name);
// Function parameters shadow same-named outer variables
function process(data) {
// "data" clearly refers to the parameter, not anything external
return data.map((item) => item.value);
}Closures and Scope
Closures are a direct consequence of lexical scope. When a function is returned from another function, it retains access to the outer function's scope:
function createCounter() {
let count = 0; // private via closure
return {
increment: () => ++count,
getCount: () => count,
};
}
const counter = createCounter();
counter.increment();
counter.increment();
console.log(counter.getCount()); // 2
console.log(typeof count); // "undefined" (not accessible)For a deep dive into closures and returning functions, see Returning Functions from Functions in JavaScript.
Module Scope
ES modules have their own scope. Variables declared at the top level of a module are not global - they are module-scoped:
// utils.js (ES module)
const SECRET_KEY = "abc123"; // module-scoped, NOT global
export function getKey() {
return SECRET_KEY;
}
// app.js
import { getKey } from "./utils.js";
console.log(getKey()); // "abc123"
console.log(SECRET_KEY); // ReferenceError (not exported)IIFE Scope (Pre-Module Pattern)
Before ES modules, developers used IIFEs to create module-like scope:
const MyModule = (function () {
const privateVar = "secret";
return {
getPrivate: () => privateVar,
};
})();Practical Scope Patterns
Limiting Variable Lifetime
function processOrder(order) {
// discount only exists when needed
{
const discount = calculateDiscount(order);
order = applyDiscount(order, discount);
}
// discount is garbage collected
// tax only exists when needed
{
const tax = calculateTax(order);
order = applyTax(order, tax);
}
// tax is garbage collected
return order;
}Private Variables in Loops
function createButtons(labels) {
const buttons = [];
for (let i = 0; i < labels.length; i++) {
// Each iteration creates a new scope for i
buttons.push({
label: labels[i],
onClick() {
console.log(`Button ${i}: ${labels[i]}`);
},
});
}
return buttons;
}
const btns = createButtons(["Save", "Delete", "Cancel"]);
btns[0].onClick(); // "Button 0: Save"
btns[1].onClick(); // "Button 1: Delete"Common Scope Mistakes
1. Accidental Global Variables
function calculateArea(width, height) {
result = width * height; // MISSING let/const! Creates a global!
return result;
}
// Use strict mode to catch this
"use strict";
function calculateArea(width, height) {
result = width * height; // ReferenceError in strict mode
return result;
}2. Confusing var Hoisting with Scope
function example() {
console.log(x); // undefined (var is hoisted but not initialized)
var x = 10;
console.log(x); // 10
}
function example2() {
console.log(y); // ReferenceError (let is hoisted but in TDZ)
let y = 10;
}3. Modifying Outer Variables Unexpectedly
let total = 0;
function addToTotal(amount) {
total += amount; // Modifies outer variable (side effect!)
}
// Better: return new value, keep function pure
function addToTotal(currentTotal, amount) {
return currentTotal + amount; // no side effects
}Scope and this
Scope and this are different concepts. Scope determines variable access. this determines the execution context:
const obj = {
name: "Alice",
greet() {
// 'this' refers to obj (execution context)
// 'name' from scope would look up the scope chain
console.log(this.name); // "Alice" (via this)
},
};
// Arrow functions inherit 'this' from their lexical scope
const obj2 = {
name: "Bob",
greet: () => {
console.log(this.name); // undefined (arrow uses outer this)
},
greetCorrect() {
const inner = () => {
console.log(this.name); // "Bob" (arrow inherits from greetCorrect)
};
inner();
},
};Quick Reference
| Scope type | Created by | Accessible from |
|---|---|---|
| Global | Top-level declarations | Everywhere |
| Function | Function body | Inside that function and nested functions |
| Block | { } with let/const | Inside that block only |
| Module | ES module file | Inside the module (unless exported) |
| Closure | Returned inner function | The inner function, even after outer returns |
Rune AI
Key Insights
- Three scope types: global, function, and block scope
- let/const are block-scoped: contained within
{}blocks - var is function-scoped: ignores block boundaries, leaks out of
if/for - Scope chain looks outward: inner -> outer -> global, never the reverse
- Lexical scope: functions access variables from where they are defined, not called
- Minimize globals: use modules, functions, and block scope to limit variable access
Frequently Asked Questions
What is the difference between scope and context?
Why does var leak out of blocks but not functions?
Can I access a variable from an [inner loop](/tutorials/programming-languages/javascript/js-for-loop-syntax-a-complete-guide-for-beginners) in the outer function?
How does [strict mode](/tutorials/programming-languages/javascript/javascript-strict-mode-use-strict-explained) affect scope?
Conclusion
JavaScript scope determines where variables are accessible. Global scope makes variables available everywhere but should be minimized. Function scope contains variables within a function. Block scope (with let and const) contains variables within {} blocks. The scope chain searches from innermost to outermost scope when resolving variable names. Lexical scope means a function's access is determined by its position in the code, not where it is called. Use let and const for block scope, avoid var for cleaner scoping, and use modules and closures to encapsulate private state.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.