EasyCore JS📖 Theory Question

What are the different types of scope in JavaScript?

💡

Hint

Global, function (local), and block scope — each has different variable rules

Full Answer

JavaScript has three types of scope:

  • Global scope — Variables declared outside any function or block. Accessible everywhere. In browsers, becomes a property of window.
  • Function scope — Variables declared with var inside a function are only accessible inside that function.
  • Block scope — Variables declared with let or const inside {} are scoped to that block.
var globalVar = 'everywhere';

function fn() {
  var funcVar = 'function only';
  if (true) {
    let blockVar = 'block only';
    var leaky = 'leaks to fn scope'; // var ignores blocks!
  }
  console.log(leaky);    // ✓ 'leaks to fn scope'
  console.log(blockVar); // ✗ ReferenceError
}

console.log(funcVar); // ✗ ReferenceError

The scope chain: When a variable isn't found in the current scope, JS looks up to the outer scope — all the way to global. Inner scopes access outer variables; outer scopes cannot access inner.

💡 Prefer const/let over var — they're block-scoped and avoid the leaky behavior of var.

More Core JS Questions

EasyWhat is the difference between var, let, and const?EasyExplain closures with a practical example.EasyWhat is hoisting in JavaScript?EasyExplain the event loop, call stack, and microtask queue.

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint