Summary - Scope
Build a counter module using global, function and block scope.
Summary - Scope
In this group you learned JavaScript's four scope ideas: global (outermost, accessible everywhere), function (inside a function, closed from outside), block (let/const inside { }) and hoisting (var/function are lifted; let/const stay in the TDZ).
Now you will use them together: you will write a counter module that keeps state with global and function scope, then compare inner and outer variables with shadowing.
Exercise Write a counter module
Declare a global counter with let counter = 0 outside. Write a function called increment() that increases counter by one and returns the new value. Outside, call console.log(increment()) twice.
Show example solution
let counter = 0;
function increment() {
counter = counter + 1;
return counter;
}
console.log(increment());
console.log(increment());
Exercise Compare with shadowing
Declare let counter = 10 outside. Write a snapshot() function that declares let counter = 50 inside, shadowing the outer counter, and returns counter. Outside, first log the inner result with console.log(snapshot()), then log the outer counter with console.log(counter).
Show example solution
let counter = 10;
function snapshot() {
let counter = 50;
return counter;
}
console.log(snapshot());
console.log(counter);
Test yourself
-
Match the scope type
- Global
- Accessible everywhere
- Function
- Only inside the function
- Block
- let/const inside { }
- Hoisting
- var is lifted up
-
Complete the block scope
if (active) { ____ status = 'active'; console.log(status); }Show answer
if (active) { let status = 'active'; console.log(status); }