← Learning Hub
Intermediate

Scope, Closures and this

Scope decides where a variable can be used. let and const live only inside the { } block where they are made.

Scope is about visibility: which parts of your code can see which variables. It protects you from accidents - a variable named total inside one function doesn't clash with a different total somewhere else. Keeping variables in the smallest scope that works makes code safer and easier to understand.

Example
const shop = "Terixto";          // global: usable everywhere

function greet() {
  const msg = "Welcome";         // only inside greet
  if (true) {
    let inside = "!";            // only inside this if-block
    console.log(msg + " to " + shop + inside);
  }
  // console.log(inside);  -> ReferenceError: inside is not defined
}
greet();   // Output: Welcome to Terixto!

Closures

A function remembers the variables around it, even after the outer function has finished. This is called a closure. It is a neat way to keep private data.

Closures are behind many everyday patterns: event handlers that remember which product they belong to, counters, and functions that "configure" other functions. If a function seems to remember a value after the outer function has finished, that's a closure at work.

Example
function makeCounter() {
  let count = 0;                 // private: nobody else can change it
  return function () {
    count = count + 1;
    return count;
  };
}

const next = makeCounter();
console.log(next());   // Output: 1
console.log(next());   // Output: 2
console.log(next());   // Output: 3
Example
<!DOCTYPE html>
<html>
  <body>
    <pre id="out"></pre>
    <script>
      function show(...values) {
        document.getElementById("out").textContent += values.join(" ") + "\n";
      }
      function makeDiscount(percent) {
        return price => price - price * percent / 100;
      }
      const diwaliSale = makeDiscount(20);
      const clearance  = makeDiscount(50);
      show("Diwali price of ₹1000:", diwaliSale(1000));
      show("Clearance price of ₹1000:", clearance(1000));
    </script>
  </body>
</html>
▶ Try it yourself

this

Inside an object's method, this means the object itself. Arrow functions do not have their own this; they use the one from outside. So write object methods as normal functions.

Example
const cart = {
  items: 3,
  describe() {
    return "Cart has " + this.items + " items";
  },
};
console.log(cart.describe());   // Output: Cart has 3 items
Avoid var. It ignores block scope and causes surprises. Use const by default and let when the value must change.
Key points
  • let and const are block-scoped.
  • A closure is a function that remembers its surrounding variables.
  • this in a method is the object; arrow functions use the outer this.

📝 Test yourself

1. Where can a let variable made inside an if-block be used?
2. What is a closure?
3. Fill in the keyword that is block-scoped and cannot be reassigned:
rate = 18;