Quiz Entry - updated: 2026.07.05
What is the difference between global and local variables in JavaScript?
Global variables, declared outside any function, are visible everywhere; local variables, declared inside a function or block, only exist within it.
Where you declare a variable decides who can see it — this is called its scope.
- A global variable is defined outside all functions and can be read or changed anywhere in the program.
- A local variable is defined inside a function (or a
{ }block) and only exists there; outside, it's as if it never existed.
let global = 2; // global: visible everywhere
function myFunc() {
let local = 1; // local: only inside myFunc
// here, both global and local are accessible
}
// here, global is accessible
// but referring to local throws a ReferenceError — it doesn't exist out here
A dangerous gotcha: if you assign to a variable without let/const, JavaScript doesn't error — it silently creates a global variable instead. This "accidental global" is a classic source of bugs:
function bad() {
oops = 5; // no 'let' — accidentally creates a global!
}
Best practice: always declare with let or const, and reach for const whenever the value shouldn't change. This keeps variables tightly scoped and prevents accidental globals.
Go deeper:
MDN: Closures — how lexical scope works and why an inner function keeps access to its outer variables.