In JavaScript, why were classes introduced when we already had functions?
Think about how classes help organize code and reuse features.
Classes give a simpler and more readable way to create objects and manage inheritance compared to using functions and prototypes directly.
What is the output of this code?
function Person(name) { this.name = name; } Person.prototype.greet = function() { return `Hello, ${this.name}`; }; class Animal { constructor(name) { this.name = name; } greet() { return `Hi, ${this.name}`; } } const p = new Person('Alice'); const a = new Animal('Dog'); console.log(p.greet()); console.log(a.greet());
Look at how greet() is defined in each case.
The function Person uses prototype to define greet which returns 'Hello, name'. The class Animal defines greet as a method returning 'Hi, name'.
What is the output of this code?
class Vehicle { constructor(type) { this.type = type; } describe() { return `This is a ${this.type}`; } } class Car extends Vehicle { constructor(type, brand) { super(type); this.brand = brand; } describe() { return `${super.describe()} of brand ${this.brand}`; } } const myCar = new Car('car', 'Toyota'); console.log(myCar.describe());
Check how super is used to call the parent method.
The Car class extends Vehicle and calls super.describe() to get 'This is a car', then adds 'of brand Toyota'.
How do classes help organize code better compared to using only functions and objects?
Think about how classes bundle properties and methods.
Classes bundle related data (properties) and actions (methods) in one place, which helps keep code clean and easier to maintain.
What is the output of this code?
class Counter { #count = 0; increment() { this.#count++; } getCount() { return this.#count; } } const c = new Counter(); c.increment(); c.increment(); console.log(c.getCount()); console.log(c.#count);
Private fields cannot be accessed outside the class.
The private field #count can be accessed inside the class methods but trying to access c.#count outside causes a TypeError.