Scope
Where variables live and who can see them — the key to avoiding mysterious bugs.
What you will learn
- Tell global and local scope apart
- Understand block scope with let/const
- Avoid common scope mistakes
Global vs local
A variable declared inside a function is local — only that function can see it. A variable declared outside is global — everyone can see it.
<script>
let team = "CodingClave"; // global
function show() {
let role = "Trainer"; // local to show()
document.write(team + " — " + role);
}
show();
// document.write(role); // would ERROR: role is not visible here
</script>team is declared outside any function, so it is global — code anywhere, including inside show(), can read it. role is declared inside show(), so it is local — it exists only while show() runs. That is why the commented-out last line would error: outside the function, role simply does not exist.
Note: Output: CodingClave — Trainer
Note: let and const are also block-scoped — a variable made inside { } (like an if or loop) only exists inside those braces. This prevents many accidental bugs.
Tip: Keep variables as local as possible. Fewer globals means fewer surprises and clashes — a habit of clean, bug-free code.
Q. A variable declared inside a function is:
✍️ Practice
- Create a local variable in a function and confirm it cannot be read outside.
- Show that a
letinside anifblock is not visible outside it.
🏠 Homework
- Write a short note explaining global vs local scope with your own example.