Sub topic 5
How Classes Differ from Functions: Strict Mode, TDZ, and new
Earlier chapters showed that a class is a function and that its methods live on a prototype. That raises a practical question: why not keep writing constructor functions? The answer is that a class follows stricter rules than the function it compiles to. This chapter covers those rules: the code inside a class always runs in strict mode, a class name is unusable until its definition runs, and a class constructor only runs through new.
This chapter assumes you know let and const scoping, function hoisting, and the basics of this. It also assumes you can run a script in Node.js or a browser console.
The Differences at a Glance
| Behavior | Constructor function | Class |
|---|---|---|
| Strict mode | Only if the file or function opts in | Always, for the whole class body |
| Hoisting | Fully hoisted and usable before its line | Hoisted, but in the temporal dead zone until defined |
| Called without `new` | Runs; `this` is the global object or `undefined` | Throws `TypeError` |
| Methods enumerable | Yes, if assigned to `prototype` | No |
| Methods usable with `new` | Yes, any `function` can be | No, methods are not constructors |
| Name binding inside the body | Can be reassigned | Read-only, like `const` |
The sections below go through each row and show the mistakes these rules catch.
Class Bodies Are Always Strict
Everything inside a class body runs in strict mode: the constructor, methods, getters, setters, field initializers, and static blocks. You cannot turn this off, and you don't need a 'use strict' directive.
Strict mode turns several silent mistakes into errors. The most common one in class code is assigning to a variable you never declared:
function sloppyRecord() {
totalSloppy = 1; // in a classic script, this silently creates a global
}
sloppyRecord();
console.log(typeof globalThis.totalSloppy); // 'number'
class Tally {
record() {
totalStrict = 1; // same typo, but the class body is strict
}
}
try {
new Tally().record();
} catch (err) {
console.log(err.name); // 'ReferenceError'
}Run this as a classic script, for example node file.js with a .js file in a project without "type": "module". ES modules are strict throughout, so in a module the first function would throw too.
Strict mode also changes these behaviors inside a class:
- A method called without a receiver gets
this === undefinedinstead of the global object. The chapter onthisbinding covers this in detail. - Duplicate parameter names, such as
method(a, a) {}, are a syntax error. - Legacy octal literals such as
010and thewithstatement are syntax errors. - Assigning to a read-only property, such as a frozen object's property, throws instead of being ignored.
Hoisting and the Temporal Dead Zone
A function declaration is hoisted together with its value, so you can call it on a line above its definition. A class declaration is hoisted too, but it behaves like let: the name is reserved for the whole scope but stays uninitialized until the declaration runs. The stretch of code between the start of the scope and the declaration is the temporal dead zone (TDZ). Reading the name inside the TDZ throws a ReferenceError.
console.log(typeof hoistedFn); // 'function'
function hoistedFn() {}
try {
new Early();
} catch (err) {
console.log(err.name); // 'ReferenceError'
console.log(err.message); // in V8: "Cannot access 'Early' before initialization"
}
class Early {}
console.log(typeof Early); // 'function'Even typeof throws inside the TDZ, although typeof on an undeclared name returns 'undefined'.
Proof That the Name Is Hoisted
If class declarations were not hoisted at all, reading the name early would find any outer variable with the same name. It doesn't. The inner declaration shadows the outer name from the very top of the block:
const Widget = 'outer string';
{
try {
console.log(Widget);
} catch (err) {
console.log(err.name); // 'ReferenceError', not 'outer string'
}
class Widget {}
console.log(typeof Widget); // 'function'
}This catches people during refactors. Adding a class to a block can break an earlier line in that block that used to read an outer variable.
What Counts as "Using" the Class Early
The TDZ only matters for code that runs before the declaration. A method body that mentions another class runs later, when someone calls it, so the order of the declarations is irrelevant:
class Library {
makeBook() {
return new Book(); // runs only when makeBook() is called
}
}
class Book {}
console.log(new Library().makeBook() instanceof Book); // trueSome parts of a class run during the definition itself, so they must not reach into the TDZ:
- The
extendsclause is evaluated when the class is defined. - Static field initializers and static blocks run when the class is defined.
- Computed method names such as
[key]() {}are evaluated when the class is defined.
try {
class Registry {
static fallback = new Entry(); // runs now, while Entry is still in the TDZ
}
} catch (err) {
console.log(err.name); // 'ReferenceError'
}
class Entry {}The same rule applies to class Child extends Parent {} when Parent is declared further down. Declare base classes first.
Class Expressions
A class expression assigned to const or let follows the same TDZ rule through that variable. Assigned to var, the name is undefined before the assignment, so an early new throws a TypeError ("not a constructor") rather than a ReferenceError. Both mean the class wasn't ready, but the different error names can send you searching in the wrong place.
The Read-Only Inner Name
Inside the class body, the class name works like a const. Outside the body, a class declaration's binding works like let and can be reassigned.
class Token {
static reset() {
Token = null; // inner binding is read-only
}
}
try {
Token.reset();
} catch (err) {
console.log(err.name); // 'TypeError'
}
console.log(typeof Token); // 'function', unchangedBecause of this, methods that refer to Token keep pointing at the real class even if outside code reassigns the outer variable.
A Class Requires new
A constructor function is an ordinary function, and nothing stops you from calling it without new. In a sloppy script that writes properties onto the global object. A class constructor refuses to run without new:
function OldPoint(x) {
this.x = x;
}
OldPoint(5); // forgot new: in a classic script, this is globalThis
console.log(globalThis.x); // 5, a leaked global
class NewPoint {
constructor(x) {
this.x = x;
}
}
try {
NewPoint(5);
} catch (err) {
console.log(err.name); // 'TypeError'
console.log(err.message); // in V8: "Class constructor NewPoint cannot be invoked without 'new'"
}NewPoint.call(obj, 5) and NewPoint.apply(obj, [5]) throw the same TypeError. Old code used them to "inherit" from a constructor, which is one reason class-based inheritance has to go through extends and super.
If you want a value that can be called without new, put a plain function in front of the class:
class Money {
constructor(cents) {
this.cents = cents;
}
}
const money = (cents) => new Money(cents);
console.log(money(250) instanceof Money); // trueMethods Are Not Constructors
The reverse rule also holds. A method defined with class syntax has no internal construct behavior, so new on a method throws:
class Parser {
parse() {
return 'parsed';
}
}
const p = new Parser();
try {
new p.parse();
} catch (err) {
console.log(err.name); // 'TypeError' (p.parse is not a constructor)
}Non-Enumerable Methods
When you assign methods to prototype by hand, they are enumerable and show up in for...in loops. Class methods are defined as non-enumerable, so only the instance's own data appears:
function OldUser(name) {
this.name = name;
}
OldUser.prototype.greet = function () {
return `Hi, ${this.name}`;
};
class NewUser {
constructor(name) {
this.name = name;
}
greet() {
return `Hi, ${this.name}`;
}
}
const oldKeys = [];
for (const key in new OldUser('Ada')) oldKeys.push(key);
const newKeys = [];
for (const key in new NewUser('Ada')) newKeys.push(key);
console.log(oldKeys); // ['name', 'greet']
console.log(newKeys); // ['name']Common Errors and How to Read Them
| Symptom | Likely cause | Fix |
|---|---|---|
| `ReferenceError: Cannot access 'X' before initialization` | Class used, extended, or referenced by static code above its declaration | Move the declaration up, or reference it only inside methods |
| `TypeError: Class constructor X cannot be invoked without 'new'` | Called as a function, or through `.call`/`.apply` | Add `new`, or use `extends` and `super` for inheritance |
| `ReferenceError: y is not defined` inside a method | Undeclared assignment, caught by strict mode | Declare the variable or assign to `this.y` |
| `TypeError: X is not a constructor` | `new` used on a method, or a `var` class expression read before assignment | Use the class itself; fix ordering |
| `TypeError: Assignment to constant variable` inside a class | Reassigned the class name within its own body | Store state in a static field instead |
Exercise
The following script throws before printing anything. Which line throws, what is the error type, and what is the smallest change that fixes it? class Admin extends Account {} class Account {} console.log(new Admin() instanceof Account);
Show answer
The first line throws a ReferenceError. The extends clause is evaluated when Admin is defined, and at that moment Account is still in its temporal dead zone. Swap the first two lines so Account is declared before Admin. The script then prints true.
Exercise
A team converts function Logger(prefix) { this.prefix = prefix; } into a class with the same constructor. A legacy file still calls Logger('app') without new. Describe what happened before the change in a sloppy script, and what happens after it.
Show answer
Before the change, the call ran with this set to the global object, so it silently created a global prefix property and returned undefined. After the change, the call throws TypeError: Class constructor Logger cannot be invoked without 'new'. The class turns a hidden bug into an immediate error. Fix the caller by adding new, or export a factory function such as (prefix) => new Logger(prefix).
Exercise
Why does this code print 'function' and not throw, even though Helper is declared after Tool? class Tool { static kind() { return typeof Helper; } } class Helper {} console.log(Tool.kind());
Show answer
The reference to Helper is inside a static method body, which runs only when Tool.kind() is called. By then Helper's declaration has run and the binding is initialized. Only code that runs during the class definition, such as extends clauses, computed keys, static field initializers, and static blocks, can hit the temporal dead zone.