DEV Community

Azrul Aziz
Azrul Aziz

Posted on • Updated on

JavaScript: So class is a function?

I have written a lot of class component using React. But I have never really understood class.
In this short post I will explore what class is fundamentally.

Lets go ahead & see one way to declare a class:

class User {}
Enter fullscreen mode Exit fullscreen mode

Here we use a class declaration to declare a class called User. So what is class? is it a function? or is it an object? Lets test:

typeof(User) // "function"
Enter fullscreen mode Exit fullscreen mode

Well class is actually a function!
If its a function, lets try to invoke it and see what happens.

User() //TypeError: class constructors must be invoked with |new|
Enter fullscreen mode Exit fullscreen mode

Eror! What happened? Initially we saw that class is a function, but when we tried to execute it like a normal function, it throws an error saying class constructors must be invoked with |new|.

Classes are "special functions"

According to MDN Classes are "special functions". I went to look for more info and learned that class is actually used as a constructor function. A constructor function is a function that is used to construct an object. That's why the console throws an error about needing the new keyword. In order to invoke a constructor function, we must use the new keyword.

Lets see an example:

const lily = new User()

typeof(lily) // "object"

console.log(lily) // Object {}
Enter fullscreen mode Exit fullscreen mode

We invoked the class using the new keyword and assign it to a variable named lily. When we evaluate the typeof lily, we got object as the result. The result from logging the value also returns an object. As mentioned above, constructor function generates an object.

Im only scratching the surface here. In the future post I will explore even further on what goes inside class and why to use class when we can just use a normal function as a constructor function to construct an object.

Oldest comments (0)