Sobes.tech
Middle

JavaScript classes are syntactic sugar over what?

sobes.tech AI

Answer from AI

Classes in JavaScript are syntactic sugar over prototypal inheritance. Under the hood, classes are implemented using constructor functions and prototypes.

For example, a class:

class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

is equivalent to:

function Animal(name) {
  this.name = name;
}
Animal.prototype.speak = function() {
  console.log(this.name + ' makes a sound.');
};

Thus, classes simplify and make object creation and inheritance more readable, but do not change the fundamental prototype model in JavaScript.