Skip to main content

Javascript Conference: Functional- Map, Reduce and Filter vs Object Oriented Programming

What is functional programming? and why?

  • A programming paradigm
  • a coding style
  • a mindset
  • a sexy, buzz-wordy trend
  • safer, easier to debug/maintain
  • established community
Not functional: 
var name = “Anjana”; 
var greeting = “Hi, I’m ”; 
console.log(greeting + name); 
Output: “Hi, I’m Anjana”

Functional: 
function greet(name) { 
       return “Hi, I’m ” + name; 
greet(“Anjana”); 
Output: “Hi, I’m Anjana”

Avoid side effects use “pure” functions
Not pure: 
var name = “Anjana”; 
function greet() { 
      console.log(“Hi, I’m ” + name); 
}

Pure: 
function greet(name) {
     return “Hi, I’m ” + name; 
}

Use higher-order functions functions can be inputs/outputs
function makeAdjectifier(adjective) {
     return function (string) { 
                   return adjective + “ ” + string; 
 }; 
var coolifier = makeAdjectifier(“cool”); 
coolifier(“conference”); 
Output: “cool conference”

Don’t iterate use map, reduce, filter

What is Map-Reduce?






























# Map reduce
- 4 argument with loops.
- with help of reduce, we can transform array to object and vice-versa.
- reduce compound data into single data.

Avoid mutability use immutable data
Mutation (bad!):
var rooms = [“H1”, “H2”, “H3”]; 
rooms[2] = “H4”; 
rooms; => ["H1", "H2", "H4"]

No mutation (good!): 
var rooms = [“H1”, “H2”, “H3”]; 
Var newRooms = rooms.map(function (rm) {  
                if (rm == “H3”) { 
                      return “H4”; 
               }else { return rm; 
               } 
}); 
newRooms; => ["H1", "H2", "H4"] rooms; 
Output: ["H1", "H2", "H3"]
Persistent data structures for efficient immutability Mori, Immutable.js 
FP libraries for JS 
● Mori (http://swannodette.github.io/mori/) 
● Immutable.js (https://facebook.github. io/immutable-js/) 
● Underscore (http://underscorejs.org/) 
● Lodash (https://lodash.com/)
● Ramda (http://ramdajs.com/) 

What is Object-Oriented programming?

  • object-oriented JS gets tricky (prototypes? this?!?)
There are certain features or mechanisms which makes a Language Object Oriented like:
  1. Object
  2. Classes
  3. Encapsulation
  4. Inheritance
1. Object
An Object is a unique entity that contains property and methods. For example “car” is a real-life Object, which have some characteristics like color, type, model, horsepower and performs a certain action like drive. The characteristics of an Object are called as Property, in Object-Oriented Programming and the actions are called methods. An Object is an instance of a class. Objects are everywhere in JavaScript almost every element is an Object whether it is a function, arrays, and string.

Note: A Method in javascript is a property of an object whose value is a function. The object can be created in two ways in JavaScript:
a) Using an Object Literal
//Defining object
let person = {
    first_name:'Mukul',
    last_name: 'Latiyan',

    //method
    getFunction : function(){
        return (`The name of the person is 
          ${person.first_name} ${person.last_name}`)
    },
    //object within object
    phone_number : {
        mobile:'12345',
        landline:'6789'
    }
}
console.log(person.getFunction()); 
console.log(person.phone_number.landline);
Output:6789

b) Using an Object Constructor:
//using a constructor
function person(first_name,last_name){    
this.first_name = first_name;    
this.last_name = last_name; } //creating new instances of
person object
let person1 = new person('Mukul','Latiyan');
let person2 = new person('Rahul','Avasthi');   
console.log(person1.first_name);
console.log(`${person2.first_name} ${person2.last_name}`);

Output: Mukul

Output: Rahul Avasthi

c) Using Object.create() method: 
The Object.create() method creates a new object, using an existing 
object as the prototype of the newly created object.
// Object.create() example a

// simple object with some properties

const coder = {

    isStudying : false,

    printIntroduction : function(){

        console.log(`My name is ${this.name}. Am I 

          studying?: ${this.isStudying}.`)

    }

}

// Object.create() method

const me = Object.create(coder);

// "name" is a property set on "me", but not on "coder"

me.name = 'Mukul'

// Inherited properties can be overwritten

me.isStudying = 'True'
me.printIntroduction();
Output: My name is Mukul. Am I studying? : true

2. Classes Classes are blueprint of an Object. A class can have many 
Object, because class is a template while Object are instances of the 
class or the concrete implementation. Before we move further into 
implementation, we should know unlike other Object Oriented 
Language there is no classes in JavaScript we have only Object. To be 
more precise, JavaScript is a prototype based object oriented language, 
which means it doesn’t have classes rather it define behaviors using 
constructor function and then reuse it using the prototype. 
Note: Even the classes provided by ECMA2015 are objects.

Example:
Lets use ES6 classes then we will look into traditional way of defining 
Object and simulate them as classes.

// Defining class using es6
class Vehicle {
  constructor(name, maker, engine) {
    this.name = name;
    this.maker =  maker;
    this.engine = engine;
  }
  getDetails(){
      return (`The name of the bike is ${this.name}.`)
  }
}
// Making object with the help of the constructor
let bike1 = new Vehicle('Hayabusa', 'Suzuki', '1340cc');
let bike2 = new Vehicle('Ninja', 'Kawasaki', '998cc');
  
console.log(bike1.name);    // Hayabusa
console.log(bike2.maker);   // Kawasaki
console.log(bike1.getDetails());
Output:
Hayabusa
Kawasaki
The name of the bike is Hayabusa.

Traditional Way
// Defining class in a Traditional Way.
function Vehicle(name,maker,engine){
    this.name = name,
    this.maker = maker,
    this.engine = engine
};
  
Vehicle.prototype.getDetails = function(){
    console.log('The name of the bike is '+ this.name);
}
  
let bike1 = new Vehicle('Hayabusa','Suzuki','1340cc');
let bike2 = new Vehicle('Ninja','Kawasaki','998cc');
  
console.log(bike1.name);
console.log(bike2.maker);
console.log(bike1.getDetails());
Output: same as above
As seen in the above example it is much simpler to define 
and reuse object in ES6. Hence, we would be using ES6 in 
all our examples.

3. Encapsulation
The process of wrapping property and function within a 
single unit is known as encapsulation. Let’s understand 
encapsulation with an example.


//encapsulation example

class person{

    constructor(name,id){

        this.name = name;

        this.id = id;

    }

    add_Address(add){

        this.add = add;

    }

    getDetails(){

        console.log(`Name is ${this.name},Address is:
${this.add}`);

    }

}

  

let person1 = new person('Mukul',21);

person1.add_Address('Delhi');

person1.getDetails();

Output: Name is Mukul, Address is: Delhi


In the above example we simply create an person Object using the 
constructor and Initialize it property and use it functions we are not 
bother about the implementation details. We are working with an 
Objects interface without considering the implementation details.
Sometimes encapsulation refers to hiding of data or data 
Abstraction which means representing essential features hiding the 
background detail. Most of the OOP languages provide access 
modifiers to restrict the scope of a variable, but their are no such 
access modifiers in JavaScript but their are certain way by which we 
can restrict the scope of variable within the Class/Object.
// Abstraction example
function person(fname,lname){
    let firstname = fname;
    let lastname = lname;
  
    let getDetails_noaccess = function(){
        return (`First name is: ${firstname} Last 
            name is: ${lastname}`);
    }
  
    this.getDetails_access = function(){
        return (`First name is: ${firstname}, Last 
            name is: ${lastname}`);
    }
}
let person1 = new person('Mukul','Latiyan');
console.log(person1.firstname);
console.log(person1.getDetails_noaccess);
console.log(person1.getDetails_access());

Output:
undefined
undefined
First name is Mukul, Last name is Latiyan.

In the above example we try to access some property
(person1.firstname) and 
functions(person1.getDetails_noaccess) but it returns 
undefine while their is a method which we can access 
from the person object(person1.getDetails_access()), by 
changing the way to define a function we can restrict its 
scope.

4. Inheritance
It is a concept in which some property and methods of an 
Object is being used by another Object. Unlike most of the 
OOP languages where classes inherit classes, JavaScript 
Object inherits Object i.e. certain features (property and 
methods)of one object can be reused by other Objects.
Lets’s understand inheritance with example:


//Inhertiance example

class person{

    constructor(name){

        this.name = name;

    }

    //method to return the string

    toString(){

        return (`Name of person: ${this.name}`);

    }

}

class student extends person{

    constructor(name,id){

        //super keyword to for calling above class constructor

        super(name);

        this.id = id;

    }

    toString(){

        return (`${super.toString()},Student ID: ${this.id}`);

    }
}
let student1 = new student('Mukul',22);
console.log(student1.toString());
Output: Name of person Mukul, Student ID: 22

In the above example we define an Person Object with 
certain property and method and then we inherit the Person 
Object in the Student Object and use all the property and 
method of person Object as well define certain property and methods for Student.
Note: The Person and Student object both have same method 

i.e toString(), this is called as Method Overriding
Method Overriding allows method in a child class to have 
the same name and method signature as that of a parent 
class.
In the above code, super keyword is used to refer 

immediate parent class instance variable.


Comments

Popular posts from this blog

Javascript: Object to Array and Array to Object

Output: Final Array [ { mango: 1 }, { apple: 2 }, { banana: 3 }, { orange: 1 }, { watermelon: 1 }, { papaya: 1 } ] Output: Final Object { mango: 1, apple: 2, banana: 3, orange: 1, watermelon: 1, papaya: 1 }

Javascript: Callback and High Order Function

CALLBACK A callback is a function that gets invoked after an asynchronous result appears. a callback function is an async function argument. - Asynchronous code result handle using callback and promises. // callback  function function with argument  // ---argument :// if a function pass-through function as an argument, it is higher-order function. function needs to be called in order to execute. a callback is used when calling a function asynchronous  What is a Callback or Higher-order Function? A callback function , also known as a higher-order function, is a function that is passed to another function (let’s call this other function “otherFunction”) as a parameter, and the callback function is called (or executed) inside the otherFunction. A callback function is essentially a pattern (an established solution to a common problem), and therefore, the use of a callback function is also known as a callback pattern. High-order function is a function that takes ...

Javascript: Frontend - AngularJS

# FrontEnd Technologies: # Web (Internet) - Html, css framework (bootstrap, material design-> component based) Angular 2 - Single page application (fast). - Web application or website that interacts with the user by dynamically rewritting the current page rather than loading entire new pages from a server. - Can do asynchronous jobs. # Tools: - Typescript - VS code # MVVW (Model View ViewModel Pattern) -> two-way data binding - In angular, the controller (the C in MVC) is replaced by ViewModel (the VM in MVVM). # Typescript Programming Language Typescript (.ts) is imp in angular 2. - supersetup js - strictly typed program - can do class based oop - future programming language. - security maintain (TS code compile and run in js) - JS with additional features. # Data Binding - Controller and Views synchronize. Types: 1. Event -  eg: click, onClick, change 2. Property - eg: hide, show 3. 2-way binding - Reflect in view if changes in model- c...