Collating Functions Into a Class

Not all functions are made equal. A class is essentially a family of functions that are related to each other in some way. They may have commonality under a certain category. They may have similarities in what they do.

Whatever the case, sometimes, it’s just better to write your functions as a method in an object.

JavaScript itself is built around the idea of objects, even it if doesn’t immediately seem like it.

Here’s a quick low down on how classes work and 5 reasons why you should turn your functions into objects in JavaScript.

A quick primer on classes in JavaScript

A class in JavaScript is a type of function. Under normal circumstances, you’d usually write a function like this:

function catName(){
   console.log("Tibbers");
}

Or if you get fancy with arrow notation, a function may look something like this:

catName = () => console.log("Tibbers");

While that’s nice and all, what if you have a bunch of cat related functions? What if you want to attach these cat functions to an instance of something? What if you want to do it in a way that doesn’t require you to figure out and tell the code which instance you’re targetting your function against?

This is where classes come in handy.

A class generally has two parts to it — attributes and methods.

attributes defines the values of a particular instance of a class. methods do something to these attributes.

attributes are set in the constructor and methods generally come in the form of functions sitting inside the class.

So a class could look something like this:

class Cat{
  constructor(name, age, sound){   
      this.name = name; 
      this.age = age; 
      this.sound = sound; 
  }
  speak = () => console.log(this.sound);
  name = () => console.log('hello, my name is ' + this.name);
  age = () => console.log('I am ' + this.age);
}

And that’s basically 80% of what a class is in JavaScript. The other 20% deals with extensions and different ways to structure a class, which is out of scope for this story (but will be expanded further in the near future).

This is because the question we’re trying to answer is why you should collate your functions into a class rather than just leaving them as stand-alone bits of code.

Organized functions are more functional

The purpose of a function is to create a scope and boundaries for your code. When you write a function, you are essentially saying to the interpreter — hey, I’ve got a collection of things that are to be bundled and used together.

When you write a class, what you’re doing is creating another level of organization for your code.