Scope and Variables

Variable Scope Explained: Global, Local and Block

By ScopedBits Editorial Team · · 4 min read

Scope is the part of a program where a name can be used. When you create a variable, the language decides where in the code that variable is visible, and where it is not. Mistakes with scope cause some of the most confusing bugs beginners meet: a value that is unexpectedly empty, a change that does not stick, or a name that suddenly refers to something else.

The rules vary between languages, but the main ideas are shared. This article explains global, local and block scope, then covers shadowing and closures, using short examples in Python and JavaScript.

Global scope

A global variable is declared at the top level of a file or program, outside any function. Code almost anywhere can read it.

greeting = "Hello"

def welcome(name):
    return f"{greeting}, {name}"

The function reads greeting even though it was not passed in. That convenience is also the danger. Any part of the program can depend on a global, and in many languages any part can change it. When a bug appears, you may have to search the whole program for the culprit. For that reason, globals are best kept for true constants, such as configuration values that never change.

Local scope

A local variable is created inside a function and exists only while that function runs. Code outside cannot see it.

def total_price(prices):
    total = 0
    for price in prices:
        total += price
    return total

print(total)   # error: name 'total' is not defined

Local scope is what makes functions independent. You can reuse a name like total in a hundred functions without them interfering. Prefer local variables whenever possible, and pass data in through parameters and out through return values.

Block scope

Some languages limit a variable to the block, that is the pair of braces, where it is declared. Modern JavaScript is a good example, with let and const being block scoped.

if (true) {
  let message = "inside";
  const limit = 3;
}
console.log(message); // ReferenceError

The older var keyword in JavaScript does not respect blocks. It is scoped to the whole function, which led to many surprises, and most current code avoids it. Python is different again: it has no block scope for if, for and while. A variable assigned inside a loop remains visible after the loop ends, in the same function.

for i in range(3):
    last = i
print(i, last)   # works: prints 2 2

Know which model your language uses, since assumptions carried over from another language are a frequent cause of bugs.

Name lookup: the scope chain

When code uses a name, the language searches outward, starting with the innermost scope. Python describes this as the LEGB rule: Local, Enclosing function, Global, then Built-in. JavaScript follows a similar chain of nested scopes. The first match wins, and if nothing is found, you get an error.

Shadowing

Shadowing happens when an inner scope declares a name that already exists in an outer scope. The inner one hides the outer one within its area.

let count = 10;
function demo() {
  let count = 1;     // shadows the outer count
  return count;      // 1
}

Shadowing is legal, but it can mislead a reader, who may think they are changing the outer variable. Avoid reusing names across scopes when it adds confusion. Many linters warn about it.

Changing a global from inside a function

In Python, assigning to a name inside a function creates a new local variable, even if a global has the same name. To change the global, you must declare it.

counter = 0

def increment():
    global counter
    counter += 1

Without the global line, Python raises an error, because it treats counter as local and finds that it was read before assignment. The nonlocal keyword does a similar job for a variable in an enclosing function. Needing either keyword often suggests a design that could be simpler, such as returning a new value or using a small class.

Closures

A closure is a function that remembers the variables from the scope where it was created, even after that scope has finished.

function makeCounter() {
  let count = 0;
  return function () {
    count += 1;
    return count;
  };
}

const next = makeCounter();
next(); // 1
next(); // 2

The inner function keeps access to count, and nothing outside can touch it. Closures give you private state without a class, and they power callbacks, event handlers and many everyday patterns.

A well known trap: in older JavaScript, creating functions in a loop with var made all of them share a single variable. Using let fixes this, because each pass of the loop gets its own binding.

Practical guidelines

  1. Keep variables in the smallest scope that works.
  2. Declare a variable close to where you first use it.
  3. Pass values through parameters instead of reaching for globals.
  4. Use constants for fixed values, and name them in capital letters if your language convention says so.
  5. Avoid reusing the same name for different things in nested scopes.
  6. When a variable has the wrong value, ask which scope it lives in, and who else can modify it.

Frequently Asked Questions

Are global variables always bad?

Not always. Read only constants and well documented configuration are reasonable. The trouble comes from mutable globals that many parts of a program change, because they make behaviour hard to predict and test.

What is the difference between scope and lifetime?

Scope is where a name is visible in the source code. Lifetime is how long the value exists in memory while the program runs. A closure shows the difference: the variable is out of scope for most code, yet it stays alive as long as the closure uses it.

Why does my variable work inside a loop but fail outside?

In a language with block scope, the variable disappears at the closing brace. Declare it before the loop if you need it afterward, then assign to it inside.

Related reading