Learn JavaScript
❯ classes_oop.constructors

Constructors in JavaScript

$concept

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.

$how it works
1

Automatic initialization

new Dog("Rex") runs constructor immediately — the instance is valid from the first line that names it.

2

Always use new

Bare Dog() misbinds this — capitalize class names as convention and lint new-cap to enforce construction.

3

Derived calls super first

Subclass constructors must invoke super(...) before this — parent state forms before child specialization.

4

One constructor only

Later definitions overwrite earlier ones — vary construction with defaults, rest params, and static factories.

$example
class Counter {
constructor(start = 0) {
this.n = start;
}
}
let c = new Counter(5);
console.log(c.n);
Output
5
1new Counter(5) runs the constructor with start=5, assigning this.n.
2Omitted arguments would default to 0 — one signature serving both shapes.
35 prints from properly initialized instance state.
$use cases
Requiring setup data as constructor parameters (no invalid instances)
Default and rest parameters standing in for overloading
Static factory methods (Point.fromPolar) for named construction styles
Guarding with new.target in libraries tolerating bare calls

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.