Global scope
Learn that variables declared in global scope are accessible everywhere.
What is global scope?
Global scope is the area where variables written at the outermost level live. When you declare a variable outside any function or block, it becomes global and can be accessed from anywhere in the code.
For example, an appName variable declared at the top can be read both inside and outside functions. This makes global variables handy for shared state; but using too many makes the code harder to follow.
The global object (window/globalThis)
In the browser, global scope is tied to the global object. In browsers this object is window; the modern, environment-agnostic name is globalThis.
Variables declared with var at the top level become properties of window: writing var appName = 'Stock'; makes window.appName work too. let and const live in the global scope but are not added to window. Knowing this difference helps when reading old code.
Exercise Use a global variable
Declare a global variable named appName with the value "Stock". Write a function called showApp() that logs appName with console.log from inside. Then call the function.
Show example solution
let appName = "Stock";
function showApp() {
console.log(appName);
}
showApp();
Test yourself
-
Which of these is a global variable?
let counter = 0; function inc() { counter++; }- counter declared at the top, outside any function
- counter declared inside the inc function
- counter declared inside an if block
- counter declared inside a for loop
Show answer
counter declared at the top, outside any function — Correct. counter is global because it is declared in the outer scope.
-
Declare the global variable
let appName = ____;Show answer
let appName = "Stock"; -
Match the scope type to its example
- Global scope
- Declared outside any function
- Function scope
- Declared inside a function
- Block scope
- Declared with let in a block
- Hoisting
- Declaration is lifted up