🟒 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