The JavaScript class statement
The class keyword defines a blueprint for creating objects. A constructor sets up each instance, and methods are shared by all instances. You create one with new: const u = new User("Ada"). Classes support inheritance with extends. Under the hood they're syntactic sugar over JavaScript's prototype system.
Overview
A class is a template for objects of the same kind. The constructor method runs when you create an instance and is where you set up its data on this; other methods defined in the class are shared across every instance. You build an object from a class with the new keyword: new User("Ada") calls the constructor and returns a fresh object.
Classes can build on one another through inheritance. class Admin extends User makes Admin inherit User's methods, and super(...) calls the parent constructor. This lets you share behavior without repetition. Classes also support getters, setters, static methods (called on the class itself, like Object.keys()) and private fields prefixed with #.
It's worth knowing that class is mostly syntactic sugar over JavaScript's older prototype-based inheritance — it's a cleaner syntax for what was always possible, not a new object model. Two practical notes: class bodies run in strict mode automatically, and unlike function declarations, classes are not hoisted, so you must define a class before you use it.
Syntax
class User {
constructor(name) {
this.name = name;
}
greet() {
return "Hi, " + this.name;
}
}
class Admin extends User {
constructor(name) { super(name); this.role = "admin"; }
}
const u = new User("Ada");
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
class Counter {
constructor() { this.count = 0; }
increment() { this.count++; return this; }
}
const c = new Counter();
c.increment().increment().increment();
document.getElementById('out').textContent = 'Count: ' + c.count; // Count: 3
</script>
Best practices
- Set instance data on
thisin theconstructor; put shared behavior in methods. - Use
extendsandsuper()for inheritance instead of copying code between classes. - Remember classes aren't hoisted — define a class before you instantiate it.
- Use
#nameprivate fields for internals that shouldn't be accessed from outside.
Frequently asked questions
How do I create a class in JavaScript?
class Name { constructor(...) { ... } }, then create instances with new Name(...).What does the constructor do?
new, and is where you initialize the object's properties on this.How does class inheritance work?
class Child extends Parent to inherit methods, and call super(...) in the child constructor to run the parent's setup.