Functional vs.

Object-Oriented Programming

Object-Oriented

Uses self contained pieces of code, (classes in other OOP languages) in JavaScript, functions disguised as classes. Techniques used are Inheritance, Polymorphism, and Encapsulation.

Functional

Functional programming uses pure functions and avoids side effects, meaning if you put the same input in, you will always get the same output.

OOP Example


function User(name, email){
  this.name = name;
  this.email = email;
}

User.prototype.greeting = function(){
 return `Hi I am ${this.name}. 
  Please email me at ${this.emeil}`
}

class User{
 constructor(name, email){
  this.name = name
  this.email = email
 }

 greeting(){
  return `Hi I am ${this.name}. 
   Please email me at ${this.emeil}`  
 }
}


const jon = new User('jon', 'jon@me.com')

Functional Example



function createUser(name, email){
  const obj = {}
  
  obj.name = name;
  obj.email = email;
  obj.greeting = function(){
   return `Hi I am ${this.name. 
    Please email me at ${this.email}}`
  }
  
}

let jon = createUser('jon', 'jon@me.com')

OOP uses

Imperative Pattern

What is Imperative pattern?

Imperative Pattern focuses on describing how a program operates. It has commands for the computer to perform. 

let books = [
  {name:'JavaScript', pages:450},
  {name:'Angular', pages:902},
  {name:'Node', pages:732}
];


for (var i = 0; i < books.length; i++) {
  books[i].lastRead =  new Date();
}

Example:

 

 

Functional uses

Declarative Pattern

Declarative pattern?

Declarative Pattern focuses on what the program should accomplish without specifying how the program should achieve the result.


let books = [
  {name:'JavaScript', pages:450},
  {name:'Angular', pages:902},
  {name:'Node', pages:732}
];

let newBooks = books.map((book)=> {
  book.lastRead = new Date()
  return book;
});


Example:

Great Resource

(oldie but a goodie)

Master the JavaScript Interview: What is Functional Programming?

Functional Programming

By JD Richards