JavaScript class

Beginner
5 min read
Updated: Nov 2026
3 examples

Definition and Usage

A class is syntax for constructor functions plus prototype methods. You create instances with new. Methods listed in the class body go on the prototype.

JavaScript Syntax

JavaScript
class Person {
  constructor(name) { this.name = name; }
  hello() { return "Hi " + this.name; }
}
console.log(new Person("Ada").hello());
Try it Editor

How It Works

  1. constructor runs. Sets this.name.
  2. hello method. Found on the prototype.

Examples

Example 1 — Many instances

Each object has its own data.

JavaScript
class C { constructor(n){ this.n = n; } }
console.log(new C(1).n, new C(2).n);
Try it Editor

How It Works

  1. Separate instances.

Example 2 — typeof class

Classes are functions.

JavaScript
class A {}
console.log(typeof A);
Try it Editor

How It Works

  1. class creates a constructor function.

Example 3 — Must use new

Calling without new throws.

JavaScript
class A {}
try { A(); } catch (e) { console.log(e.name); }
Try it Editor

How It Works

  1. Class constructors require new.

Frequently Asked Questions

Mostly yes over prototypes, with stricter rules (must use new, methods non-enumerable).

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful