Algorithm Action: Class in JS Part 2

Nicholas Echevarria
2 min readJan 8, 2021
Photo by Markus Spiske on Unsplash

Algos, algos, algos: the cornerstone of a competent software engineer. This is why I’m compiling all my research and work on the topic in a series of articles titled Algorithm Action.

Today, we’re wrapping up our exploration of Object Oriented Programming in Javascript.

Class Methods

In part one, I covered how Javascript handles Object Oriented Programming without actually being an OOP-based programming language. We covered classes, constructors, and instance method. Now, we’re diving a little more deeply into class methods.

What are they?

Also known as static methods, class methods are used only with entire classes rather than instances of that class. Let’s take a look at what MDN has to say:

The static keyword defines a static method or property for a class. Static members (properties and methods) are called without instantiating their class and cannot be called through a class instance. Static methods are often used to create utility functions for an application, whereas static properties are useful for caches, fixed — configuration, or any other data you don’t need to be replicated across instances.

Thinking of static methods as “utility” methods is a good way to determine what should be an instance method versus what should be a static method or property. For instance, check the bolded static method at the bottom of the Student class:

class Student { 
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.tardies = 0;
this.scores = [];
}
// instance method
fullName() {
return `Your full name is ${this.firstName} ${this.lastName}`;
}
// instance method
markLate() {
this.tardies += 1;
if (this.tardies >= 3) {
return "You're expelled!"
}
return `${this.firstName} ${this.lastName} has been late ${this.tardies} times.`
}
// instance method
addScore(score) {
this.scores.push(score);
return this.scores;
}
// instance method
calculateAverage() {
let sum = this.scores.reduce(function (a, b) { return a + b });
return sum / this.scores.length;
}
// class method (a "utility" method)
static enrollStudents(...students) {
// send an email to each student in the list
}

}

While there’s no actual code for it, the use case for a static method is clear.

While class methods won’t be used frequently in conquering data structures, it’s important to know about them generally speaking. We will, however, be using Class syntax to create our data structure and to fill it in with some default values.

Algorithm Action will continue to delve deep, starting with Singly Linked Lists! I hope this two series is helping you out!

--

--