Global vs Local Variables in JavaScript Guide

Learn the difference between global and local scope in JavaScript. Understand where variables are visible, how scope works, and how to avoid common scope mistakes.

6 min read

Where a variable is visible in your code is called its scope. Comparing global vs local variables in JavaScript comes down to two main categories: global scope and local scope. Understanding the difference helps you avoid one of the most common beginner bugs: accidentally sharing data between parts of your code that should not be connected.

A global variable is visible everywhere in your program. A local variable is visible only inside the block or function where it was declared.

javascriptjavascript
let globalMessage = "I am visible everywhere";
 
function showMessage() {
  let localMessage = "I am visible only here";
  console.log(globalMessage); // works: global is accessible
  console.log(localMessage);  // works: local is in scope
}
 
showMessage();
console.log(globalMessage); // works
console.log(localMessage);  // ReferenceError: not defined

The variable globalMessage is declared outside any function, so every part of the code can see it. The variable localMessage is declared inside the showMessage function, so it only exists while that function runs. Outside the function, JavaScript throws a ReferenceError.

Global Variables

A variable becomes global when you declare it outside of any function or block, at the top level of your script. Global variables are accessible from any function, any block, and any file that runs after the declaration.

javascriptjavascript
let appName = "Task Manager";
let version = "2.1.0";
 
function printAppInfo() {
  console.log(appName + " v" + version);
}
 
printAppInfo();

Both global variables are used inside the function without being passed as arguments. This works because the function can see everything in the outer scope.

Global variables are convenient for values that truly need to be shared everywhere, like application configuration or shared constants. But they come with a cost: if you have too many global variables in a large program, two different parts of your code might accidentally use the same name and overwrite each other.

Modern JavaScript solves this with modules, which let you export and import variables between files without polluting a shared global namespace.

In browsers, variables declared with var at the top level become properties of the global window object. Variables declared with let or const at the top level are global in scope but do not attach to window. This makes let and const safer for global declarations.

Local Variables

A local variable is declared inside a function or a block. It only exists within that function or block and is destroyed when the function finishes running or the block ends.

javascriptjavascript
function calculateTax(price) {
  let taxRate = 0.08;
  let tax = price * taxRate;
  return tax;
}
 
console.log(calculateTax(100));
console.log(taxRate); // ReferenceError: taxRate is not defined

The variable taxRate only exists while calculateTax is executing. Once the function returns, taxRate is gone. Trying to access it from outside produces a ReferenceError.

Local variables are the default you should aim for. They keep data contained, make functions self-contained, and prevent accidental interference between unrelated parts of your program.

Block Scope vs Function Scope

The kind of local scope you get depends on which keyword you use. Variables declared with let and const have block scope: they exist only inside the nearest set of curly braces. Variables declared with var have function scope: they exist everywhere inside the nearest function.

Scope boundaries with let, const, and var

A let or const variable stays inside its block. A var variable escapes its block and is visible throughout the entire function. This is why modern JavaScript prefers let and const for all local variables.

Here is a concrete example of the difference:

javascriptjavascript
function demoScope() {
  if (true) {
    let blockScoped = "only inside if";
    var functionScoped = "visible everywhere in function";
  }
  console.log(functionScoped); // works
  console.log(blockScoped);    // ReferenceError
}
 
demoScope();

The var variable functionScoped is hoisted to the top of demoScope and visible after the if block. The let variable blockScoped is destroyed when the if block ends. Block scoping is more predictable and catches mistakes that function scoping silently ignores.

Variable Shadowing

When a local variable has the same name as a global variable, the local one takes priority inside its scope. This is called shadowing: the local variable hides the global one from view.

javascriptjavascript
let message = "global";
 
function printMessage() {
  let message = "local";
  console.log(message);
}
 
printMessage();
console.log(message);

The function prints "local" because the inner message variable shadows the outer one. Outside the function, the global message is still "global" because the local variable never affected it. Shadowing can be useful when you want to temporarily reuse a name without changing the outer value, but overusing it makes code harder to follow.

Common Mistakes with Scope

Declaring a variable without let, const, or var creates an accidental global variable. This is one of the most dangerous scope mistakes a beginner can make:

javascriptjavascript
function setScore() {
  score = 100; // no keyword: becomes accidental global
}
 
setScore();
console.log(score); // 100 (leaked out of the function!)

Always use a declaration keyword. In strict mode, which modern JavaScript enables by default, this mistake throws a ReferenceError instead of silently creating a global variable.

Another common mistake is trying to access a block-scoped variable from outside its block. This often happens with loop variables:

javascriptjavascript
for (let i = 0; i < 3; i++) {
  // i exists only here
}
console.log(i); // ReferenceError

The loop variable i is block-scoped to the for loop. It does not exist outside the curly braces. If you need the value after the loop, store it in a variable declared before the loop.

When to Use Global vs Local

Use local variables for almost everything. Declare variables inside the function or block where they are needed. This keeps your data contained and makes each piece of code independent.

Use global variables sparingly, only for values that truly need to be shared across your entire application. Configuration constants, shared error messages, and feature flags are common candidates. Even then, prefer exporting them from a module rather than relying on the global scope.

SituationPrefer
Data used only inside one functionLocal
Loop counters and temporary calculationsLocal
Configuration shared across the appGlobal, as a module export
Feature flags read by multiple filesGlobal, as a module export
javascriptjavascript
// Good: local, contained
function formatPrice(amount) {
  const currencySymbol = "$";
  return currencySymbol + amount.toFixed(2);
}
 
// Acceptable: global constant for app-wide config
const API_BASE_URL = "https://api.example.com";

For more on how to declare variables correctly, see the guide on declaring and using variables. To understand which keyword to pick for scoping, read the var vs let vs const comparison.

Rune AI

Rune AI

Key Insights

  • Global variables are accessible anywhere in your code.
  • Local variables exist only inside the block or function where they are declared.
  • Block scope (let and const) is more contained than function scope (var).
  • Use local variables by default to prevent accidental name collisions.
  • Variable shadowing lets a local variable hide a global one with the same name.
RunePowered by Rune AI

Frequently Asked Questions

What happens if a local and global variable have the same name?

The local variable takes priority within its scope. This is called variable shadowing. The global variable is still accessible outside the local scope but is hidden inside it.

Are global variables bad in JavaScript?

Using too many global variables can cause name collisions and make code harder to debug. Modern JavaScript uses modules and block scoping to avoid the global namespace. Use globals sparingly and only when necessary.

What is the difference between var and let for global variables?

var creates a property on the global window object in browsers. let and const create global variables that are not attached to window, making them slightly safer.

Conclusion

Global variables are visible everywhere in your code. Local variables are visible only inside the block or function where they are declared. Use local variables by default to keep your code contained and predictable. Reserve global variables for values that truly need to be shared across your entire application.