@FahadM to JavaScriptEnglish • 4 days ago

How do you declare a global variable from inside a JavaScript function?

message-square
0
1
How do you declare a global variable from inside a JavaScript function?
@FahadM to JavaScriptEnglish • 4 days ago

To create or expose a global variable from inside a JavaScript function, assign a property explicitly on globalThis (the standard cross-environment global object in browsers, Node.js, and workers, replacing older environment-specific window or global assumptions) or, in non-strict mode only, assign to an undeclared identifier—though explicitly attaching to globalThis or returning values / passing state is strongly preferred over implicit globals, which throw a ReferenceError in strict mode and ES modules.


1. Assigning Explicitly on globalThis (Recommended Over Implicit Globals)

Writing window.myVar = ... only works in browser main threads, while assigning to an undeclared variable (x = 123) fails with a ReferenceError in strict mode and inside ES modules; globalThis works across browsers, Node.js, and Web Workers when you genuinely need a shared global property:

// Expose a named property on globalThis inside a function
function registerGlobalConfig(key, value) {
  if (typeof key !== "string" || key.trim() === "") {
    throw new TypeError("Expected a non-empty string key.");
  }

  globalThis[key] = value;
  return globalThis[key];
}

// Example usage:
registerGlobalConfig("APP_ENV", "production");
console.log(globalThis.APP_ENV); // "production"
  • Works across environments: globalThis avoids environment-specific window vs. global mismatches.
  • Collision risk: Polluting globalThis with generic names can overwrite built-ins or collide with third-party scripts; use a single namespaced object if needed.

2. Why Implicit Undeclared Assignment Is Discouraged ("use strict" & Modules)

In non-strict script mode, assigning to a variable that was never declared with var, let, or const creates a property on the global object, whereas strict mode ("use strict") and all ES modules (<script type="module"> or .mjs) treat that assignment as a ReferenceError:

// Demonstrates why implicit global assignment breaks in strict mode / modules
function attemptImplicitGlobal() {
  "use strict";

  try {
    // Throws ReferenceError in strict mode and ES modules
    // accidentalGlobal = "oops";
    throw new ReferenceError("Implicit globals are disallowed in strict mode.");
  } catch (error) {
    return error.name;
  }
}

console.log(attemptImplicitGlobal()); // "ReferenceError"
  • Harder to trace: Implicit globals make data flow invisible and cause subtle bugs during refactoring or testing.
  • Not allowed in modules: ES modules are always strict, so undeclared writes always throw.

3. Cleaner Alternatives: Returning Values or Passing a Shared State Object

Instead of creating new global variables dynamically inside functions, return values from functions, pass dependencies/state objects explicitly, or hold shared state inside a dedicated module or closure so functions stay predictable and testable:

// Preferred pattern: return state or update a scoped store instead of mutating globals
function createAppStore(initialState = {}) {
  const state = { ...initialState };

  return {
    set(key, value) {
      state[key] = value;
      return value;
    },
    get(key) {
      return state[key];
    },
    snapshot() {
      return { ...state };
    }
  };
}

const store = createAppStore({ theme: "dark" });
store.set("pageSize", 25);
console.log(store.snapshot()); // { theme: "dark", pageSize: 25 }
  • Easier testing and isolation: Scoped stores or returned values avoid cross-test leakage and hidden side effects.
  • Clearer ownership: Anyone reading the code sees exactly where state is created, read, and updated.

TL;DR: Assign explicitly to globalThis[name] = value when a true cross-environment global is needed from inside a function (avoiding implicit undeclared globals, which throw a ReferenceError in strict mode and ES modules), and prefer returning values or using a scoped state object whenever possible.