Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A JavaScript name can be available at the top level without being a property of the global object. In a classic browser script, top-level var and function declarations create global-object properties, while top-level let, const, and class declarations create global lexical bindings instead. In CommonJS and native ECMAScript modules, top-level declarations are module-scoped. For new code, keep state local, share code with imports and exports, and use globalThis only when you intentionally need a host-wide property.

What is a global variable in JavaScript?

“Global variable” is often used for two related but different things: a binding available in a global scope, and a property stored on the global object. Those are not interchangeable. A top-level let in a classic script is globally scoped, for example, but does not become globalThis.name. The behavior depends on how the code is run: as a classic script, a CommonJS module, or a native ECMAScript module.

In browsers, the global object is commonly accessible through window; in other JavaScript hosts, use globalThis for the standard cross-environment reference. Host behavior can still differ, and a host-provided globalThis value is not guaranteed to be simply its global object. See MDN’s globalThis reference.

How declarations behave at the top level

Code context Top-level declaration Global-object property?
Classic script var Yes. A global var binding is represented as a non-configurable property of the global object.
Classic script function declaration Yes, in the traditional script environment.
Classic script let, const, or class No. These create global lexical bindings, not properties on the global object.
CommonJS module or native ECMAScript module Any top-level declaration No. Declarations stay within the module scope.

These distinctions are documented in MDN’s references for var and JavaScript grammar and types.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Classic browser scripts

In a non-module <script>, top-level var and function declarations can be seen as properties on globalThis (and usually window in a browser). Top-level let and const are still global lexical bindings in that script environment, but reading globalThis.name for them does not retrieve the binding.

// Classic browser script, not <script type="module">
var legacyShared = 1;
let scriptBinding = 2;

console.log(globalThis.legacyShared); // 1
console.log(globalThis.scriptBinding); // undefined

Do not use window as a synonym for every global binding. It is a browser-specific global-object reference, and it will not be present in environments such as Node.js workers or server-side execution.

CommonJS and native ECMAScript modules

Top-level names in CommonJS files and native ES modules belong to their module, not to the global object. This is a useful boundary: another file cannot silently access a module’s local names just because they were declared at the top level. Share a value by exporting it and importing it where needed. MDN notes that module features are imported into the scope of a single script rather than made available in global scope; see JavaScript modules.

// settings.js
export const apiBase = "/api";

// app.js
import { apiBase } from "./settings.js";
console.log(apiBase);

Here apiBase is available in app.js because it is explicitly imported, not because it became global.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

How accidental globals happen

In sloppy-mode code, assigning to a name that has no declared binding can create a property on the global object. A misspelling can therefore leak state across code that was never meant to share it:

// Avoid in sloppy-mode code: no declaration exists
// total = 4;

In strict mode, the same undeclared assignment throws a ReferenceError instead of creating an implicit global. Native ECMAScript modules are automatically strict, as MDN explains in its strict mode reference. Strict mode makes this class of mistake visible; it does not replace declaring variables correctly.

Best practices for variables and shared state

Keep bindings in the narrowest useful scope

Declare a value inside the function or block that uses it when possible. Local state makes dependencies easier to find and reduces collisions with unrelated scripts and libraries.

Declare every binding; choose const or let

Use const when you will not reassign the binding and let when reassignment is required. const prevents rebinding, not mutation of an object held by the binding:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
const settings = { theme: "light" };
settings.theme = "dark"; // allowed: the object was mutated
// settings = {};         // TypeError: the binding cannot be reassigned

Prefer these block-scoped declarations to var in new code. The choice between const and let does not itself determine whether a name is global; execution context does.

Share through module interfaces

Use named exports and imports for application code that needs to communicate across files. This makes the sharing relationship explicit instead of placing state into a namespace visible to unrelated code.

Use strict behavior and linting

Modules are strict automatically. For classic scripts, a "use strict"; directive can make undeclared assignment fail rather than silently creating a global. ESLint’s no-implicit-globals rule can flag global declarations or assignments that may not be intended; check its behavior against the project’s script and module configuration.

If a global is genuinely required, make it explicit

Some host integrations or compatibility layers need a globally reachable value. Give it a project-specific name, document who owns it and how long it should live, and write it explicitly rather than relying on sloppy assignment:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
globalThis.AppBridge = { version: 1 };

This deliberately sets a property on the host’s global-this value. Reserve the pattern for intentional integration, not ordinary application state.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common questions and troubleshooting

Why is my name on window?

Check whether the code runs as a classic script and whether the name was declared with top-level var or as a function declaration. Those declarations traditionally create global-object properties in that context. A top-level let or const in a classic script does not.

Why is a name missing from globalThis?

It may be a global lexical binding rather than a global-object property, or it may be top-level in a module. In either case, it is not expected to appear as globalThis.name. If another module needs the value, export and import it.

Why does undeclared assignment work in one file but fail in another?

The files may execute under different strictness rules. Modules are strict automatically; a classic script without strict mode may allow an undeclared assignment to create an accidental global. Declare the name explicitly rather than depending on that difference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Or skip the browser setup

If your goal is to capture a web page rather than manage a JavaScript global, ScreenshotNeo can return a screenshot or PDF from one GET request. Its API accepts consent banners before capture and removes 60+ known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server offers screenshot and PDF tools for AI agents. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots.

cURL example (see the ScreenshotNeo API documentation):

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Sign up for 1,000 free screenshots a month, with no card required.

Frequently Asked Questions

Does globalThis work in browsers and Node.js?

It is the standardized way to reference the global-this value across JavaScript environments. The host determines what that value represents; browser-only names such as window are not universal.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Is a global lexical binding the same as a global-object property?

No. A global lexical binding can be available to code in a classic script without appearing as a property such as globalThis.name.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.