Ok friends, let's start from the beginning right? What is object-oriented programming?
The idea behind Object-Oriented programming is that you create a blueprint for the look of your "object" and call it over and over again to do whatever you want with it. Sounds helpful right? Well, it is. Every time you want to use an object, you must first create it so that it exists, and then configure its properties to use the attached functionalities. These functionalities are known as 'methods'. For example, a User object may have a get user details (in the form of a method) functionality attached. As you can see in theory is a really clear idea.
When you start learning JavaScript the structure used to create "methods" are functions. In a function-based structure, most of the time, you will need to inject a dependency into the function for it to work. The problem with the above becomes that if you were to expand the number of functions, this can soon be quite tricky. Although initially, it seems much easier to write everything as functions and call it as needed. Actually, that was my game plan for me JS project. If you're new at JavaScript I would suggest starting written your code like this and ones you feel confident in your code to move to classes and JSOO. Just a suggestion!
But... why we need an Object-Oriented structure in JavaScript if a simple function would work just as fine? Well, when you think around classes rather than a series of interconnected functions, you are reducing the risk and scope of failure if it occurs. That's because every dependency injection creates a potential point of failure and as a programmer, we DON'T WANT OR NEED THAT!. Not only is it time-consuming to track functions, but it is even more time and mental cost if you have to do it a dozen times for exactly the same thing.
OOP in JavaScript can decrease the mental load and potential spaghetti relationships inherent in function-based programming. The more you learn and the more applications you build it's pretty easy to notice that JavaScript-based front-ends and back-ends apps grown in both size and complexity. When the structure of the code is easily understandable, it reduces the possibility of errors, making it easy to add new functions without breaking everything around it and that's the real beauty of JavaScript Object-Oriented Programming.
Thank you for reading! :)
Top comments (0)