Why you never truly use OOP: The sweet world of OOP syntactical sugar in JS
Photo by Benyamin Bohlouli on Unsplash
There are 2 famous paradigms in Javascript,
- OOP
- Functional Programming
While many languages run fully on OOP like C#, Java, etc., there are some like Python and JS in which we can freely work in both of these. But in Javascript, there is something very different going on behind the scenes.
1. Introduction of OOP in JS
Photo by ian dooley on Unsplash
As we all know, OOP has been very famous in programming since it was first coined by Alan Kay in the 1960s. It is a paradigm where everything is a class(just like a blueprint). We create objects from them. I came across this example somewhere that says that "the object is the ice cream freeze and the children of the objects are the ice creams 🍨themselves🍧🍧🍦🍦🍨."
2. The starting of OOP in JS
As it is so famous, OOP was introduced in Javascript. But the syntax was like this:
function Hero(name, level) {
this.name = name;
this.level = level;
}
// Adding a method to the constructor
Hero.prototype.greet = function() {
return `${this.name} says hello.`;
}
By seeing this example by the Digital Ocean Blog, we can easily notice that it is not a class at all, it is a function{😲😲😲}!! Classes were just written as normal functions back then, nothing special.
The ES2015(ES6) Update
Photo by Clément Hélardot on Unsplash
Now we use this syntax instead:
class Hero {
constructor(name, level) {
this.name = name;
this.level = level;
}
// Adding a method to the constructor
greet() {
return `${this.name} says hello.`;
}
}
At first sight, it seems a bit longer, but it is a more dev-friendly way to do it🌷. But behind the scene, it is just like the function one, it just adds a level of abstraction.
But why did they introduce it?
The answer is simple:-
- It is more dev-friendly for existing Javascript devs who use it.
- Devs coming from other programming languages are more familiar with this syntax.
Now we know, whenever we are writing a class in Javascript, we are just making a new function.
Thanks for reading! See you later😊😊!