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.

JavaScriptbeginner
10 min read

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:

javascriptjavascript
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 defined

Global Scope

Variables declared outside any function or block are in the global scope. They are accessible from anywhere in your code:

javascriptjavascript
// 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:

javascriptjavascript
// 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

javascriptjavascript
// 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 behavior

Function Scope

Variables declared inside a function are only accessible within that function. This applies to var, let, and const:

javascriptjavascript
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:

javascriptjavascript
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:

javascriptjavascript
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 { }:

javascriptjavascript
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:

javascriptjavascript
// 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

javascriptjavascript
// 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)
KeywordScope typeRe-assignableRe-declarableHoisted
varFunctionYesYesYes (initialized as undefined)
letBlockYesNoYes (temporal dead zone)
constBlockNoNoYes (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:

javascriptjavascript
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

CodeCode
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:

javascriptjavascript
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:

javascriptjavascript
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:

javascriptjavascript
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:

javascriptjavascript
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:

javascriptjavascript
// 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:

javascriptjavascript
const MyModule = (function () {
  const privateVar = "secret";
  return {
    getPrivate: () => privateVar,
  };
})();

Practical Scope Patterns

Limiting Variable Lifetime

javascriptjavascript
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

javascriptjavascript
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

javascriptjavascript
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

javascriptjavascript
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

javascriptjavascript
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:

javascriptjavascript
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 typeCreated byAccessible from
GlobalTop-level declarationsEverywhere
FunctionFunction bodyInside that function and nested functions
Block{ } with let/constInside that block only
ModuleES module fileInside the module (unless exported)
ClosureReturned inner functionThe inner function, even after outer returns
Rune AI

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
RunePowered by Rune AI

Frequently Asked Questions

What is the difference between scope and context?

Scope determines which variables a function can access based on where it is defined. Context refers to the value of `this` inside a function, which depends on how the function is called. They are independent concepts.

Why does var leak out of blocks but not functions?

`var` was designed before block scope existed in JavaScript. It is function-scoped by specification. `let` and `const` (ES6) introduced true block scope. This is one of the main reasons developers prefer `let` and `const` over `var`.

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?

If the variable is declared with `let` or `const` inside the loop body, it is only accessible inside that block. If it is declared with `var`, it is accessible anywhere in the containing function. If it is declared outside the loop, it is accessible both inside and outside the loop.

How does [strict mode](/tutorials/programming-languages/javascript/javascript-strict-mode-use-strict-explained) affect scope?

Strict mode (`"use strict"`) prevents accidental global variable creation. Without strict mode, assigning to an undeclared variable creates a global. With strict mode, it throws a `ReferenceError`.

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.