Scope decides where a name can be used. JavaScript has function scope and block scope; names declared with let or const exist only inside their surrounding brace block.
Local variables and parameters
Function parameters and variables declared inside a function belong to that call. Another function can use the same names without referring to the same variables.
function swap(a, b) {
const temporary = a;
a = b;
b = temporary;
console.log(a, b);
}
let a = 3;
let b = 8;
swap(a, b); // prints 8 3 inside the function
console.log(a, b); // still 3 8 outsideNumbers are passed by value, so swapping local parameters does not change the outer variables.
Two rooms, two pairs of boxes
Unlock the complete interactive lab, deeper explanations, and curated reference answers.
KNOWLEDGE QUIZ
Block scope and outer variables
A name declared with let or const inside an if, for, or standalone brace block cannot be accessed after that block. A variable declared outside all functions has module or global scope and can be read by several functions. Shared mutable state can make a program harder to follow, so keep it limited.
let score = 0;
function addScore(points) {
score += points;
}
function getScore() {
return score;
}
addScore(10);
console.log(getScore()); // 10KNOWLEDGE QUIZ
Build a shared scoreboard
Store a score in one outer variable and use two focused functions to update and read it.
- Declare let score = 0 outside the functions.
- Write addScore(points).
- Write getScore() and verify the result in top-level code.