agyanadda@gmail.com

JS Scope

Functions 1 min read Updated Dec 1, 2026 Topic 19 of 38

Scope decides where a variable can be used.

Three kinds

  • Global scope — declared outside all functions; usable everywhere.
  • Function scope — declared inside a function; usable only inside it.
  • Block scope — let and const inside { } (if, for) exist only inside that block.

var ignores block scope, which causes bugs. Another reason to use let and const.

Closures

An inner function remembers the variables of the function it was created in, even after that outer function has finished:

function counter() {
  let count = 0;
  return () => ++count;
}
const next = counter();
next(); // 1
next(); // 2

Keep variables in the smallest scope you need. Fewer global variables means fewer clashes.

Example

Example — Block scope and a closure HTML
<button id="btn">Clicked 0 times</button>
<pre id="out"></pre>

<script>
  const site = 'AgyanAdda'; // global

  if (true) {
    let inside = 'only in this block';
  }
  document.getElementById('out').textContent =
    'site: ' + site + '\ninside: ' + (typeof inside);

  function makeCounter() {
    let count = 0; // private to the closure
    return () => ++count;
  }
  const next = makeCounter();
  document.getElementById('btn').onclick = function () {
    this.textContent = 'Clicked ' + next() + ' times';
  };
</script>

Test Yourself With Exercises

Exercise 1 Multiple Choice

A let variable declared inside an if block can be used:

Exercise 2 True / False

var respects block scope.

Exercise 3 Fill in the Blank

A function that remembers variables from its outer function is called a ___.

Frequently Asked Questions

JavaScript moves declarations to the top of their scope before running. Function declarations can be called before they appear; let and const cannot be used before their line.