Constructors in JavaScript
The constructor method runs automatically at new, establishing valid initial state — assigning parameters to fields, validating, and acquiring resources. Forgetting new (calling Dog() bare) runs it with undefined this (strict: TypeError) — new.target guards detect bare calls when libraries must be foolproof.
Derived constructors must call super() before touching this (the parent builds first), and returning an object from a constructor replaces the instance (returning primitives is ignored). One constructor per class — overload via default/rest parameters, not signatures.
Automatic initialization
new Dog("Rex") runs constructor immediately — the instance is valid from the first line that names it.
Always use new
Bare Dog() misbinds this — capitalize class names as convention and lint new-cap to enforce construction.
Derived calls super first
Subclass constructors must invoke super(...) before this — parent state forms before child specialization.
One constructor only
Later definitions overwrite earlier ones — vary construction with defaults, rest params, and static factories.
class Counter { constructor(start = 0) { this.n = start; }}let c = new Counter(5);console.log(c.n);Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.