Global vs Local Variables in JavaScript Guide
Understand the difference between global and local variables in JavaScript. Learn how scope works with var, let, and const, why global variables cause problems, and how to structure your code for clean, predictable variable access.
Every variable in JavaScript exists within a scope: the region of your code where that variable can be accessed. Understanding scope is what separates code that works predictably from code that produces mysterious bugs where values change when you did not expect them to, or variables come back as undefined when you were sure you defined them.
Think of scope like rooms in a building. A variable declared inside a specific room (a function or block) is local: only the people inside that room can see and use it. A variable declared in the main hallway (outside all rooms) is global: anyone in any room can see and use it. The problem with hallway variables is that anyone can change them, and when something goes wrong, you have to check every room to figure out who changed the value.
This guide explains how global and local scope work in JavaScript, why global variables cause real problems in real codebases, and how to structure your code so that variables live in the smallest scope they need.
What Are Global Variables?
A global variable is declared outside of any function, block, or module. It is accessible from anywhere in your code.
// Global variables: declared at the top level of a script
const APP_NAME = "TaskManager";
let totalUsers = 0;
function registerUser(name) {
totalUsers += 1; // Can access and modify the global variable
console.log(`${name} registered. Total users: ${totalUsers}`);
}
function displayStats() {
// Can also access the same global variable
console.log(`${APP_NAME} has ${totalUsers} registered users`);
}
registerUser("Alice"); // "Alice registered. Total users: 1"
registerUser("Bob"); // "Bob registered. Total users: 2"
displayStats(); // "TaskManager has 2 registered users"In a browser, global variables declared with var (or without any keyword) become properties of the window object:
var legacyGlobal = "I'm on window";
console.log(window.legacyGlobal); // "I'm on window"
// let and const do NOT attach to window
let modernGlobal = "I'm NOT on window";
console.log(window.modernGlobal); // undefinedWhat Are Local Variables?
A local variable is declared inside a function or block and exists only within that scope. Code outside the function or block cannot access it.
Function-Scoped Local Variables
function calculateAreaOfCircle(radius) {
// 'area' is local to this function
const pi = 3.14159;
const area = pi * radius * radius;
return area;
}
const result = calculateAreaOfCircle(5);
console.log(result); // 78.53975
// console.log(area); // ReferenceError: area is not defined
// console.log(pi); // ReferenceError: pi is not defined
// Both variables exist only inside calculateAreaOfCircleBlock-Scoped Local Variables (let and const)
With let and const, any pair of curly braces {} creates a new scope:
const score = 85;
if (score >= 70) {
const grade = "Pass"; // Block-scoped: exists only inside this if-block
let message = "Well done!"; // Block-scoped: same as grade
console.log(`${grade}: ${message}`); // "Pass: Well done!"
}
// console.log(grade); // ReferenceError: grade is not defined
// console.log(message); // ReferenceError: message is not defined// Loop variables with let are scoped to the loop block
for (let i = 0; i < 3; i++) {
console.log(`Iteration ${i}`);
}
// console.log(i); // ReferenceError: i is not defined
// i does not exist outside the for loopHow var, let, and const Affect Scope
The keyword you use to declare a variable directly determines its scope behavior.
| Keyword | Scope Type | Leaks Out of Blocks? | Leaks Out of Functions? |
|---|---|---|---|
var | Function scope | Yes | No |
let | Block scope | No | No |
const | Block scope | No | No |
function demonstrateScope() {
if (true) {
var funcScoped = "I leak out of blocks"; // function-scoped
let blockScoped = "I stay in this block"; // block-scoped
const alsoBlock = "I also stay here"; // block-scoped
}
console.log(funcScoped); // "I leak out of blocks" (var leaks!)
// console.log(blockScoped); // ReferenceError
// console.log(alsoBlock); // ReferenceError
}
demonstrateScope();var Ignores Block Boundaries
This is one of the most common sources of bugs in JavaScript. A var variable declared inside an if, for, or while block is accessible outside that block. This is why modern JavaScript uses let and const exclusively.
The Scope Chain: How JavaScript Looks Up Variables
When your code references a variable, JavaScript searches for it starting from the current scope and moving outward through parent scopes until it reaches the global scope. This is called the scope chain.
const globalMessage = "I'm global";
function outer() {
const outerMessage = "I'm in outer";
function inner() {
const innerMessage = "I'm in inner";
// inner can see all three variables:
console.log(innerMessage); // "I'm in inner" (own scope)
console.log(outerMessage); // "I'm in outer" (parent scope)
console.log(globalMessage); // "I'm global" (global scope)
}
inner();
// outer can see its own + global, but NOT inner's variables:
// console.log(innerMessage); // ReferenceError
}
outer();Think of it like a one-way mirror: inner functions can look outward and see variables in their parent scopes, but outer scopes cannot look inward.
// Practical example: scope chain in a real scenario
const TAX_RATE = 0.08; // Global constant
function processInvoice(items) {
const subtotal = items.reduce((sum, item) => sum + item.price, 0);
function calculateWithTax() {
// This function can access 'subtotal' (parent scope)
// and 'TAX_RATE' (global scope)
return subtotal + (subtotal * TAX_RATE);
}
function formatCurrency(amount) {
return `$${amount.toFixed(2)}`;
}
const total = calculateWithTax();
return formatCurrency(total);
}
const invoice = processInvoice([
{ name: "Widget", price: 25.00 },
{ name: "Gadget", price: 49.99 }
]);
console.log(invoice); // "$80.99"Why Global Variables Are Problematic
While global variables are sometimes necessary (application configuration, constants), excessive use of globals creates several real problems.
Problem 1: Name Collisions
// file: analytics.js
var count = 0; // Global!
function trackPageView() {
count += 1;
}
// file: cart.js (loaded after analytics.js)
var count = 0; // This OVERWRITES the analytics count!
function addToCart(item) {
count += 1; // Meant for cart items, but shares the same global 'count'
}
// Now analytics.trackPageView() and cart.addToCart() fight over 'count'Problem 2: Unpredictable Mutations
let userData = { name: "Alice", role: "user" };
// Any function in any file can change userData
function promoteUser() {
userData.role = "admin";
}
function resetUser() {
userData = null; // Completely replaces the global variable
}
// If promoteUser and resetUser run in unexpected order,
// other code that reads userData will breakProblem 3: Memory Leaks
// Global variables persist for the entire lifetime of the page
var eventLog = []; // This array will NEVER be garbage collected
function logEvent(event) {
eventLog.push({
type: event.type,
timestamp: Date.now(),
target: event.target.outerHTML // Stores large HTML strings
});
}
// After hours of use, eventLog could consume hundreds of MB
// The garbage collector cannot reclaim this memory because
// the global variable keeps a reference alive| Problem | Global Variables | Local Variables |
|---|---|---|
| Name collisions | High risk (shared namespace) | No risk (isolated scope) |
| Unexpected mutations | Any code can change the value | Only the owning function can change it |
| Memory management | Never garbage collected | Collected when function returns |
| Testing | Hard to isolate (shared state) | Easy to test (pass inputs, check outputs) |
| Debugging | Must search entire codebase | Search only the function |
Strategies for Minimizing Global Variables
Strategy 1: Use Local Variables and Return Values
// BAD: using globals to pass data between functions
let processedData; // Global state
function fetchData() {
processedData = { users: 100, revenue: 5000 };
}
function displayData() {
console.log(processedData.users); // Depends on fetchData running first
}
// GOOD: use parameters and return values
function fetchData() {
return { users: 100, revenue: 5000 };
}
function displayData(data) {
console.log(data.users); // Explicit dependency, no globals
}
const data = fetchData();
displayData(data);Strategy 2: Use Modules (ES Modules)
// userService.js
let users = []; // Module-scoped, not global
export function addUser(user) {
users.push(user);
}
export function getUsers() {
return [...users]; // Return a copy, not the original
}
// app.js
import { addUser, getUsers } from "./userService.js";
addUser({ name: "Alice" });
console.log(getUsers()); // [{ name: "Alice" }]
// 'users' array is NOT accessible directly from app.jsStrategy 3: Wrap Code in Functions or IIFEs
// IIFE (Immediately Invoked Function Expression)
// Creates a private scope without polluting global namespace
(function() {
const apiKey = "sk_live_abc123"; // Not global!
const cache = new Map();
function fetchWithCache(url) {
if (cache.has(url)) return cache.get(url);
const result = `Data from ${url}`; // Simplified for example
cache.set(url, result);
return result;
}
// Only expose what needs to be public
window.myApp = { fetchWithCache };
})();
// apiKey and cache are inaccessible from outside
// console.log(apiKey); // ReferenceErrorBest Practices
Use const and let instead of var for block scoping. Block scope keeps variables contained to the smallest possible area, reducing the chance of accidental access or modification from unrelated code.
Declare variables in the narrowest scope possible. If a variable is only used inside a for loop, declare it inside the loop. If it is only used inside one function, declare it inside that function. Never make a variable global just because it is "convenient."
Use ES modules to encapsulate state. Module-scoped variables are not global; they exist only within their module file. Other modules can access them only through explicit export and import statements, which makes dependencies clear and traceable.
Reserve globals for true application-wide constants. Configuration values, feature flags, and mathematical constants are legitimate globals. Mutable state (user data, cart contents, form values) should never be global.
Pass data through function parameters. If two functions need to share data, pass it as a parameter rather than storing it in a global variable. This makes each function's dependencies explicit and testable.
Common Mistakes and How to Avoid Them
These Scope Mistakes Cause Hard-to-Find Bugs
Variable scope bugs are especially tricky because the code may appear to work in testing but fail in production under different conditions.
Forgetting to use a keyword and creating accidental globals. Writing count = 5; without let, const, or var creates an implicit global variable (in non-strict mode). Always use strict mode ("use strict";) to catch this as an error.
Using var in loops and getting unexpected behavior. Because var is function-scoped, loop variables declared with var share the same binding across all iterations. This causes the classic closure-in-a-loop bug where all callbacks reference the final value.
// Bug: var shares the same 'i' across all iterations
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Output: 3, 3, 3 (not 0, 1, 2!)
// Fix: let creates a new 'i' for each iteration
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Output: 0, 1, 2Modifying global state from multiple functions without coordination. When several functions read and write the same global variable, the order of execution determines the result. This creates race conditions that are nearly impossible to reproduce and debug.
Shadowing variables unintentionally. Declaring a local variable with the same name as an outer variable hides ("shadows") the outer one. This can lead to confusion when the outer variable's value does not change as expected.
Next Steps
Compare var, let, and const in detail
Read the complete comparison of var vs let vs const to understand hoisting, the temporal dead zone, and why let and const are the modern standard.
Learn about closures
Closures are a direct consequence of scope. Understanding how inner functions capture variables from outer scopes is key to mastering JavaScript.
Explore [JavaScript functions](/tutorials/programming-languages/javascript/what-is-a-function-in-javascript-beginner-guide) in depth
Functions create scope boundaries. Learn how JavaScript functions work from basic declarations to advanced patterns like closures and higher-order functions.
Practice with real projects
Build a small application (task tracker, quiz app, expense logger) and challenge yourself to use zero global variables. Pass all data through function parameters and return values.
Rune AI
Key Insights
- Scope determines access: Global variables are accessible everywhere; local variables exist only within their function or block
- let and const provide block scope: Unlike
var, they do not leak out ofif,for, orwhileblocks - Global dangers: Name collisions, untracked mutations, memory leaks, and testing difficulty all stem from excessive global state
- Minimize globals: Use ES modules, function parameters, and return values instead of shared mutable global variables
- Scope chain: JavaScript searches from the current scope outward through parent scopes to find variables, which is why inner functions can access outer variables but not vice versa
Frequently Asked Questions
Are global variables always bad in JavaScript?
What is the difference between global scope and module scope?
Can local variables have the same name as global variables?
How do closures relate to local variables?
Why does `var` not respect block scope?
Conclusion
The distinction between global and local variables is fundamental to writing reliable JavaScript. Global variables are visible everywhere, making them convenient but dangerous because any code can modify them unexpectedly. Local variables are contained to their scope, making code predictable, testable, and free from name collisions. Choosing let and const over var, leveraging ES modules, and passing data through function parameters instead of globals are the practices that separate maintainable code from brittle code.
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.