Skip to the content

Lesson 50 of 296

Scope: global, function and block

What you will learn

  • What scope is
  • Global scope, function scope and block scope
  • Lexical scope
  • The scope chain
  • Shadowing
  • Why global variables are a problem
On this page

What is scope?

Scope is the area of the code where a variable can be used. Outside its scope, the variable does not exist and using it gives a ReferenceError.

Scope keeps code safe: variables inside one function cannot be changed by accident from somewhere else.

Global scope

A variable created outside every function and block is global. It can be used anywhere in the file.

const appName = "JobPrep";

function show() {
  console.log(appName);       works
}

Function scope

A variable created inside a function only exists inside that function.

function calculate() {
  const result = 42;
  console.log(result);         works
}
calculate();
console.log(result);           ReferenceError: result is not defined

Every call to the function creates fresh variables.

Block scope

A block is any code inside { }: an if, a loop, or just braces. Variables created with let and const inside a block only exist inside that block.

if (true) {
  const message = "Hi";
  let count = 1;
}
console.log(message);          ReferenceError
for (let i = 0; i < 3; i++) { }
console.log(i);                ReferenceError

var ignores blocks. It is only limited by functions (Lesson 51):

if (true) {
  var old = "visible";
}
console.log(old);              "visible"

Nested scopes and the scope chain

Scopes can be inside other scopes. Code can use variables from its own scope and every scope around it, but not from scopes inside it.

const a = 1;                    global

function outer() {
  const b = 2;                  outer's scope

  function inner() {
    const c = 3;                inner's scope
    console.log(a, b, c);       1 2 3
  }

  inner();
  console.log(c);               ReferenceError
}

When JavaScript looks for a variable, it searches:

  1. The current scope.
  2. The scope around it.
  3. And so on outwards, up to the global scope.
  4. If not found anywhere: ReferenceError.

This path is called the scope chain. It only goes outwards, never inwards.

Lexical scope

Lexical scope means a function's scope is decided by where the function is written in the code, not by where it is called from.

const name = "Global";

function printName() {
  console.log(name);
}

function run() {
  const name = "Inside run";
  printName();
}

run();          "Global"

printName was written at the top level, so it sees the global name. It does not matter that it was called inside run. This idea is the foundation of closures (Lesson 53).

Shadowing

If an inner scope creates a variable with the same name as an outer one, the inner one hides (shadows) the outer one inside that scope.

const level = "global";

function test() {
  const level = "function";
  console.log(level);        "function"
}

test();
console.log(level);          "global"

Shadowing is allowed, but it can confuse readers. Prefer different names.

Why globals are a problem

  • Any code can change them, so bugs are hard to trace.
  • Two scripts can use the same name and overwrite each other.
  • They stay in memory for the whole life of the page.

In the browser, a var or function declaration at the top level of a normal script becomes a property of the global window object. ES modules (Lesson 73) solve this: top-level variables in a module are private to that module.

Common mistakes

  • Using a variable outside the block or function it was created in.
  • Thinking scope depends on where a function is called.
  • Accidentally creating a global by assigning to a name you never declared (in non-strict code, total = 5 without let creates a global). Strict mode and modules turn this into an error.
  • Shadowing a variable and changing the wrong one.

How to say it in an interview

"Scope decides where a variable is accessible. There is global scope, function scope and block scope; let and const are block-scoped, while var is only function-scoped. JavaScript uses lexical scope, meaning a function's access to variables is decided by where it is written, not where it is called. Variable lookup walks outwards along the scope chain to the global scope. I avoid globals and use modules so top-level variables stay private."

Key words

WordMeaning
ScopeWhere a variable can be used
Global scopeAvailable everywhere
Function scopeAvailable only inside one function
Block scopeAvailable only inside one { } block
Lexical scopeScope decided by where code is written
Scope chainThe outward path JavaScript searches for a variable
ShadowingAn inner variable hiding an outer one with the same name

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.