Category Archives: Javascript

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",
console.log(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 !!!!!


  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 => ({
    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 – and Arrays.reduceFew useful javascript functions:

    Array.join :

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


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

    const fourWheelersName = => '${fourWheeler} is Four wheeler.')
    /* Car Four Wheeler
    Bus Four Wheeler
    Truck Four Wheeler */
    /* Car
    Truck */
    const names = ["Test","Test1","Test2"]
    const editName = (oldName,newName,names) => => (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) => {
    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(
    name(new Person())
    const compose = (...fns) => (args) => fns.reduce((composed,f) => f(composed), arg)

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).

ES6 Basics

JavaScript Basics

1. Const : We cannot reset the value of constant variable.

const value = true;

2. let : with let keyword, we can limit the scope of a variable to any code block.

let topic = true;

3. Template String: with template string, we can create one string and insert the variable values by surrounding them with ${}

`${Salutation} ${firstName} ${lastName}`

4. Default Parameters: If a value is not provided for the argument, default value will be used. default argument can be any type.

function activity(name="Test"){

5. Arrow Function: With arrow functions, you can create the functions without using the function keyword.

var showName = (firstName,lastName) =>`${firstName} ${lastName}` 
var displayRole = role => {
  throw new Error('Role is required');
return `${role}` 

Note: Arrow function protect the scope of this, but not block the scope of this.

6. Transpiling ES6: Not all browser supporting ES6, so we need to convert it to ES5 code before running it in browser.One of the popular tool for transpiling  is Babel.You can transpile the javascript directly in the browser using inline Babel transpiler. You just include the browser.js file and any script with type=”text/babel” will be converted.

<script src=""> </script>
<script src="script.js" type="text/babel"></script>

Note: Transpiling approach is not a good idea for production because it will slow down the application.

ES6 Objects and Arrays:

1. Destructuring Assignment:

It allows us to locally scope fields within an object and to declare which values will be used.

  • Destructuring object having four keys and we only want to use two keys out of them.
var object= { salutation: "Mr.",
 firstName: "Test",
 lastName: "Data",
 role: "Developer"}

var {firstName,lastName} = object console.log(firstName,lastName); 
  • Destructuring incoming function argument:
var name = { firstName: "Test",
lastName: "Data" }

var showFirstName = ({firstName}) => console.log(`${firstName}`)
  • Assign the specific element value of an array to a variable name:
var [salutation] = ["Salutation","FirstName","LastName"]
console.log(salutation) //Salutation
var [,,lastName] = ["Salutation","FirstName","LastName"]
console.log(lastName) //LastName 

2. Object Literal Enhancement:

It the process of restructuring or putting back together.

  • with object literal enhancement, we can grab variables from global scope and turn them into an object.
var firstName = "Test"
var lastName = "Data"
var name = {firstName,lastName}
console.log(name) // {firstName:"Test", lastName:"Data"} 
  • with object literal enhancement, we can create object method.
var print = () =>{ console.log(`${this.firstName} ${this.lastName}`)}
var name = {firstName, lastName, print}
name.print() // Test Data 
  • while defining object methods, it is no longer necessary to use the function keyword
const newName = { firstName,
console.log(`${this.firstName} ${this.lastName}`);
 console.log(`salutation ${this.firstName} ${this.lastName}`);}

3. The Spread Operator:

It represents with three dots(…) that performs several different tasks.

  • With Spread Operator, we can combine the contents of arrays.
 var fruits = ["Mango","Grapes","Banana"]
 var drinks = ["Mazza","Rani","Tropicana"]
 var fruitDrink = [...fruits,...drinks] 
 console.log(fruitDrink.join(",")) //Mango,Grapes,Banana,Mazza,Rani,Tropicana

Note: Spread Operator creates the copy of the array and then do the specified process.

  • Spread Operator can be used to get some, or the rest, of the items in the array
 var [first,] = fruits
 console.log(rest.join(",")) //Grapes,Banana
  • Spread Operator can also be used to collect function arguments as an array.
function directions(...args){ 
var [start, ...remaining] = args
 var [finish, ...stops] = remaining.reverse()
 console.log(`drive through ${args.length} towns`)
 console.log(`start in ${start}`)
 console.log(`the destination is ${finish}`)
 console.log(`stopping ${stops.length} times in between.`) 
  • Spread Operator can also be used for Objects.
var employee = { name: "Test", age: "20" }
var department = " Admin"
var company = { ...employee, department }
console.log(company) // { name:"Test", age:"20", department:"Admin" }


It give us a way to make sense out of asynchronous behavior. It simplify back to a simple pass or fail.


ES6 introduces class declaration, but javascript still works the same way. Functions are objects and inheritance is handled through the prototype.

class Person
constructor(name,age){ = name this.age = age
 console.log('My name is ${} and I am ${this.age} years old.') }

Note: All types should be capitalized, due to that we will capitalize all class names.

  • We can create the new instance of the class using new keyword.
const personObj = new Person("Test data", 30);
 console.log(personObj.display()); //My name is Test data and I am 30 years old.

Simple Inheritance:

class UID extends Person{
 constructor(name, age, uniqueID){
 this.uniqueID = uniqueID 
 console.log('And ${this.uniqueID} is my uniqueID.') }

const personDtl = new UID("Test Data", 30, 1234567)
 console.log(personDtl.print()); //My name is Test data and I am 30 years old. And 1234567 is my uniqueID.

ES6 Modules:

JavaScript module is a piece of reusable code that can easily be incorporated into other javascript files.JavaScript module stored in separate file, one file per module.

  • Export multiple javascript object per module.

export const display(name) => log(name, new Date())
export const log(name, timestamp) =>
console.log(`${timestamp.toString()} : ${name}`)
  • export default, using this we can export single javascript object from a module.
const person = new Person("Test data", 26)
export default person
  • Modules can be consumed in other javascript file using import statement. Modules containing multiple export can take advantage of object destructuring.
import {display, log} from './script1'
import person from './script2'

display("display Test data details")
log("logging test data details")

  • we can scope modules variables locally under different variable names.

import {display as d, log as l} from './script1'

p("display test data details")  l("logging test data details")

  • we can import everything into single  variable using *.

import * as prsn from './script'


It is the module pattern that is supported by all versions of Node.js

  • with commonJS, object are exported using module.exports
module.exports = {display, log}
  • with commonJS, objects are imported using require function

const {display, log} = require('./script1')