JavaScriptEasy
What is global scope?
Global scope is the outermost scope: anything declared there can be read from anywhere in the program, which makes it convenient but risky.
How things become global
- Top-level declarations in a classic script (
<script>withouttype="module"). varand function declarations at the top level of a classic script also become properties of the global object (windowin browsers).let/constare global but do not becomewindowproperties.- Assigning to an undeclared variable (
count = 1) in sloppy mode silently creates a global. Strict mode throws instead. - Explicitly:
globalThis.config = {...}.
Modules change the picture
In ES modules (and Node's CommonJS files) each file has its own module scope. Top-level variables are private to the module unless exported. This is why modern code rarely creates globals by accident.
globalThis
A standard way to reach the global object in any environment: window in browsers, self in workers, global in Node.
Why to avoid globals
- Name collisions with other scripts, libraries or browser features.
- Hidden dependencies: any code can change the value, which makes bugs hard to trace.
- Testing: globals leak state between tests.
Prefer modules, pass values as arguments, and keep truly shared state in one well-defined place.
Code example
js
1"use strict";23// globalThis works everywhere (browser, worker, Node)4globalThis.appVersion = "2.1.0";5console.log(appVersion); // readable from anywhere: "2.1.0"67function readVersion() {8 return appVersion; // found by walking up the scope chain9}10console.log(readVersion());1112// Strict mode stops accidental globals13try {14 undeclaredCounter = 1; // ReferenceError in strict mode15} catch (e) {16 console.log(e.name); // ReferenceError17}1819// Shadowing a global inside a function20function useLocal() {21 const appVersion = "local";22 return appVersion;23}24console.log(useLocal(), globalThis.appVersion); // local 2.1.02526delete globalThis.appVersion; // clean up
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.