JavaScript Classes

Blueprints for objects, inheritance and getters.

✍️ 3 exercises + code challenge in this lesson

A class is a template for creating objects.

  • constructor() runs when a new object is created with new.
  • Methods are defined inside the class body.
  • extends creates a child class; super() calls the parent constructor.
  • get / set define computed properties.
  • static methods belong to the class itself, not to instances.
  • Fields starting with # are private.

Key Takeaways: JavaScript Classes

Mastering JavaScript Classes helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

JavaScript Classes Code Example

JavaScript
<pre id="out"></pre>
<script>
const log = (...a) => document.getElementById("out").textContent += a.join(" ") + "\n";
class Account {
  #balance = 0;

  constructor(owner) { this.owner = owner; }
  deposit(amount) { this.#balance += amount; return this; }
  get balance() { return this.#balance; }
  static bank() { return "CodesInTech Bank"; }
}

class SavingsAccount extends Account {
  constructor(owner, rate) {
    super(owner);
    this.rate = rate;
  }
  interest() { return this.balance * this.rate; }
}

const acc = new SavingsAccount("Ali", 0.05);
acc.deposit(10000).deposit(5000);
log(Account.bank(), "|", acc.owner, "has", acc.balance);
log("Yearly interest:", acc.interest());
</script>
Free sign-in required · Google login available

JavaScript Classes Practice Exercises

Check what you learned in “JavaScript Classes”.

/ 3 solved
Fill in the blank

Create a child class.

class Dog  Animal { }
✓ Correct! Not quite. Try again.
Multiple choice

Which method runs when a new object is created from a class?

✓ Correct! Not quite. Try again.
Code challenge

Create a class Person with a constructor(name) and a method greet() that returns "Hi, " + name. Log new Person("Ali").greet().

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services