Scope
Prerequisites: Functions
Scope is where a variable can be seen and used. A variable declared
with let/const inside a function (or any { } block) is local — it
only exists inside that block, and is invisible outside it.
function setTotal() {
const total = 100;
console.log(total); // works: total is visible here
}
setTotal();
console.log(total); // ReferenceError: total is not defined
Common mistakes
- Expecting a variable declared inside a function to be usable outside
it. If you need the value outside,
returnit and store the result in a variable at the outer level.