Course contentsShow
← JavaScript
Lesson 79 of 2,7233. Variables and ScopeFree lesson

Function Scope

Variables declared with var inside a function are only accessible within that function.

Function Scope

What you'll learn: How variables declared with var inside a function stay private to that function.

When you declare a variable with var inside a function, it exists only within that function's boundaries. This is called function scope. The variable is born when the function runs and disappears when the function finishes. Code outside the function cannot see or access it.

Think of a function like a room with walls. Variables declared with var inside that room stay inside — they can't be seen from the hallway (global scope) or from other rooms (other functions).

How It Works

function greet() {
  var message = "Hello!";
  console.log(message); // "Hello!" — works fine
}

greet();
console.log(message); // Error! message is not defined

In this example, message is declared inside greet(). It's accessible everywhere within greet(), but once the function ends, message no longer exists. Trying to access it from outside causes an error.

Multiple Functions, Separate Scopes

Each function gets its own scope:

function sayHello() {
  var greeting = "Hello";
  console.log(greeting); // "Hello"
}

function sayGoodbye() {
  var greeting = "Goodbye";
  console.log(greeting); // "Goodbye"
}

sayHello();
sayGoodbye();

Even though both functions use a variable named greeting, they don't conflict. Each greeting lives in its own function scope — they're completely separate variables.

Why Function Scope Matters

Function scope keeps your variables contained and prevents accidental conflicts. Without it, every variable name would need to be globally unique, making code messy and error-prone.

Key Takeaway: Variables declared with var inside a function are only accessible within that function — they're invisible to the outside world.