Back to Freecodecamp

What Are Static Properties and Methods in Classes?

curriculum/challenges/english/blocks/lecture-understanding-how-to-work-with-classes-in-javascript/673403dbf5c9835898632c84.md

latest8.7 KB
Original Source

--interactive--

Static properties and methods belong to the class itself, not to the individual instances of the class. You can access them directly on the class name without creating an instance of the class. They are defined within classes to encapsulate related functionality.

You can define a static method by writing the static keyword before the name of the method.

js
class MyClass {
  static staticMethod() { ... }
}

Then, you can call the static method on the class directly, using dot notation and passing any necessary arguments:

js
MyClass.staticMethod();

Notice that you are able to call the method without creating an instance of the class. That's one of the key characteristics of static methods.

Here's an example. Let's say that we are creating a movies application and we want to be able to compare movies based on their rating.

We could consider this comparison method as a higher level method that is not specific to any movie:

js
if (movieA.rating < movieB.rating) {
  console.log(`${movieB.title} has a higher rating.`);
} 

It's like a more general method related to the Movie class.

For readability and maintainability purposes, it would be helpful to define it within the Movie class to keep all related methods relatively close to each other.

Therefore, this is a perfect candidate for a static method. You can see it here, just below the constructor:

:::interactive_editor

js
class Movie {

  constructor(title, rating) {
    this.title = title;
    this.rating = rating;
  }

  static compareMovies(movieA, movieB) {
    if (movieA.rating > movieB.rating) {
      console.log(`${movieA.title} has a higher rating.`);
    } else if (movieA.rating < movieB.rating) {
      console.log(`${movieB.title} has a higher rating.`);
    } else {
      console.log("These movies have the same rating.");
    }
  }

}

let movieA = new Movie("Movie A", 80);
let movieB = new Movie("Movie B", 45);
console.log(movieA);

:::

The static method is defined with the static keyword and it's called compareMovies. It has two parameters: movieA and movieB. These will be instances of the Movie class.

We will compare them based on their rating, on a range from 0 to 100. This logic is implemented with a conditional and it will print an appropriate message based on which movie has a higher rating.

Once the method has been defined, you can call it on the class. But first, you need to have the arguments ready and defined in your program.

In this case, the method takes two movie instances as arguments, so we define these instances here:

js
let movieA = new Movie("Movie A", 80);
let movieB = new Movie("Movie B", 45);

You can see that movieA has a higher rating than movieB. Let's see the output of this method.

To call the method, you just need to use dot notation on the class itself. You write the name of the class (Movie), followed by a dot, and then the name of the static method (compareMovies).

Then, you pass the arguments within parentheses. In this case, they are the two movie instances that the method requires.

js
Movie.compareMovies(movieA, movieB);

Here is the updated example:

:::interactive_editor

js
class Movie {

  constructor(title, rating) {
    this.title = title;
    this.rating = rating;
  }

  static compareMovies(movieA, movieB) {
    if (movieA.rating > movieB.rating) {
      console.log(`${movieA.title} has a higher rating.`);
    } else if (movieA.rating < movieB.rating) {
      console.log(`${movieB.title} has a higher rating.`);
    } else {
      console.log("These movies have the same rating.");
    }
  }

}

let movieA = new Movie("Movie A", 80);
let movieB = new Movie("Movie B", 45);
Movie.compareMovies(movieA, movieB);
console.log(movieA);

:::

Static methods are also helpful for implementing "factory" methods. A factory method is a method that you define in addition to the constructor to create objects based on specific criteria.

Here's an example with a Pizza class. The static method createMargherita is a factory method that you can call to create a Margherita pizza instance with its type and price already set.

js
class Pizza {
  constructor(type, price) {
    this.type = type;
    this.price = price;
  }

  static createMargherita() {
    return new this("Margherita", 6.99);
  }
}

This also brings up something very important about static methods.

The value of the this keyword in static methods is the class itself, since the static method belongs to the class.

That's why we can use this to create a new instance of the Pizza class.

If you call this method on the Pizza class itself and assign the returned instance to a variable, like in this example:

js
let myPizza = Pizza.createMargherita();

You can use it wherever you need to in your code. For example, you can print it to the console:

js
console.log(myPizza);

This is the output:

js
Pizza { type: 'Margherita', price: 6.99 }

You can also use dot notation to call its methods and access its properties, like this:

js
console.log(myPizza.type);

Here is the full example:

js
class Pizza {
  constructor(type, price) {
    this.type = type;
    this.price = price;
  }

  static createMargherita() {
    return new this("Margherita", 6.99);
  }
}

let myPizza = Pizza.createMargherita();
console.log(myPizza);
console.log(myPizza.type);

In addition to methods, you can also define static properties with the static keyword.

In this example, we have a static numberOfPizzasSold property.

js
class Pizza {
  static numberOfPizzasSold = 0;

  constructor(type) {
    this.type = type;
    Pizza.numberOfPizzasSold++;
  }
}

It's static because it doesn't belong to any particular pizza instance, it belongs to the class itself.

It has an initial value of 0 and it's updated every time a new instance is created.

If you create two pizza instances, the value will be updated twice:

js
let pizza1 = new Pizza("Margherita");
let pizza2 = new Pizza("Neapolitan");

To access the value of a static property, you just need to use dot notation on the class itself, since the property belongs to the class.

js
class Pizza {
  static numberOfPizzasSold = 0;

  constructor(type) {
    this.type = type;
    Pizza.numberOfPizzasSold++;
  }
}

let pizza1 = new Pizza("Margherita");
let pizza2 = new Pizza("Neapolitan");

console.log(Pizza.numberOfPizzasSold);

In this case, the output is 2 because two pizzas were sold.

These are the fundamentals of static properties and methods in JavaScript. Understanding static members is essential for creating reusable and efficient classes.

--questions--

--text--

What is the primary purpose of a static method in a JavaScript class?

--answers--

To create new instances of the class.

--feedback--

Think about how static methods are related to the class itself, not to individual objects.


To access the properties of the class instance.

--feedback--

Think about how static methods are related to the class itself, not to individual objects.


To define methods that can be accessed without creating an instance of the class.


To inherit properties and methods from a parent class.

--feedback--

Think about how static methods are related to the class itself, not to individual objects.

--video-solution--

3

--text--

What is the main difference between a static method and an instance method in JavaScript?

--answers--

Static methods can only be used within the class, while instance methods can be used outside the class.

--feedback--

Think about the scope and accessibility of static and instance methods.


Static methods can access instance properties, while instance methods cannot access instance properties.

--feedback--

Think about the scope and accessibility of static and instance methods.


Static methods are associated with the class itself, while instance methods are associated with specific instances of the class.


Static methods are always public, while instance methods can be public or private.

--feedback--

Think about the scope and accessibility of static and instance methods.

--video-solution--

3

--text--

How can you access a static property of a class in JavaScript?

--answers--

By using the this keyword.

--feedback--

Think about how static properties are associated with the class itself.


By creating an instance of the class and accessing the property through the instance.

--feedback--

Think about how static properties are associated with the class itself.


By directly using the class name and the property name.


By using the prototype property of the class.

--feedback--

Think about how static properties are associated with the class itself.

--video-solution--

3