DEV Community

Cover image for JavaScript: Procedural, Functional, or Object-Oriented?
Ben ltaif
Ben ltaif

Posted on • Edited on • Originally published at funkydev.io

JavaScript: Procedural, Functional, or Object-Oriented?

If you've ever come across JavaScript, you might have wondered about its true programming paradigm. Is it a procedural language? Functional? Object-oriented? The simple answer is: it's all of the above. Let's dive into these different aspects to demystify JavaScript's nature.

1. JavaScript as a Procedural Language

In the early days of JavaScript, its primary purpose was to add simple interactivity to web pages. In this context, it was often used procedurally. Here's what that looks like:

// Variable definition
let a = 5;
let b = 3;
let sum;

// Function to compute the sum
function add(x, y) {
    return x + y;
}

// Calling the function
sum = add(a, b);
console.log(`The sum of ${a} and ${b} is: ${sum}`);
Enter fullscreen mode Exit fullscreen mode

In the procedural style, operations are performed through sequences of instructions. Data can be passed from one function to another, but they are typically not encapsulated within the functions themselves.

2. JavaScript and Functional Programming

As JavaScript evolved, frameworks and libraries like React, Redux, and Lodash encouraged a functional approach. This emphasizes "pure" functions, avoiding mutable states and side effects.

const numbers = [1, 2, 3, 4, 5, 6];

// Filter even numbers
const evenNumbers = numbers.filter(num => num % 2 === 0);

// Double the even numbers
const doubleEvenNumbers = evenNumbers.map(num => num * 2);

console.log(doubleEvenNumbers); // [4, 8, 12]
Enter fullscreen mode Exit fullscreen mode

3. Object-Oriented Nature of JavaScript

JavaScript hasn't forgotten fans of object-oriented programming. It uses prototyping for inheritance, allowing each object to inherit properties and methods from another object.

// Define a "Dog" class
class Dog {
    constructor(name, breed) {
        this.name = name;
        this.breed = breed;
    }

    bark() {
        return `${this.name} says: Woof!`;
    }
}

// Create an instance of the "Dog" class
const rex = new Dog('Rex', 'German Shepherd');
console.log(rex.bark()); // "Rex says: Woof!"
Enter fullscreen mode Exit fullscreen mode

So, what is the true face of JavaScript? It's its ability to support these three paradigms that make it so powerful. As a developer, understanding these three facets of JavaScript will enable you to produce efficient, clean, and maintainable code, tailored to your project's specific requirements.

Top comments (6)

Collapse
 
pvivo profile image
Peter Vivo

Thanks for the JS we can use these paradigm. My advice if does not a really good reason, much better to separate the data and the code, which lead to smaller code parts which is work alone on the current data, so we does not need the bring whole jungle with gorilla when we will counting our bananas

But so many times we don't able to select that way, then we can choice some good old OOP patterns.

If we look forward and we would like to use decorator to class then we need to change to typescript.

Collapse
 
uncle_ben profile image
Ben ltaif

Thank you for your insights and suggestions on using JS. I wholeheartedly agree with your perspective on separating data from code. This approach not only ensures better modularity but also facilitates easier maintenance and scalability.

The OOP paradigm has stood the test of time, and I recognize that sometimes, given the project constraints, we have to stick with tried-and-true methods. If we're leaning towards using decorators for classes, I'm open to the idea of adopting Typescript. It provides static typing which can aid in catching errors early in the development process.

I'm at your disposal to discuss the best way forward. Please let me know if you'd like us to explore other options or delve deeper into certain aspects.

Collapse
 
pvivo profile image
Peter Vivo • Edited

I'm often face a problem when I try to categorized the use of generator function. That part is really underestimated in JavaScript. Maybe I can give the declarative programming title for it. Generator don't exactly functional paradigm, because generator is a long lived function with capability to handle a preserved process, like a game rule on one function.

for example this code is part of my POC poker game ( really old one around 2017 ) the full code is there: regexp Poker game with generator, as you see that time I used classes.

class PokerGame{
// tons of other stuffs
  *singleRound() {
    for( let deal of this.dealing() ) yield deal
    for( let flop of this.theBetRound( 'Flop' ) ) yield flop
    for( let flop of this.theFlop() ) yield
    for( let turn of this.theBetRound( 'Turn' ) ) yield turn
    yield this.theTurn(); 
    for( let river of this.theBetRound( 'River' ) ) yield river
    yield this.theRiver(); 
    for( let showdown of this.theBetRound( 'Showdown' ) ) yield showdown
    let winnerIs = []
    for( let score of this.showScores( winnerIs )) yield score
    let winner = this.theShowdown( winnerIs )
    yield winner    
    winner.chips += this.dealer.drawBet()
    for( let pause of Array(10)) yield winner
  }
}
Enter fullscreen mode Exit fullscreen mode

This code is unfinished, and don't implemented every poker game rule.

Collapse
 
dsaga profile image
Dusan Petkovic

Thanks for the article, I still have some trouble understanding the differences between procedural and functional programming, it generally seams like functional is the more declarative approach vs procedural is the more imperative ... :/

Collapse
 
uncle_ben profile image
Ben ltaif

Thank you for taking the time to read the article and share your thoughts. I understand that distinguishing between procedural and functional programming can be challenging. Your observation is spot on: functional programming is often viewed as a more declarative approach, while procedural is more imperative.

To help clarify further, I'm considering writing a detailed piece that delves deeper into this topic. I hope that it might offer more clarity for readers like you. Stay tuned, and I truly appreciate your engagement with the content.

Best regards,

Collapse
 
dsaga profile image
Dusan Petkovic

Thanks!