JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

How do ES6 classes work in JavaScript?

Asked on Aug 06, 2024

Answer

ES6 classes in JavaScript provide a more intuitive syntax for creating objects and handling inheritance, similar to class-based languages like Java or Python.
<!-- BEGIN COPY / PASTE -->
        class Animal {
            constructor(name) {
                this.name = name;
            }

            speak() {
                console.log(`${this.name} makes a noise.`);
            }
        }

        class Dog extends Animal {
            speak() {
                console.log(`${this.name} barks.`);
            }
        }

        const dog = new Dog('Rex');
        dog.speak(); // Output: Rex barks.
        <!-- END COPY / PASTE -->
Additional Comment:
  • The "class" keyword is used to define a class.
  • "constructor" is a special method for creating and initializing objects.
  • "extends" is used for inheritance, allowing a class to inherit properties and methods from another class.
  • Methods inside classes do not require the "function" keyword.
  • The "super" keyword can be used to call the constructor or methods of the parent class.
✅ Answered with JavaScript best practices.
← Back to All Questions