What is the difference between OOP and functional programming? To figure this out we will be writing a small factorial website calculator. The first approach uses functional programming, the second one OOP.

Introduction

Before we get started with coding I want to give you a quick introduction to object-oriented and functional programming.

Both are programming paradigms differing in the techniques they allow and forbid.

There are programming languages that only support one paradigm e.g. Haskell (purely functional).

As well as languages that support multiple paradigms such as JavaScript, you can use JavaScript to write object-oriented or functional code or even a mixture of both.

Setup

Before we can dive deep into the differences between these two paradigms we need to set up the project.

For that we first create all the files and folders we need like this:

$ mkdir func-vs-oop
$ cd ./func-vs-oop
$ cat index.html
$ cat functional.js
$ cat oop.js

I’m using the cat command because it works both on Linux-systems and Windows Powershell.

Next up we need to create a simple form for the factorial calculator inside the index.html.

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
  <script src="functional.js" defer></script>
</head>
<body>
  <div class="container mt-5">
    <div class="container mt-3 mb-5 text-center">
      <h2>Functional vs OOP</h2>
    </div>
    <form id="factorial-form">
      <div class="form-group">
        <label for="factorial">Factorial</label>
        <input class="form-control" type="number" name="factorial" id="factorial" />
      </div>
      <button type="submit" class="btn btn-primary">Calculate</button>
    </form>
    <div class="container mt-3">
      <div class="row mt-4 text-center">
        <h3>Result:</h3>
        <h3 class="ml-5" id="factorial-result"></h3>
      </div>
    </div>
  </div>
</body>
</html>

To give this form a better look and feel we use bootstrap as a CSS-Framework. If you display this HTML in the browser it should look like this:

Image for post

factorial calculator

Currently, this form won’t do anything.

Our goal is to implement a logic where you can enter a number up to 100. After clicking the “Calculate”-button it should show the result in the result-div. We will implement this both in the object-oriented way and the functional way.

#web-development #oop #javascript #programming #functional-programming

Functional Programming vs OOP in JavaScript
3.20 GEEK