CodeZettaInterview Hub

JavaScript · Scope · Fresh / Intern · Concept

What are global, function, and block scope in JavaScript?

Short Interview Answer

Global is top-level; function scope wraps `var`/params; block scope (`{}`) applies to `let`, `const`, and class bindings.

Detailed Explanation

Global scope is the outermost environment — browsers expose it via `window`/`globalThis` for classic scripts. Function scope means `var` declarations and function declarations inside a function are visible throughout that function, ignoring inner blocks. Block scope, introduced widely with ES6, means `let`, `const`, and class declarations are confined to the nearest enclosing `{}` (including `if`, `for`, `while`, and bare blocks). Modules have their own top-level scope that does not leak to `globalThis`. Choosing the right declaration keyword is the practical way to control scope.

Example

function demo(x) {
  if (true) {
    var a = 1;
    let b = 2;
  }
  console.log(a); // 1
  console.log(b); // ReferenceError
}

Interview Tip

Give a one-line contrast: '`var` is function-scoped; `let`/`const` are block-scoped.'

Common Mistake

Saying JavaScript has only function scope — that was largely true pre-ES6 for `var`, not for modern JS.

Did you know this answer?