JavaScript Fundamentals / Classes

Static Methods and Properties

⚡️ Static Methods and Properties

Static members belong to the class itself, not to its objects.

  • Called using the class name

  • Cannot be accessed through instances


✅ Static Method (static)

  • Used for utility/helper functions

  • Does not need an object to run

  • Cannot access instance properties directly

Example:

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

console.log(MathUtil.add(5, 3)); // 8

❌ Invalid:

const m = new MathUtil();
m.add(5, 3); // Error: not a function

✅ Static Properties

  • Store shared data for all objects

  • Accessed using the class name

Example:

class Counter {
  static count = 0;

  constructor() {
    Counter.count++;
  }
}

new Counter();
new Counter();

console.log(Counter.count); // 2

✔ Every instance updates the same shared value


💵 Example: BankAccount with Static Interest Rate & Account Counter

class BankAccount {
  static interestRate = 0.05;   // ✅ static property (shared by all accounts)
  static totalAccounts = 0;     // ✅ tracks how many accounts are created

  constructor(owner, balance) {
    this.owner = owner;
    this.balance = balance;
    BankAccount.totalAccounts++; // ✅ updates shared static value
  }

  addInterest() {
    this.balance += this.balance * BankAccount.interestRate;
    return this.balance;
  }

  static setInterestRate(newRate) {   // ✅ static method
    BankAccount.interestRate = newRate;
  }

  static getTotalAccounts() {         // ✅ static method
    return BankAccount.totalAccounts;
  }
}

// --- Usage ---
const acc1 = new BankAccount("Bhaskar", 1000);
const acc2 = new BankAccount("Tisha", 2000);

console.log(BankAccount.getTotalAccounts()); // 2 ✅

acc1.addInterest();
console.log(acc1.balance); // 1050 ✅ (5% added)

BankAccount.setInterestRate(0.10); // ✅ update shared rate

acc2.addInterest();
console.log(acc2.balance); // 2200 ✅ (10% added)

✅ Static vs Instance

Feature

Static

Instance

Belongs to

Class

Object

Accessed by

ClassName.member

object.member

Shared across instances

✅ Yes

❌ No

Needs object to use

❌ No

✅ Yes