Local and global variables
A variable's scope decides where in your code it can be seen and used. A global variable is declared outside any function or block and can be reached from anywhere in the script. A local variable is declared inside a function or a block and exists only there. Understanding the difference explains why a variable is sometimes "not defined" and helps you avoid bugs caused by code accidentally changing shared values.
Global scope, function scope and block scope
JavaScript has three main levels of scope:
- Global scope: variables declared at the top level of a script. Every function can read them.
- Function scope: variables declared inside a function, including its parameters. They are created each time the function runs and disappear when it finishes.
- Block scope: variables declared with
letorconstinside curly braces, such as anifblock or aforloop. They exist only inside those braces.
const siteName = 'Shop'; // global
function checkout(cart) {
let total = 0; // local to checkout
for (const item of cart) { // item exists only inside the loop
total += item.price;
}
if (total > 1000) {
const discount = 100; // exists only in this if block
total -= discount;
}
console.log(siteName, total); // inner code can read globals
return total;
}
checkout([{ price: 700 }, { price: 600 }]); // logs "Shop 1200"
console.log(typeof total); // "undefined": not visible here
How JavaScript looks up a name
When code uses a variable, JavaScript first looks in the current scope. If the name is not there, it checks the enclosing scope, then the next one out, all the way to the global scope. This chain is based on where the code is written, which is why it is called lexical scope. Inner scopes can see outer variables, but outer scopes can never see inside inner ones.
Shadowing: same name, different variable
If you declare a local variable with the same name as a global one, the local one "shadows" it inside that function. Changes to the local copy do not affect the global, which can be helpful or confusing depending on whether you meant it.
let count = 10;
function reset() {
let count = 0; // a new local variable, shadows the global
count++;
return count; // 1
}
reset();
console.log(count); // still 10
var behaves differently
The older var keyword ignores block scope. A var declared inside an if or for block is visible throughout the whole function. At the top level of a classic script, var also becomes a property of the global window object, while let and const do not. That leaky behaviour is the main reason modern code uses let and const.
The accidental global
A classic bug is assigning to a variable without declaring it: writing total = 0 instead of let total = 0 inside a function. In non-strict scripts, JavaScript silently creates a global variable called total. Another function using the same name can then overwrite it, and the bug shows up far from its cause. Strict mode, which is on automatically in ES modules and classes, turns this into a ReferenceError so you notice immediately.
Why fewer globals is better
- Any code, including third-party scripts, can change a global, so its value is hard to trust.
- Two scripts using the same global name can clash and break each other.
- Functions that rely only on their parameters and local variables are easier to test and reuse.
Keep variables in the smallest scope that works, declare every variable with const or let, and pass data into functions through parameters rather than sharing globals. Global constants that never change, such as configuration values, are generally fine.
Closures, which build on this exact lookup rule, let a function remember local variables even after its outer function has returned. They come up soon as you learn that functions are objects in JavaScript.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.