Menu
Coddy logo textTech

Static Utility Methods

Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 33 of 56.

Static methods are utility functions that belong to the class itself rather than to instances of the class. They're useful for functions that don't require access to instance-specific data.

Let's create a class with a static utility method:

class MathHelper {
  // Define a static method
  static square(number) {
    return number * number;
  }
}

To call a static method, you use the class name directly:

// Call the static method without creating an instance
const result = MathHelper.square(5);
console.log(result); // 25

Notice we didn't need to create a new instance with new MathHelper(). Static methods are perfect for utility functions that perform operations without needing instance data.

challenge icon

Challenge

Create a class named StringUtils with a static method called capitalize that takes a string as an argument and returns the same string with the first letter capitalized. For example, if the input is "javascript", the method should return "Javascript". Export this class.

  1. Check if the string is empty: if (!str || str.length === 0) (Without this check an empty string could cause issues).
    1. !str checks for null/undefined (prevents errors)
    2. str.length === 0 checks for empty string (returns "" instead of crashing)
  2. Get the first character: str.charAt(0)
  3. Make it uppercase: .toUpperCase()
  4. Get the rest of the string: str.slice(1) (from position 1 to end)
  5. Combine: uppercase first character + rest of string

Cheat sheet

Static methods are utility functions that belong to the class itself rather than to instances. They don't require access to instance-specific data.

Define a static method using the static keyword:

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

Call static methods directly on the class without creating an instance:

const result = MathHelper.square(5);
console.log(result); // 25

Useful string methods for static utilities:

  • str.charAt(0) - gets the first character
  • str.toUpperCase() - converts to uppercase
  • str.slice(1) - gets substring from position 1 to end
  • !str || str.length === 0 - checks for null/undefined or empty string

Try it yourself

import { StringUtils } from './stringUtils.js';

// Don't modify the code below
console.log(StringUtils.capitalize("programming"));
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming