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.
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.
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<!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 yourselfthis
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.
const cart = {
items: 3,
describe() {
return "Cart has " + this.items + " items";
},
};
console.log(cart.describe()); // Output: Cart has 3 itemsvar. It ignores block scope and causes surprises. Use const by default and let when the value must change.- 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.
