Posted on: October 29, 2022|Amrish Kushwaha

Static vs Instance in Javascript

Static vs Instance in Javascript

Static properties and methods & instance properties and methods are related to the Class in javascript.

In this article, we will learn the difference between these two (static and instance).

Static properties and methods:

Static properties and methods are those properties and methods which belongs to the class only.

It is directly available to the Class.

We define them with static word in class declaration.

For e.g.

class Car {
static noOfWheels = 4
static increase(speed) {
return ++speed
}
}

In this example, you can see that the property noOfWheels is static property and the method increase is a static method.

Another way to declare static properties and methods on the class is by using the dot method.

For example:

class Car {}
Car.noOfWheels = 4
Car.increase = function (speed) {
return ++speed
}

Some Key Points:

  • Static properties and methods belongs the class.
  • Static properties and methods of a class are available to instances of that class.

Instance properties and methods:

Those properties and methods which are attached to instances of the class i.e. objects, not to the class, are called instance properties and methods.

For example:

class Car {
speed = 0
increaseSpeed() {
return ++this.speed
}
}
const car1 = new Car()
console.log(car1.speed) // 0
console.log(car1.increaseSpeed()) // 1

In the above code, you can see that instance property speed and instance method increaseSpeed of object car1

Another way to declare this:

class Car {}
const car1 = new Car()
car1.speed = 0
car1.increaseSpeed = function () {
return ++this.speed
}
console.log(car1.speed) // 0
console.log(car1.increaseSpeed()) // 1;

The difference:

Static properties and methods belong to class. Thus it will be available to all the instances of that class.

Instance properties and methods belong to the instance of the class.


Thanks for reading the article. Keep coding and keep solving problems.

About author:

Amrish Kushwaha

Amrish Kushwaha

I am Amrish Kushwaha. Software Engineer, Maker, Writer. I am currently focused on frontend development with curiosity of building end to end software system. Currently I am working at Rafay Systems. I love to write as well as build side projects when I am free.

Related category articles: