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 —
letandconstinside{ }(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>