Day 427

Chep
5 min readMay 24, 2023

--

Today I will be explaining the difference between Static vs Instance Methods in Javascript.

So a little background I like to think of classes in Javascript as factories for making objects. So you could say an object is an instance of a class in the same way I am an instance of the human species. Another example would be how the The Mandibles is an instance of a book.

Static methods allow us to call a function directly on a class, rather than on an object created by the class. This opens up a world of possibilities, from utility methods to alternative constructors. Instance methods on the other hand use a specific instance of the class that we’re working with. I’ll start with an example of an instance method.

Imagine we have a class called Recipe. It represents various delicious recipes with their ingredients and instructions. Inside this class, we have an instance method called showNextInstruction. Take a look at this code snippet:

class Recipe {
constructor(name, ingredients, instructions) {
this.name = name;
this.ingredients = ingredients;
this.instructions = instructions;
this.currentStep = 0;
}
// name is a string
// ingredients and instructions are arrays

showNextInstruction() {
if (this.currentStep >= this.instructions.length) {
console.log("All instructions have been completed.");
return;
}

const nextStep = this.instructions[this.currentStep];
this.currentStep++;
console.log(nextStep);
}
}

const mimosas = new Recipe(
'Mimosas',
['Champagne', 'Orange juice'],
['Pour champagne into a glass.', 'Add orange juice.']
);

mimosas.showNextInstruction(); // Expected output: Pour champagne into a glass.
mimosas.showNextInstruction(); // Expected output: Add orange juice.
mimosas.showNextInstruction(); // Expected output: All instructions have been completed.

Notice that within our showNextInstruction method, the this keyword is pointing at the specific instance of the class that we're working with. So by calling this.instructions on the recipe object, we're able to access the instructions specifically for our delightful Mimosas recipe here. Let’s break it down.

To use the showNextInstruction method, we first create an instance of the Recipe class. We call the method on the object itself, and it guides us step by step through the instructions.

But now, let’s shift our focus to static methods. Behold, the Coffee class!

class Coffee {
static listRoasts() {
return ['Light', 'Medium', 'Dark'];
}
}

console.log(Coffee.listRoasts());

This method doesn’t rely on a specific Coffee to be called. I don’t have to create a latte, or a cappuccino, or an americano to use this method. I can simply call the listRoasts() method on the Coffee class itself and it will return the various roasts.

So when to use static methods? One common use case is utility methods. These methods perform logic or provide information related to the class domain but aren’t tied to a specific instance of that class. I’ll give you two more quick examples. JavaScript contextualizes mathematical functions under the Math constant.

Math.round(30.4):
answer: 30
The Math.round() function is used to
round a number to the nearest integer.

Math.max(1, 4, 10, 7):
answer: 10
The Math.max() function is used to find
the maximum value among the given numbers.

As you can see these Math methods are utility methods that help us with complex mathematical operations. Going back to our Coffee class, we could have a utility method like convertWaterGramsToOunces. It doesn’t depend on specific instance variables but provides a handy conversion for coffee enthusiasts.

class Coffee {
static convertWaterGramsToOunces(grams) {
return grams * 0.035;
}
}

console.log(Coffee.convertWaterGramsToOunces(200)); // Expected output: 7

Our convertWaterGramsToOunces static method takes in a number of grams for the parameter and converts it to ounces. In this case, the method convertWaterGramsToOunces is called with the argument 7, which will be assigned to the parameter. convertWaterGramsToOunces is a quick and useful function if you ever find yourself missing a scale while brewing your perfect cup of coffee. So when it comes to using static methods, remember we don’t need to create an instance of the class. We can simply call the method directly on the class itself.

Alternate constructors are another reason to embrace static methods. They allow us to generate objects with different parameters based on the data at hand. Using factory analogies again you can think of alternate constructors as factory functions for creating specific instances of a class. For example, let’s say we have a TeamMember class. We want to create a manager and a few employees. Using the standard constructor would lead to repetitive code, which we want to avoid. That’s where an alternate constructor, a static method, comes to the rescue.

class TeamMember {
constructor(name, role) {
this.name = name;
this.role = role;
}

static createEmployee(name) {
return new TeamMember(name, 'employee');
}
}

const manager = new TeamMember('John Doe', 'manager');
const employee = TeamMember.createEmployee('Jane Smith');

console.log(manager);
console.log(employee);

Look at this createEmployee static method. It only works to create employees not managers. It takes the employee’s name as an argument inside the parameter and returns a new TeamMember object with the role set as ‘employee.’ With this approach, we can create employees quickly and efficiently, without repetitive code.

So instead of having to write this.

const teamMember1 = new TeamMember("Sloan", "manager")
const teamMember2 = new TeamMember("Chad", "employee")
const teamMember3 = new TeamMember("Karen", "employee")
const teamMember4 = new TeamMember("Michelle", "employee")

We can just call the alternate constructor TeamMember which is a static method.

const teamMember1 = new TeamMember("Sloan", "manager")
const teamMember2 = TeamMember.createEmployee("Chad")
const teamMember3 = TeamMember.createEmployee("Karen")
const teamMember4 = TeamMember.createEmployee("Michelle")

So let’s recap to make sure we understand the distinction between instance and static methods:

Instance methods, like enchanted spells woven into the very fabric of our objects, bring forth the essence of individuality and purpose. With the power of the this keyword, they channel the unique attributes and behaviors of each object, breathing life into their existence. These methods serve as loyal companions, tirelessly working to fulfill the needs and desires of their associated instances. They are the threads that connect us to our objects, allowing us to manipulate, query, and transform their state with precision and grace. Through instance methods, we wield the ability to shape our objects' destinies and orchestrate the symphony of our code's functionality.

On the other hand, static methods, like luminous gems embedded within our code, bestow upon us the sorcery of versatility and resilience. They transcend the boundaries of individual objects, reaching beyond the confines of instance variables. When summoned upon the class itself, they bring forth utility methods and alternate constructors, providing organization and abstraction to our codebase. These hidden gems enhance our creations, imbuing them with additional functionality. Static methods grant us the flexibility to perform tasks that are not bound to specific instances, empowering us to build robust and flexible codebases. As we embrace the power of static methods and the enchantment of instance methods, we embark on a journey to manifest our vision of a decentralized and empowered digital realm, where every sovereign individual reigns supreme over their technological destiny. If they put in the work to write code of course ;D

And if all that was a bit too dramatic for some Javascript concepts here is a nice visual to look at which drills down the points I just covered.

5/23/23

Conor Jay Chepenik

--

--

Chep
Chep

Written by Chep

I've decided to write everyday for the rest of my life or until Medium goes out of business.

No responses yet