Class Syntax

What is a Data Structure?

Data structures are collections of values, the relationships among them, and the functions or operations that can be applied to the data.

Most of the data structures do not come 'for free' in JavaScript, we will need to implement our own with ES2015 Class syntax.

Class - a blueprint for creating objects with pre-fefined properties and methods. "establishing a pattern "

Simple Class Example

// upon instantiating a new Student object, firstName and
// lastName must be passed in, else they will be undefined.
class Student {
  constructor (firstName, lastName, year) {
    this.firstName = firstName;
    this.lastName = lastName;
    // shows that the argument names don't need to match
    // the class variable names.  The student object will
    // have a student.grade value, NOT a student.year.
    this.grade = year;
    this.tardies = 0;
    this.scores = [];
  // instance method:
    return `My full name is ${this.firstName} ${this.lastName}`
  markLate() {
    this.tardies += 1;
    return `${this.firstName} ${this.lastName} has been late ${this.tardies} times `
  // while you could access the scores array on a Student instance directly,
  // we assume that a good developer will interact with this provided interface.
  addScore(score) {
    return this.scores;
  calculateAverage() {
    let sum = this.scores.reduce((a, b) => {
      return a + b
    return sum / this.scores.length;
  // Class Method (note the capital first letter)
  static EnrollStudents (...students) {
    // send emails to all students in array of student
    // instances passed into function.
    return 'enrolling students'


To create an instance of Student:

let firstStudent = new Student("David", "Attenborough", 0)
let secondStudent = new Student("Axl", "Rose", 3)

this keyword has many different meanings in different contexts. When inside of the constructor, "this" refers to the individual instance of the class being created.

Instance Method - a method/function that works on individual instances of classes, but NOT on the class level.

Calling an instance method

// => My full name is David Attenborough

// => [92]

Class Methods

defines methods/functionality that is pertinent to classes but not necessarily specific instances. Syntax defines a class method with static keyword.

Calling a class method

Student.EnrollStudents([firstStudent, secondStudent])

another good example of a class method would be if you had a Point class, that had {x: 1, y: 3} shape and you wanted to calculate the distance between them.

Point.distance(pointA, pointB)


Immer.js State Library


JS Data Structure Notes