Getting Started with Modern JavaScript — Classes

Michael Karén
4 min readAug 27, 2020

We often need to create many objects of the same kind, like users or cars. In object-oriented languages, a class is often used for this purpose.
JavaScript, being a prototype-based language, has something called constructor functions.

Classes, introduced with ES6 provide “syntactical sugar”, that is comparable to inheritance in object-oriented languages. Classes are special functions meant to mimic the class keyword from these other languages. In this article we go through how to use JavaScript classes.

Defining a Class

To define a class we use the class keyword followed by the name of the class. The body of a class is the part that is in curly braces {}:

class Car {
// Body of the class
}

The code above defines a class Car. This syntax is named class declaration.

The new operator instantiates the class:

const myCar = new Car();

This is how we create a new object, an instance, of the Car class.

console.log(typeof Car); // -> function

And as you can see, in JavaScript, a class is a kind of function.

We don’t need to give the class a name. By using a class expression you can assign the class to a variable:

const Car = class {} // unnamed
const Car = class Car {} // named

Class expressions can be named or unnamed. The name given to a named class expression is local to the class’s body.

Hoisting

An important difference between function declarations and class declarations is that function declarations are hoisted and class declarations are not. Therefore you need to first declare the class before you can initialize objects with the `new` keyword.

Conceptually, for example, a strict definition of hoisting suggests that variable and function declarations are…

--

--

Michael Karén

Frontend Architect • JavaScript Enthusiast • Educative.io Author • ngVikings organizer.