Scope, closures, and classes
ECMAScript 2026
Scope decides where a name can be used. Closures let functions keep access to names around them. Classes give you a reusable way to create objects that share a structure and behavior.
On this page
What is scope?
Names declared with let or const inside a block are visible in that block and blocks nested inside it. An inner block can use a different variable with the same name. This is called shadowing.
How to try it Open a browser tab, then open Developer Tools → Console. Type the example or paste it into the Console after reviewing it, then run it. Reload before repeating declarations with the same names.
const product = "Pen";
{
const product = "Notebook";
console.log(product);
}
console.log(product);
What to expect Inside the block it prints Notebook; outside it prints Pen.
Keep access to values with a closure
A closure is a function together with access to the scope where it was created. When makeCounter finishes, the function it returns can still read and change count. Each call to makeCounter makes a separate count.
How to try it Open a browser tab, then open Developer Tools → Console. Type the example or paste it into the Console after reviewing it, then run it. Reload before repeating declarations with the same names.
function makeCounter() {
let count = 0;
return function addOne() {
count += 1;
return count;
};
}
const next = makeCounter();
console.log(next(), next());
What to expect It prints 1 and 2. A new counter starts again at 1 on its first call.
Create an object from a class
A class describes how to make related objects. new creates one instance and runs constructor with the supplied arguments. this refers to that instance in the constructor and when its method is called through the instance.
How to try it Open a browser tab, then open Developer Tools → Console. Type the example or paste it into the Console after reviewing it, then run it. Reload before repeating declarations with the same names.
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
total(quantity) {
return this.price * quantity;
}
}
const pen = new Product("Pen", 2500);
console.log(pen.name, pen.total(2));
What to expect The Console shows Pen and 5000. Make another instance with a different price to see that it has its own data.