JavaScript ยท Chapter 41 of 55

JavaScript Scope

Scope determines where a variable is accessible in your code. JavaScript has global scope, function scope, and (with let/const) block scope.

Variables declared inside a function or block are not visible outside it, which helps prevent naming collisions and keeps code modular.

Block scope vs function scope

`let` and `const` are block-scoped โ€” confined to the nearest `{}`. `var` is function-scoped, ignoring block boundaries like if-statements.

Global scope

Variables declared outside any function or block are globally accessible, but polluting global scope is generally considered bad practice.

Example 1 (javascript)
if (true) {
  let x = 10;
  console.log(x);
}
// console.log(x); would throw an error here
Output
10

x is block-scoped and inaccessible outside the if-block.

Example 2 (javascript)
function outer() {
  let msg = "hello";
  function inner() {
    console.log(msg);
  }
  inner();
}
outer();
Output
hello

Inner functions can access variables from their enclosing scope.

Key points

  • let/const are block-scoped; var is function-scoped.
  • Inner scopes can access outer (enclosing) variables.
  • Outer scopes cannot access inner scope variables.
  • Minimizing global variables reduces naming conflicts and bugs.
๐Ÿ’ก Note: Block scoping with let/const is one of the biggest improvements ES6 brought over var.

๐Ÿ“ Quick Quiz

1. Which is block-scoped?

2. Can an inner function access outer variables?

3. Which is function-scoped, not block-scoped?