Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk5 min

JavaScript Global Variables: Scope and Best Practices

Top-level JavaScript declarations behave differently in classic scripts, CommonJS, and ES modules. Learn what becomes a global-object property and how to share code without accidental globals.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

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

A JavaScript name declared at the top level is not always 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 and const create global lexical bindings that do not appear as window.name or globalThis.name. In CommonJS and native ES modules, top-level declarations are module-scoped. For new code, prefer local bindings and explicit module imports and exports; use a global only when you deliberately need host-wide access.

What is a global variable in JavaScript?

“Global” can describe a name available in a global scope, or a property stored on the global object. Those concepts overlap in some contexts but are not interchangeable. A declaration can be globally scoped without making a property such as globalThis.myName.

The exact result depends on how the code is executed: as a classic script, a CommonJS module, or a native ECMAScript module. Browser hosts also expose their own globals, such as browser APIs; those are distinct from application variables you create.

How declaration type and execution mode affect scope

Context or declaration Where the name lives Global-object property?
Top-level var in a classic script Global binding Yes; it is represented as a non-configurable global-object property.
Top-level function declaration in a classic script Global declaration Yes, in the traditional script environment.
Top-level let or const in a classic script Global lexical binding No. It is not exposed as a global-object property.
Top-level declaration in CommonJS or a native ES module Module scope No; it remains within the module unless explicitly exposed.
Undeclared assignment in sloppy-mode code May create an accidental global if no binding resolves the name Potentially yes.
Undeclared assignment in strict-mode code No binding is created No; the assignment throws a ReferenceError.

MDN’s reference on var describes classic-script global declarations, while its guide to grammar and types distinguishes lexical declarations. These distinctions matter when inspecting values through window or globalThis.

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 script example

In a classic script, the following declarations do not have identical property behavior:

var legacyShared = 1;
let scriptBinding = 2;

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

scriptBinding is still available by its identifier in the relevant global lexical environment. Its absence from globalThis does not mean it was not declared globally.

CommonJS and native ES module example

At the top level of either a CommonJS file or a native ES module, declarations belong to that module rather than a shared global namespace:

const moduleValue = 3;

console.log(globalThis.moduleValue); // undefined

In an ES module, share the binding through its explicit interface:

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.
// values.js
export const moduleValue = 3;

// app.js
import { moduleValue } from "./values.js";
console.log(moduleValue);

MDN explains that module features are imported into the scope of a single script rather than made available in global scope in its JavaScript modules guide.

Why avoid accidental globals?

A typo or forgotten declaration can create shared state in sloppy-mode code. For example, assigning total = 4 without a declaration may create a global-object property if no binding named total resolves the assignment. That can collide with another script or silently affect unrelated code.

In strict mode, the same undeclared assignment throws instead of creating an implicit global. Native ES modules are automatically strict; MDN’s strict mode reference documents this behavior. A ReferenceError is usually easier to diagnose than hidden shared state.

Best practices for sharing state

Keep bindings as local as practical

Declare a value inside the smallest function or block that needs it. Narrow scope makes dependencies easier to see and reduces name collisions between components, scripts, or modules.

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.

Use const by default and let for reassignment

Use const when the binding will not be reassigned and let when it must be. const prevents rebinding; it does not make an object immutable:

const settings = { theme: "light" };
settings.theme = "dark"; // allowed: the object can still be changed

// settings = {}; // TypeError: cannot reassign a const binding

Prefer these block-scoped declarations over var in new code where applicable.

Use module imports and exports for shared code

Modules provide an explicit interface: a producer exports what it makes available, and a consumer imports what it uses. This keeps unrelated bindings out of a shared global namespace and makes dependencies visible in the source.

Use strict behavior and linting to catch mistakes

Modules already run in strict mode. For classic scripts, a "use strict"; directive can catch undeclared assignments. ESLint’s no-implicit-globals rule can help identify unintended global declarations or assignments; check its behavior against the project’s script and module configuration.

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

If you truly need a global, make it explicit

Use a project-specific name, document who owns it and how long it should live, and assign it deliberately rather than relying on an undeclared assignment:

globalThis.AppBridge = { version: 1 };

globalThis offers a standard way to refer to the global this value across environments. However, a host may provide a globalThis value that is not simply its global object; account for the runtime you target. See MDN’s globalThis reference.

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

How to check whether a name is a global-object property

  1. Identify the execution context. Determine whether the code runs as a classic browser script, CommonJS, or a native ES module.
  2. Identify the declaration. Check whether the name comes from var, let, const, a function declaration, an import, or an assignment without a declaration.
  3. Check the property deliberately. Use Object.hasOwn(globalThis, "name") to test whether the global object has that own property. In a browser, window.name may also be relevant, but only when browser-specific behavior is what you intend to inspect.
  4. Do not use the property check as a scope test. A global lexical binding can be available by identifier while the corresponding property check returns false.

Common problems and fixes

“My top-level variable is undefined on window”

If it was declared with top-level let or const in a classic script, it is a global lexical binding, not a property on window or globalThis. If the code is a module, its top-level binding is module-scoped. Use the identifier within its scope or export and import it where needed.

“A typo created a value I did not declare”

Look for an assignment to an undeclared name in sloppy-mode code. Declare the intended binding, correct the typo, and enable strict behavior or linting so similar mistakes are caught earlier.

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.

“An undeclared assignment now throws”

That is expected in strict mode, including native ES modules. Declare the variable with const or let, or correct the identifier to the intended existing binding.

“Two scripts overwrite the same global”

Move application state into modules or narrower scopes. If a host integration genuinely requires a global property, use a project-specific namespace and document its ownership rather than publishing many generic names.

Or skip the browser setup

If your JavaScript work also needs website screenshots, ScreenshotNeo offers a one-request screenshot API. It accepts cookie or consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each of those steps can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers report the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for AI agents and other MCP clients.

For a screenshot, use this cURL request; see the ScreenshotNeo documentation for request options:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Learn about ScreenshotNeo or sign up free for 1,000 screenshots a month with no card.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.