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.

Efficient and effective code is based on how well you can organize and communicate ideas in your programming language. When it comes to JavaScript, it’s easy for things to fall into a state of disorganization because of how relaxed it is as a programming language. 

You can write the same thing in multiple ways and it’ll still work. 

So the issue becomes an organizational one.

A function is an organizational methodology. A class just takes it a step further. 


Everything is an object

JavaScript is built on the idea of prototypes. What this means is that your code starts off as a single global scope that breaks down into smaller ring-fenced scopes, which can also break down in smaller scopes.

In diagram form it can look something like this:

attributes are inherited from parent to child. 

So when an object further down the chain wants something, it asks it’s parent object for it. If the parent doesn’t have it, the process continues up the chain until either one is found or undefined is returned. 

The thing with stand-alone functions is that it doesn’t have this ability because there is no chain for it to traverse for attributes. A function essentially sits at the window object and only has access to global scopes.

Why not just set everything as a global scope?

Because you don’t need every value you encounter to hang around. Once you declare a global scope in JavaScript, most of the time it doesn’t go away. If the data attached to that variable is rather large, it can reduce your application’s speed and ability to process things efficiently due to a lack of memory space. 


Protection against mutations

There’s a misconception that when you want to protect your variables against mutations, you need to stop it from changing.

However, mutation is about the shape of your variable — not the actual variable itself.

The value of the variable can change, just not the shape.

For example, take a look at the following object.

Tibbers = { name: "Tibbers", type: "cat", color: "ginger" }

This object in its current form is not protected against mutations. Why? Because you can just do this:

Tibbers.owner = "Aphinya";

This changes the shape of the object by adding another key-pair value. However, this can be prevented if the object Tibbers is instantiated with a class.

You can try and pass it a new value but it won’t do anything. 

Why is this important?

When the shape of your data is immutable, it creates a high level of certainty in how your code functions — turning it more functional in approach and reducing potential unexpected side effects when the object is consumed elsewhere. 


containerized modularity

Anything has the potential to be modular. Useful modularity is to do with how tightly ring-fenced your logical reasoning is around a particular idea.

Anyone can say their code is modular. You can put your code inside a function and say its modular.

However, when using a class, you’re systematically approaching modularity with an enforced structure and cohesive ideology. In essence, you are containerizing your code and collating your functions in a way that turns them into a family of related features.

Because that’s what methods in a class are — a set of functions grouped together based on what they do.


JavaScript is object-oriented

JavaScript by design is a multi-paradigm language with dynamic typing. Being multi-paradigm means that it’s not restricted to just a single ideology of structuring the way you write your logic.

This means that JavaScript is not purely functional, nor is it purely object-oriented. It is a language that lets you mix and match methods of thinking and arranging your code, giving you the flexibility to adapt to the requirements and conditions of your logic rather than the other way around.

The object-oriented design feature in JavaScript follows a prototype methodology, which means that you can use classes for inheritance. It uses functions as methods and objects constructors, which means that collating your features and functionality into a class is a way to logically arrange your thoughts and translation of business rules in a way that is interlinked and related to one another.


Final thoughts

Not everything has to be a class, but there is a lot of code written that should be.

Collecting related functions into a class and turning it into an explicit object-oriented pattern can also help increase the modularity of your code and it’s reusability long term.

When it comes to debugging, having clear boundaries and established relationships between different pieces of code can also help you identify problem areas and blips in logic faster than trying to trace scopes and inheritances.

Thank you for reading!

If you’ve found this article helpful in any way, please share it with your network to help spread the word about my blog 🙂

Comments

0 comments