How to check if an Object is instance of a Class - Javascript
Tags: javascript, node
Published: 2023-07-10 18:07:02

Today, I encountered a Leetcode challenge: [Check if Object Instance of Class](https://leetcode.com/problems/check-if-object-instance-of-class/description/). In order to solve this problem, it is important to have a solid understanding of three fundamental concepts in JavaScript: Classes, Objects, and Prototypes.

## Class

Classes serve as templates for creating objects. They encapsulate data along with the code that operates on that data. [Reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)

To better comprehend the concept of a class, let's consider an analogy. Think of a class as a recipe for a cake. A recipe describes everything necessary to prepare a cake. Similarly, a class allows us to define all the components and behaviors an object needs to exist.

For instance, suppose we want to represent a Car using a class. A car requires properties such as color, factory, and maxSpeed. Additionally, a car can turn its lights on or off. In JavaScript, we can represent this as follows:

```js

class Car {

    lights = false    

    constructor(color, factory, maxSpeed) {
        this.color = color
        this.factory = factory
        this.maxSpeed = maxSpeed
    }

    toggleLights() {
        this.lights = !this.lights
    }
    
}

```

In this example, the class Car defines a constructor function that receives the necessary data when creating an object. We also define a property called lights to represent the state of the car's lights (whether they are on or off). The toggleLights function, which is a method within the class, allows us to switch the lights on and off.

## Objects

An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method. [Reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_objects)

Let's build upon the previous example by creating an object based on the Car class:

```js

const myCar = new Car('blue', 'VW', 300)

console.log(myCar.lights)
// false

myCar.toggleLights()

console.log(myCar.lights)
// true
```

To create an object from a class, we use the **new** keyword. Once the object is created, we can use it to interact with the defined properties and methods. In the provided example, the **myCar** object is created from the **Car** class, and we can access and modify its properties.

![Console.log of myCar object](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/igcokidylxaadhve6iez.png)

When we examine our myCar object, we can see that it displays all the properties defined within the class. Additionally, it has a special property called **[[Prototype]]**, which indicates the prototype from which the object was created. In this case, the prototype is the Car class's constructor.

## Prototype

Prototypes are the mechanism by which JavaScript objects inherit features from one another. [Reference](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes).

As shown in the previous example, an object is aware of its prototype, which serves as the template for its creation. In JavaScript, classes are built on prototypes, and we can determine an object's prototype using the **Object.getPrototypeOf** function.

To illustrate, let's console.log:

![Console.log of Object.getPrototypeOf function receiving myCar as a parameter](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/axvhqiqgqgmqi41vurzv.png)

The prototype of our myCar object is the Car class. However, the Car class itself also has a prototype, denoted by [[Prototype]]. Since all classes are built on prototypes, the initial prototype in the chain is the Object class.


![Console.log of Object.getPrototypeOf function receiving Object.getPrototypeOf function as a parameter that is receiving myCar as a parameter](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5z9eqjtj8u3rtia5qw15.png)

The **Object** class, in turn, has a prototype that points to **null**, which concludes the prototype chain.

![Diagram of prototype relationship](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/61xi4criowjvdhw9qi0o.png)

## Solving the leetcode problem

To determine if an object is an instance of a particular class, we need to check if the object's prototype matches the class's prototype.

In our previous example, we can achieve this by using the following code:

```js
Object.getPrototypeOf(myCar) === Car.prototype
// true
```

Thus, we can conclude that the myCar object was created based on the Car prototype.

### Edge cases of the problem

As we mentioned earlier, an object is created from a class, which, in turn, may be based on another class, and this chain continues until it reaches the Object class.

Consider the following code:

```js
Object.getPrototypeOf(myCar3) === Object.prototype
// false
```

In this case, the result is false because we are not comparing the complete prototype chain. To properly check if an object is based on the Object class, we need to modify the code as follows:

```js
myCar instanceof Car
// true
myCar instanceof Object
// true
```

Another aspect to consider is when dealing with primitive values. We must transform them into objects to determine their prototypes correctly. For example:

```js
Object(2) instanceof Number
// true
Object('23') instanceof String
// true
Object(myCar) instanceof Car
// true
```

I hope this blog post has helped you gain a better understanding of JavaScript and its concepts. Feel free to follow me for more insights into the world of JavaScript.