JavaScript Course
JavaScript
/
Intermediate

ES6 Classes

Definition

Classes are a template for creating objects. They encapsulate data with code to work on that data. JavaScript classes, introduced in ES6, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance.

Explain Like I'm New

Think of a Class like a blueprint for a house. The blueprint itself isn't a house you can live in, but it tells you exactly how to build one. When you use the `new` keyword, you are telling JavaScript to use the blueprint to build a real, physical house (an object).

Real World Example

In a game, you might have a `Player` class. The blueprint says every player needs a name and health. You can use it to spawn `const player1 = new Player('Alice')` and `const player2 = new Player('Bob')`.

Common Use Cases

  • •Object-Oriented Programming (OOP) in JavaScript
  • •Creating multiple objects that share the same methods
  • •Extending base functionality (like React class components)

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • How do you create an instance of a class?
  • What is the 'constructor' method used for?

intermediate

  • How do you inherit from another class?
  • What does the 'super()' function do?

advanced

  • What are static methods and properties?
  • What are private class features (using #)?

trick

  • Are JavaScript classes hoisted like function declarations?

Flash Cards

Question

What does the 'super()' function do?

Click to reveal answer
Answer

When creating a subclass using 'extends', you must call `super()` inside the constructor before accessing `this`. It calls the constructor of the parent class, setting up the inheritance properly.

Question

What are static methods?

Click to reveal answer
Answer

Static methods belong to the Class itself, not to the instances (objects) created from the class. You call them directly on the class, like `Math.random()`, not on a new object.

Question

Are JavaScript classes hoisted?

Click to reveal answer
Answer

Class declarations are hoisted, but they remain in the Temporal Dead Zone (like `let` and `const`). You cannot instantiate a class before it is defined in the code.