Sub topic 2
this at the Top Level and globalThis
This chapter assumes you know how to write JavaScript functions and objects, how scope works, and the ES2015+ syntax for let, const, arrow functions, and modules. The previous chapter showed that this is set by how a function is called. This chapter covers code that runs outside any function, where no call site sets this. At the top level, the value of this depends on what kind of program the code belongs to.
Why the top level is a special case
Inside a function, the engine sets this when the function is invoked. Top-level code is never invoked as a function by your program. The host environment evaluates it, and that environment chooses this for you. The host is a browser, Node.js, a worker, or another runtime, and each one evaluates code in one of a few ways:
- A classic script is a file loaded with a plain
<script>tag, or code run by the Node REPL. Its top level shares one global scope with every other classic script. - An ES module is a file loaded with
<script type="module">, a.mjsfile, or a.jsfile in a package with"type": "module". Each module has its own top-level scope. - A CommonJS module is a Node.js file that uses
requireandmodule.exports. Node wraps the file's contents in a function before it runs them.
These three kinds of code give this three different top-level values.
Classic scripts: this is the global object
In a classic script, top-level this is the global object. The global object holds built-ins such as Array, setTimeout, and console. In a browser window it is window.
<!DOCTYPE html>
<html>
<body>
<script>
console.log(this === window); // true
console.log(this === globalThis); // true
</script>
</body>
</html>Strict mode does not change this result. A 'use strict' directive at the top of a classic script changes how plain function calls bind this, which the next chapter covers. It does not touch top-level this, because no function call is involved.
<script>
'use strict';
console.log(this === window); // still true
</script>var, function declarations, and the global object
In a classic script, top-level var declarations and function declarations become properties of the global object. Top-level let, const, and class declarations do not. They go into a separate declarative record that all classic scripts share, and the global object never sees them.
<script>
var viaVar = 1;
let viaLet = 2;
function viaFunction() {}
console.log(this.viaVar); // 1
console.log(this.viaLet); // undefined
console.log(typeof this.viaFunction); // 'function'
</script>So this.someName and someName can disagree in a classic script, depending on how someName was declared. A common legacy pattern reads configuration through this.config or window.config. That pattern breaks quietly when someone changes var config to const config.
ES modules: this is undefined
Module code always runs in strict mode, and the specification sets its top-level this to undefined. This holds in browsers, Node.js, Deno, and Bun.
// main.mjs (run with: node main.mjs)
console.log(this); // undefined
var notGlobal = 'hello';
console.log(globalThis.notGlobal); // undefinedTwo things changed compared with a classic script:
thisisundefined, so code that readsthis.somethingat the top level throws aTypeError.- Top-level
varno longer creates a global property. Each module has its own scope, so no declaration in a module reaches the global object unless you assign it there explicitly.
This trips people up when they move old scripts into a bundler or switch a page to <script type="module">. Code like the following pattern, common in older libraries, stops working:
// Old UMD-style wrapper, written for classic scripts
(function (root) {
root.myLib = { version: '1.0' };
})(this);
// In a module, root is undefined and this line throws:
// TypeError: Cannot set properties of undefined (setting 'myLib')To fix it, pass globalThis instead of this, or better, use export and stop writing to the global object at all.
CommonJS modules: this is module.exports
Node.js runs a CommonJS file by wrapping its source in a function, roughly like this:
(function (exports, require, module, __filename, __dirname) {
// your file's code goes here
});Node then calls that wrapper with this set to module.exports. As a result, top-level this in a CommonJS file is the exports object. It is neither the global object nor undefined.
// counter.cjs (run with: node counter.cjs)
console.log(this === module.exports); // true
console.log(this === exports); // true
console.log(this === globalThis); // false
this.answer = 42;
console.log(module.exports.answer); // 42The link only lasts while module.exports still points at the original object. If you reassign module.exports, this keeps pointing at the old, now-unused object:
// reassign.cjs
module.exports = { fresh: true };
this.lost = 'nobody will see this';
console.log(module.exports.lost); // undefined
console.log(this === module.exports); // falseTop-level var in CommonJS is scoped to the wrapper function, so it does not create a global property either. The Node REPL is different. It evaluates input like a classic script, so this === globalThis is true there. A snippet that behaves one way in the REPL can therefore behave another way once you save it to a file.
Other hosts
Workers have no window. In a Web Worker, the global object is the worker's global scope, which is also reachable as self. A classic worker script sees that object as top-level this. A module worker, created with new Worker(url, { type: 'module' }), sees undefined.
| Environment | Kind of code | Top-level this | Does top-level var create a global property? |
|---|---|---|---|
| Browser `<script>` | Classic script | `window` | Yes |
| Browser `<script type="module">` | ES module | `undefined` | No |
| Node.js `.cjs` or default `.js` | CommonJS | `module.exports` | No |
| Node.js `.mjs` or `"type": "module"` | ES module | `undefined` | No |
| Node.js REPL | Script-like | `globalThis` | Yes |
| Classic Web Worker | Classic script | worker global scope (`self`) | Yes |
| Module Web Worker | ES module | `undefined` | No |
globalThis: one name for the global object
Before ES2020, no single name reached the global object in every environment. Browsers had window and self, Node had global, and workers had only self. Portable libraries had to guess:
// Pre-ES2020 approach, shown for comparison
var getGlobal = function () {
if (typeof self !== 'undefined') return self;
if (typeof window !== 'undefined') return window;
if (typeof global !== 'undefined') return global;
throw new Error('Unable to locate global object');
};Another old trick was Function('return this')(). It creates a sloppy-mode function and calls it plainly, so default binding returns the global object. It fails in pages with a Content Security Policy that blocks eval-like code, which is why the standard eventually added a proper name.
globalThis is that name. It refers to the global object in every modern environment, whatever kind of code you are in:
// Works the same in a classic script, an ES module, CommonJS, or a worker
globalThis.appVersion = '2.3.0';
console.log(globalThis.appVersion); // '2.3.0'
console.log(typeof globalThis.setTimeout); // 'function'Use globalThis whenever you mean "the global object". Use this only when you mean "whatever the current call or context provides". Reading top-level this when you mean the global object only works in classic scripts, and breaks once the code becomes a module.
Arrow functions at the top level
An arrow function has no this of its own. It uses the this of the scope it was written in, a rule covered fully in a later chapter. An arrow written at the top level therefore picks up the top-level this for its kind of code:
// app.mjs
const whoAmI = () => this;
console.log(whoAmI()); // undefined, because module top-level this is undefinedThe same arrow in a classic script returns window, and in a CommonJS file it returns module.exports. Top-level arrows that read this are fragile for this reason. Moving the file between module systems changes what they see.
Edge case: eval
eval runs a string as code, and there are two forms. A direct eval is a call written literally as eval(...). It runs the string in the current scope and inherits the current this. An indirect eval is any other way of calling it, such as (0, eval)(...). It runs the string as global classic-script code, so its this is the global object, even inside a module.
// edge.mjs
console.log(eval('this')); // undefined, direct eval inherits module this
console.log((0, eval)('this') === globalThis); // true, indirect eval runs globallyYou will rarely write either form. They do show up in bundler output and old library code, and they explain occasional reports that this is the global object inside a module.
Diagnosing a surprising top-level this
When a top-level this doesn't match your expectations, work through these checks in order:
- Find out how the file is loaded. Check the
<script>tag fortype="module", the file extension, and the"type"field in the nearestpackage.json. - Check whether a bundler or transpiler rewrote the code. Some tools compile modules to CommonJS, which turns
undefinedintomodule.exports. Others replace top-levelthiswithundefinedon purpose. - Check whether the code really is top-level. Code inside any regular function follows the call-site rules from the rest of this tutorial instead.
- If you meant the global object, replace
thiswithglobalThis.
Exercise
A file contains console.log(this === globalThis) and nothing else. What does it print when it is loaded (a) with a plain script tag, (b) with a script tag that has type="module", and (c) as a CommonJS file run with node?
Show answer
(a) true, because a classic script's top-level this is the global object. (b) false, because a module's top-level this is undefined. (c) false, because a CommonJS file's top-level this is module.exports, not the global object.
Exercise
In a classic browser script, var a = 1; let b = 2; console.log(this.a, this.b); prints what, and why do the two values differ?
Show answer
It prints 1 undefined. Top-level var declarations become properties of the global object, which is this in a classic script. Top-level let declarations go into a separate declarative record that the global object does not see.
Exercise
An old script begins with 'use strict'; and later runs this.settings = {} at the top level. A teammate says it will throw because strict mode makes this undefined. Are they right? Would anything change if the file were loaded as a module?
Show answer
They are wrong for a classic script. Strict mode only changes this for plain function calls, so top-level this is still the global object and the assignment succeeds. As a module, top-level this is undefined, so the assignment throws a TypeError. The fix is to write globalThis.settings = {}, or to export settings.
Exercise
A CommonJS file contains this.name = 'util'; module.exports = { run() {} };. What does require('./file').name return, and why?
Show answer
It returns undefined. Top-level this initially points to the original module.exports object, so name is set on that object. Reassigning module.exports replaces the exported value with a new object, and the original object, which still has name, is discarded.