Algorithm Action: Class in JS

Image for post
Image for post
Photo by Luca Bravo 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 exploring using Object Oriented Programming in Javascript.

Technically, Javascript doesn’t support OO programming but in 2015 introduced the Class syntax. A Class is a blueprint for creating objects with predefined properties and methods.

We’ll be using the Class syntax to define data structures.

The class keyword creates a constant. (Keep in mind you cannot redefine it.) The method to create new objects must be called constructor and serves to give an opportunity for attributes to be defined on instantiation.

class Student { 
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}

To instantiate new objects from a class, use the new keyword:

let firstStudent = new Student("Nick", "Echevarria");let secondStudent = new Student("Yo", "Momma");

Then, you can define methods that provide functionality to a single instance of a student, in this case. They’re called instance methods. For example, Javascript arrays have the .push() instance method available to them. In the code below, a new Student has the markLate() function available to it, among others. A benefit to using instance methods is protecting given data from being directly amended by developers.

class Student { 
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.tardies = 0;
this.scores = [];
}
fullName() {
return `Your full name is ${this.firstName} ${this.lastName}`;
}
markLate() {
this.tardies += 1;
if (this.tardies >= 3) {
return "You're expelled!"
}
return `${this.firstName} ${this.lastName} has been late ${this.tardies} times.`
}
addScore(score) {
this.scores.push(score);
return this.scores;
}
calculateAverage() {
let sum = this.scores.reduce(function (a, b) { return a + b });
return sum / this.scores.length;
}
}

On the next article, we’ll be delving more deeply into class methods!

Written by

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store