JavaScript Scope
Scope is where a name can be seen. A name declared in one place may stay hidden from other places.
A local name
Scope is where a name can be seen, and this name lives inside one function. The function reads and logs its own local name.
function showName() {
const name = "Ana";
console.log(name);
}
showName();A global name
city sits at the top level of this script. The function reads the global name and logs it.
const city = "Oslo";
function showCity() {
console.log(city);
}
showCity();
console.log(city);Separate locals
Each function declares its own label here. The two locals hold different values and never mix.
function first() {
const label = "First";
console.log(label);
}
function second() {
const label = "Second";
console.log(label);
}
first();
second();Example
let score = 10;
{
let score = 99;
console.log(score);
}
console.log(score);
function showScore() {
const score = 42;
console.log(score);
}
showScore();
console.log(score);Key points
- Local scope: the inside of a function, where its own names live
- Global scope: the top level of a script, seen by all code in it
- Reading a local name from outside its function raises a ReferenceError.
- Block scope: the inside of a pair of braces, where a let name stays
- Hoisting: declarations rise to the top of their scope before code runs.
- Two functions can hold separate local names that share one spelling.
In this example, the global score starts at 10. A bare block declares its own score at 99 and logs 99 inside the braces. The next line logs the global score, still 10. The showScore function holds a local score at 42 and logs it, and the last line logs the global 10 again.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
Where can a local name inside a function be read?