JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Class Static


In JavaScript, static methods and properties are features of classes that belong to the class itself, rather than to instances of the class. Introduced in ES6, static members are useful for utility functions, constants, and operations that don’t rely on individual object instances.

Understanding static members is essential for writing modular, organized, and memory-efficient code. They are commonly used in helper classes, mathematical computations, configuration utilities, and singleton patterns.

1. What Are Static Members?

  • Static methods are functions that belong to the class, not the object instance.

  • Static properties (introduced in later JavaScript versions) are variables that also belong to the class.

  • Static members are accessed using the class name, not through an instance.

class Calculator {
  static add(a, b) {
    return a + b;
  }
}

console.log(Calculator.add(5, 10)); // 15

const calc = new Calculator();
// calc.add(5, 10); // Error: add is not a function
  • Attempting to access a static method on an instance results in an error.

2. Why Use Static Members?

  1. Utility Functions: Functions like math operations or string manipulation don’t need instance data.

  2. Shared Constants: Define common values or configuration at the class level.

  3. Memory Efficiency: Static members are stored once, rather than being recreated per instance.

  4. Logical Organization: Helps separate instance behavior from class-level behavior.

3. Static Methods

Static methods are defined using the static keyword inside a class:

class MathHelper {
  static square(x) {
    return x * x;
  }

  static cube(x) {
    return x * x * x;
  }
}

console.log(MathHelper.square(4)); // 16
console.log(MathHelper.cube(3));   // 27
  • Static methods can call other static methods using this or the class name:

class Calculator {
  static multiply(a, b) {
    return a * b;
  }

  static square(a) {
    return this.multiply(a, a);
  }
}

console.log(Calculator.square(5)); // 25
  • Using this inside a static method refers to the class itself, not any instance.

4. Static Properties

Static properties store data that is shared across all instances or logically belongs to the class itself:

class Circle {
  static pi = 3.14159;

  constructor(radius) {
    this.radius = radius;
  }

  area() {
    return Circle.pi * this.radius * this.radius;
  }
}

const circle1 = new Circle(5);
console.log(circle1.area()); // 78.53975
console.log(Circle.pi);      // 3.14159
  • The property pi is shared at the class level.

  • Static properties are not accessible from instances (circle1.pi is undefined).

5. Inheritance of Static Members

Static members can be inherited by child classes using the extends keyword:

class Vehicle {
  static category = "Transport";

  static type() {
    return "Generic Vehicle";
  }
}

class Car extends Vehicle {}

console.log(Car.category); // Transport
console.log(Car.type());   // Generic Vehicle
  • Child classes inherit static properties and methods.

  • You can also override static methods in the child class:

class Truck extends Vehicle {
  static type() {
    return "Heavy Vehicle";
  }
}

console.log(Truck.type()); // Heavy Vehicle

6. Combining Static and Instance Members

A class can have both instance and static members:

class Person {
  static species = "Homo Sapiens";

  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log(`Hello, I am ${this.name}`);
  }

  static info() {
    console.log(`All humans belong to species: ${this.species}`);
  }
}

const person1 = new Person("Alice");
person1.greet();         // Hello, I am Alice
Person.info();           // All humans belong to species: Homo Sapiens
// person1.info();       // Error: info is not a function
  • Static members are class-level, instance members are object-level.

  • Static and instance members can coexist without conflicts.

7. Practical Use Cases

  1. Utility Classes: Math, Date, or custom helper classes.

  2. Singleton Patterns: Store shared configuration in static properties.

  3. Factory Methods: Use static methods to create instances with specific logic.

  4. Constants: Define shared constants like Circle.pi in geometric computations.

class Logger {
  static logCount = 0;

  static log(message) {
    Logger.logCount++;
    console.log(`Log ${Logger.logCount}: ${message}`);
  }
}

Logger.log("Server started");  // Log 1: Server started
Logger.log("Connection established"); // Log 2: Connection established
  • The static property logCount keeps track across all calls.

8. Notes and Best Practices

  • Use static members for shared logic, constants, and utilities.

  • Avoid using static members to store instance-specific data.

  • Static members can be inherited and overridden, enabling flexible class hierarchies.

  • Combining static and instance members improves code organization and clarity.

  • Static members are useful in frameworks and libraries, e.g., React.Component static methods like getDerivedStateFromProps.

9. Summary of the Tutorial

  • Static members belong to the class, not instances.

  • They are accessed using the class name, not an object.

  • Static methods are functions for utility purposes.

  • Static properties store shared data or constants.

  • Static members can be inherited or overridden in child classes.

  • Combining static and instance members allows clean, organized, and efficient code.

Mastering static members is essential for writing reusable, modular, and memory-efficient JavaScript applications, especially when designing utility classes, constants, or shared logic.


Practice Questions

  1. Basic Static Method
    Create a class Calculator with a static method add(a, b). Call it using the class name and log the result.

  2. Accessing Static Property
    Create a class Circle with a static property pi = 3.14. Use it in a method area(radius) to calculate the area of a circle.

  3. Static Method Calling Another Static Method
    Create a class MathHelper with two static methods: multiply(a, b) and square(x) that calls multiply(x, x). Test the methods.

  4. Instance Cannot Access Static Method
    Create a static method in a class and attempt to call it from an instance. Explain why it fails.

  5. Static Property Inheritance
    Create a parent class Vehicle with a static property type = "Transport". Extend it with a class Car and log the inherited property.

  6. Overriding Static Method
    Extend a parent class Vehicle with a child class Truck and override a static method info(). Call it from the child class and log the result.

  7. Combining Static and Instance Methods
    Create a class Person with a static method species() and an instance method greet(). Create an instance and call both methods correctly.

  8. Counting Instances with Static Property
    Create a class User with a static property count. Increment it in the constructor each time a new user is created. Log User.count after creating multiple instances.

  9. Static Method Factory
    Create a static method createAdmin() in a User class that returns a pre-configured admin user instance. Test by calling the static method.

  10. Static Utility Class
    Create a utility class Converter with static methods toCelsius(f) and toFahrenheit(c). Call them without creating an instance and log the converted values.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top