Sub topic 2
this at the Top Level and globalThis
This chapter assumes you know how to write and run JavaScript in a browser or in Node.js. You should also know the difference between var, let, and const. Before looking at functions, it helps to know what this is when no function is involved at all, at the top level of a file. The answer depends on how the file is loaded, not on what code it contains.
Three kinds of top level
JavaScript code runs at the top level in one of three common ways:
- A classic script is a file loaded with a plain
<script>tag, or code typed into a browser console or the Node REPL. - An ES module is a file loaded with
<script type="module">, a.mjsfile, or a.jsfile in a Node package whosepackage.jsonsets"type": "module". - A CommonJS module is the older Node format. It uses
requireandmodule.exportsand covers.cjsfiles and.jsfiles without"type": "module".
Each one sets the top-level this differently.
Classic scripts: this is the global object
In a classic script, top-level this is the global object. In a browser that is window. Top-level var declarations and function declarations become properties of that object. let, const, and class declarations do not.
// Load with a plain <script> tag, not type="module"
console.log(this === window); // true
console.log(this === globalThis); // true
var answer = 42;
let local = 1;
console.log(this.answer); // 42, var creates a global property
console.log(this.local); // undefined, let does notES modules: this is undefined
Module code is always strict, and the specification sets top-level this in a module to undefined. This is deliberate. Modules are meant to have their own scope, so they do not hand you the global object by accident.
// main.mjs (run with: node main.mjs)
console.log(this); // undefined
console.log(typeof globalThis); // 'object', the global object is still reachableCommonJS: this is module.exports
Node wraps each CommonJS file in a function and calls it with module.exports as this. At the top level of such a file, this is the exports object and not the global object.
// counter.cjs (run with: node counter.cjs)
console.log(this === module.exports); // true
console.log(this === globalThis); // false
exports.name = 'counter';
console.log(this.name); // 'counter'The Node REPL works differently. Code typed there runs like a classic script, so this === globalThis is true. Code that behaves one way in the REPL can therefore behave another way in a file.
globalThis: one name for the global object
Before ES2020, the global object went by a different name in each environment: window in browser pages, self in web workers, and global in Node. Portable code had to test for each name. globalThis is a standard name that works in all of them, and in any mode.
function getGlobal() {
return globalThis;
}
globalThis.appConfig = { debug: true };
console.log(getGlobal().appConfig.debug); // trueUse globalThis whenever you actually need the global object. Do not rely on top-level this to get it, because that only works in classic scripts.
| Environment | Top-level `this` | Global object name |
|---|---|---|
| Browser classic script | `window` | `window`, `globalThis` |
| Browser ES module | `undefined` | `window`, `globalThis` |
| Classic web worker | `self` | `self`, `globalThis` |
| Node CommonJS file | `module.exports` | `global`, `globalThis` |
| Node ES module | `undefined` | `global`, `globalThis` |
| Node REPL | `globalThis` | `global`, `globalThis` |
Common errors
- Migrating to modules breaks
this.something. Code that read globals through top-levelthisgetsTypeError: Cannot read properties of undefinedonce the file becomes a module. ReplacethiswithglobalThis. - Expecting
letglobals on the global object.globalThis.localisundefinedfor a top-levellet, even in a classic script. - Assuming the REPL matches a file. Test top-level behavior in the same format you ship.
Exercise
A file named app.cjs contains this.version = '1.0'; console.log(globalThis.version, module.exports.version);. What does running node app.cjs print, and why?
Show answer
It prints undefined 1.0. In a CommonJS file, top-level this is module.exports, so the assignment adds version to the exports object and not to the global object.
Exercise
You move a browser script that contains var count = 0; console.log(this.count); into a <script type="module"> tag. What happens, and how do you fix it?
Show answer
It throws a TypeError, because top-level this in a module is undefined. Also, var in a module does not create a global property. Read count directly, or if you really need a global, assign globalThis.count = 0 and read globalThis.count.