DEV Community

Sourav Bandyopadhyay
Sourav Bandyopadhyay

Posted on

Instance and Non-instance properties

In JavaScript, instance properties are properties that belong to an instance of a class or an object, while non-instance properties are properties that belong to the class or the object itself.

  • Instance properties are defined inside the class constructor using the "this" keyword, and they can be accessed and modified using the dot notation on an instance of the class:
class Person {
  constructor(name, age) {
    this.name = name; // instance property
    this.age = age;   // instance property
  }
}

const john = new Person("John", 30);
console.log(john.name); // "John"
john.age = 31;
console.log(john.age); // 31
Enter fullscreen mode Exit fullscreen mode
  • Non-instance properties, on the other hand, are defined outside the class constructor or object literal using the class name or object name, respectively. They can be accessed and modified using the dot notation on the class or object itself:
// Class example
class Person {
  static species = "Homo sapiens"; // non-instance property
}

console.log(Person.species); // "Homo sapiens"

// Object example
const person = {
  name: "John",
  age: 30,
};

person.gender = "Male"; // non-instance property
console.log(person.gender); // "Male"
Enter fullscreen mode Exit fullscreen mode

In the above example, Person.species is a non-instance property of the Person class, while person.gender is a non-instance property of the person object. Non-instance properties are typically used to define values that are shared among all instances of a class or all objects of a certain type.

Top comments (0)