JavaScript Functional Programming

Functional Programming in JavaScript:

JavaScript supports functional programming and functional programming represents data in our application.

Arrow functions:

const display = name => console.log(name)

Function as variable:


const person = {
name:"test data",
display(name){
console.log(name) }
}
person.display(person.name)

Function in array:


const person = ["Test one",
name => console.log(name),
"Test two",
name => console.log(name)]

person[1](person[0]) // Test one
person[3](person[2]) // Test two

Higher order functions, functions that either take or return other functions (i.e. more than one arrow):


const person = display => name => logger(name + !!!!!)

const showName = person(name => console.log(name))

showName("Test data") //Test data !!!!!

Notes:

  1. Functions can be saved, retrieved, or flow through your applications just like variables.
  2. Functional programming is a part of declarative programming.

Core concepts of functional programming:

  1. Immutablitiy: In functional programming, data is immutable. It never changes.
    let employee = {
    name: "Test",
    gender: "M",
    age: 23,
    grade: 'B'
    }
    
    const addGrade = (employee, grade) => ({...employee,grade})
    console.log(addGrade(employee,'A').grade) // A
    console.log(employee.grade) // 'B'
    
  2. Pure functions: A pure function is a function that returns a value that is computed based on its arguments.
    To create a pure function, try to follow the mentioned rules:
    – It should take in at least one argument.
    – It should return a value or another function.
    – It should not change or mutate any of its arguments.

    const addGrade = employee => ({
    ...employee,
    age: 30,
    grade: 'C'
    })
    
    console.log(addGrade(employee)) // {name:"Test", gender:"M", age:"30", grade:"C"}
    console.log(employee) // {name:"Test", gender:"M", age:"23", grade:"B"}
    
  3. Data Transformations: Functional programming is all about transforming data from one form to another. Two core functions with functional javascript – Arrays.map and Arrays.reduceFew useful javascript functions:

    Array.join :

    const fourWheelers = ["Car","Bus","Truck"]
    console.log(fourWheelers.join("-")) // Car-Bus-Truck
    

    Array.filter:

    const lmv = fourWheelers.filter(fourWheeler => fourWheeler === "Car")
    console.log(lmv) // Car
    

    Array.map:

    const fourWheelersName = fourWheelers.map(fourWheeler => '${fourWheeler} is Four wheeler.')
    
    console.log(fourWheelersName.join('/n'))
    /* Car Four Wheeler
    Bus Four Wheeler
    Truck Four Wheeler */
    
    console.log(fourWheelers.join('/n'))
    /* Car
    Bus
    Truck */
    
    const names = ["Test","Test1","Test2"]
    const editName = (oldName,newName,names) => names.map(name => (name === oldName)? newName : name)
    
    console.log(editName("Test","Test New", names)) //["Test New","Test1","Test2"]
    console.log(names) //["Test","Test1","Test2"]
    
    ** Object.keys is a method that can be used to return an array of keys from an object.
    
    

    Array.reduce/Array.reduceRight : These functions can be used to transform an array into any value including a number, string, Boolean, object or even a function.

    Reduce takes two arguments, a callback method and an original value.

    const scores = [23,3,12,14,34,1,25]
    const maxScore = scores.reduce((max,score) => (score > max)? score : max, 0)
    
    console.log(maxScore) //34
    

    ReduceRight works the same way as reduce, the difference is that it start reducing from the end of the array rather than the beginning.

    const values = [1,2,2,3,4,2,3,5,6]
    const distinctValues = values.reduce((newValues,value) => (newValues.indexOf(value) !== -1 ? newValues : [...newValues,value]),[])
    
    console.log(distinctValues)// [1,2,3,4,5,6]
    
  4. Higher-order functions: These are the functions that can manipulate other functions.
    const showTrue = () => console.log('Execute true function')
    const showFalse = () => console.log('Execute false function')
    const checkCondition = (condition, trueFn, falseFn) => (condition ? trueFn() : falseFn())
    
    console.log(checkCondition(true,showTrue,showFalse)) //Execute true function
    console.log(checkCondition(false,showTrue,showFalse)) //Execute false function
    
  5. Recursion: It is a technique that involves creating functions that recall themselves.
    const countdown = (maxvalue, showVal) => {
    showVal(maxvalue)
    return (maxvalue > 0) ? (countdown(maxvalue-1, showVal)) : maxvalue
    }
    
    countdown(10, value => console.log(value)); //10 9 8 7 6 5 4 3 2 1 0
    
    **Recursion should be used over loops but large amount of recursions can cause JavaScript errors.
    
  6. Composition: The goal of composition is to generate higher order function by combings simpler functions. It takes functions as arguments and return a single function.
    const name = person => appendSalutation(completeName(person))
    const name = compose(
    appendSalutation,
    completeName,
    )
    name(new Person())
    
    const compose = (...fns) => (args) => fns.reduce((composed,f) => f(composed), arg)
    

NOTE:
Follow these three simple rules to achieve functional programming :

  1. Keep data immutable.
  2. Keep functions pure – accept at least one argument, return data or another function.
  3. Use recursions over looping (wherever possible).
Advertisements

One thought on “JavaScript Functional Programming

  1. Pingback: Learn TypeScript – A Brief Overview for Beginners | Abhinav Rana Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s