Static Functions & Variables
Introduction
In JavaScript, classes can have static methods and static properties. Unlike instance members (which belong to objects created from the class), static members belong to the class itself.
Static members are useful when functionality is shared across all instances, or when the behavior does not depend on any particular object. Think of them as utilities or class-wide state, rather than per-object data.
Concepts
staticmethodsstaticproperties- Not accessible from instances
Concepts
Static Methods
- Declared using the
statickeyword. - Called on the class, not an instance of the class.
- Cannot access instance properties directly (because they don’t belong to a specific object).
class MathUtils {
static add(a, b) {
return a + b;
}
}
console.log(MathUtils.add(3, 7)); // 10
Static Properties
- Belong to the class, not its instances.
- Often used as counters or configuration values.
class Counter {
static count = 0;
constructor() {
Counter.count++;
}
}
const c1 = new Counter();
const c2 = new Counter();
console.log(Counter.count); // 2
Static + Instance Together
Static properties can track global state while each instance has its own private fields.
class BankAccount {
static accountCount = 0; // shared across all accounts
#balance = 0; // private to each account
constructor(owner, startingBalance = 0) {
this.owner = owner;
this.#balance = startingBalance;
BankAccount.accountCount++;
}
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
static getTotalAccounts() {
return BankAccount.accountCount;
}
}
const acc1 = new BankAccount("Alice", 100);
const acc2 = new BankAccount("Bob", 50);
console.log(acc1.getBalance()); // 100
console.log(BankAccount.getTotalAccounts()); // 2
Examples
class TemperatureConverter {
static celsiusToFahrenheit(celsius) {
return (celsius * 9) / 5 + 32;
}
static fahrenheitToCelsius(fahrenheit) {
return ((fahrenheit - 32) * 5) / 9;
}
}
console.log(TemperatureConverter.celsiusToFahrenheit(0)); // 32
console.log(TemperatureConverter.fahrenheitToCelsius(32)); // 0
console.log(TemperatureConverter.celsiusToFahrenheit(100)); // 212
Challenges
1. MathHelper with methods
- Create a MathHelper class with static methods add(a, b), subtract(a, b), and multiply(a, b).
💡 Show Answer
class MathHelper {
static add(a, b) {
return a + b;
}
static subtract(a, b) {
return a - b;
}
static multiply(a, b) {
return a * b;
}
}
2. Add pi
- Add a static property pi = 3.14159 to MathHelper and use it to calculate the circumference of a circle.
💡 Show Answer
class MathHelper {
static pi = 3.14159;
static circumference(radius) {
return 2 * MathHelper.pi * radius;
}
}
// Example usage:
const radius = 5;
console.log(MathHelper.circumference(radius)); // Output: 31.4159
3. Counter class
- Write a
Counterclass that has a static propertycount. - Each time you create a new instance, increase the count.
- Add a static method
getCount()to return it.
💡 Show Answer
class Counter {
static count = 0;
constructor() {
Counter.count++;
}
}
console.log(Counter.count); // 0
const c1 = new Counter();
console.log(Counter.count); // 1
const c2 = new Counter();
console.log(Counter.count); // 2
4. Add getCount
- Create a
Configclass with a static propertyappName = "MyApp". - Access it without creating an instance.
💡 Show Answer
class Config {
static appName = "MyApp";
}
// Accessing the static property without creating an instance
console.log(Config.appName); // Output: MyApp
5. User with totalUsers
- Create a
Userclass with a static propertytotalUsers. - Increment it in the constructor whenever a new user is created.
💡 Show Answer
class User {
static totalUsers = 0;
constructor(name) {
this.name = name;
User.totalUsers++;
}
}
const user1 = new User("Alice");
const user2 = new User("Bob");
console.log(User.totalUsers); // Output: 2
6. Validator.isEmail
- Write a Validator class with static methods:
- isEmail(str) → returns true if the string contains @
- isNonEmpty(str) → returns true if not an empty string.
💡 Show Answer
class Validator {
static isEmail(str) {
return str.includes('@');
}
static isNonEmpty(str) {
return str !== '';
}
}
// Example usage:
console.log(Validator.isEmail("test@example.com")); // true
console.log(Validator.isEmail("invalid-email")); // false
console.log(Validator.isNonEmpty("hello")); // true
console.log(Validator.isNonEmpty("")); // false
7. BankAccount.getTotalAccounts
- Create a
BankAccountclass that uses a static propertyaccountCountto track how many accounts exist. - Add a static method
getTotalAccounts().
💡 Show Answer
class BankAccount {
static accountCount = 0;
constructor() {
BankAccount.accountCount++;
}
static getTotalAccounts() {
return BankAccount.accountCount;
}
}
// Example usage:
console.log(BankAccount.getTotalAccounts()); // 0
const acc1 = new BankAccount();
const acc2 = new BankAccount();
console.log(BankAccount.getTotalAccounts()); // 2
8. TemperatureConverter
- Write a
TemperatureConverterclass with static methods for Celsius ↔ Fahrenheit conversion.
💡 Show Answer
class TemperatureConverter {
static celsiusToFahrenheit(celsius) {
return (celsius * 9) / 5 + 32;
}
static fahrenheitToCelsius(fahrenheit) {
return ((fahrenheit - 32) * 5) / 9;
}
}
9. randomId
- Add a static method randomId() to any class that generates a random number between
1000 and 9999.
💡 Show Answer
class Utils {
static randomId() {
return Math.floor(Math.random() * 9000) + 1000;
}
}
for (let i = 0; i < 1000; i++) {
console.log(Utils.randomId());
}
10. Log class
- Create a Log class with a static array
messages = []and a static methodadd(msg). - Every time you call
Log.add("something"), store it. - Add another static method
printAll()that prints all logs.
💡 Show Answer
class Log {
static messages = [];
static add(msg) {
Log.messages.push(msg);
}
static printAll() {
console.log(Log.messages.join("\n"));
}
}
// Example usage:
Log.add("First log message");
Log.add("Second log message");
Log.printAll();