There are a couple of programming paradigms but I’ll focus on two of the popular especially working with JS, Functional Programming and Object Oriented Programming(OOP).
In functional programming, we separate the data and the functions from each other. With this method, we can clearly define data and the functions.
var numberOfSomething = 7 // These are the datas or states
var price = 100
function calculateCost(){ // An this is the function definition
console.log(numberOfSomething * price)
}
calculateCost()
Functional programming is beginner friendly, easy to understand and easy to use. Mostly used to perform pure calculations with simple inputs and when we need to avoid side effects or state changes.
On the other hand, if we are working on more complex systems with multiple interactions and entities, it’s better to follow OOP to create reusable components to avoid code repeating and more efficiency. In OOP, we keep the data and methods together in an object, moreover, we create reusable base classes to create more efficient apps.
const cost = { // This is our Object definition including our data and functions
numberOfSomething: 7,
price: 100,
calculateCost: function() {
console.log(this.numberOfSomething * this.price) // This keyword refers to cost object
}
}
cost.calculateCost()
In JS. we can also assign functions to object, we call them methods.
So if we need to calculate the cost for separate things with the same method, we need to rewrite the same object with updated data but it’s not going to be an efficient way to build. So in this case, we have class in JS. We can create a class for out cost calculations and use the same object to calculate the cost without creating the same object over and over again.
class Cost { // We use Class keyword to create a new class and the class name starts with a Uppercase
constructor(price, numberOfSomething){ // Constructor accepts as many parameters as needed
this.price = price
this.numberOfSomething = numberOfSomething
}
calculateCost() { // And we can define our functions which means methods, no need to use function keyword, we just need the method name
console.log(this.price * this.numberOfSomething)
}
}
const iphoneCost = new Cost(799, 3) // We initialize as many new objects by using our class blueprint simply using new keyword
const ipadCost = new Cost(399, 12)
iphoneCost.calculateCost()
ipadCost.calculateCost()
In React specific, we can both use Functional Programming and OOP but with the latest updates on React, functional components and hooks became today’s standart and with that, React focused on functional programming paradigm. But if we like to follow OOP approach, we can still use Class components. Also we can mix&match functional and class components in React.