Scope

Scope decides where variables are visible.

Syntaxfunction f() { let local = 1; }

Scope determines where a variable can be used.

  • Global scope β€” declared outside any function; visible everywhere.
  • Function/block scope β€” declared inside { }; visible only there.

Code inside a function can read outer variables, but the outside cannot see variables declared inside the function.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Keep a helper variable private inside a function so it cannot interfere with global module state.
  • Understand why a loop variable declared with var is shared across all iteration closures.
  • Use a nested function to encapsulate intermediate logic that only makes sense within the outer function.

More examples

Local variable is function-private

Declares tax inside a function, making it inaccessible outside and preventing naming collisions.

Example Β· js
function processOrder() {
  const tax = 0.08; // local to processOrder
  return 100 * (1 + tax);
}
console.log(processOrder()); // 108
// console.log(tax); // ReferenceError

Nested function scope

Shows that an inner function can read variables from its enclosing outer function via the scope chain.

Example Β· js
function outer() {
  const x = 10;
  function inner() {
    const y = 20;
    return x + y; // inner can read outer's x
  }
  return inner();
}
console.log(outer()); // 30

Block scope vs function scope

Contrasts var's function scope (one a across the function) with let's block scope (two separate b variables).

Example Β· js
function demo() {
  var a = "function-scoped";
  let b = "block-scoped";
  if (true) {
    var a = "still the same a";
    let b = "different b";
  }
  console.log(a); // "still the same a"
  console.log(b); // "block-scoped"
}
demo();

Discussion

  • Be the first to comment on this lesson.
Scope β€” JavaScript | SoundsCode