JavaScript
  • JavaScript Introduction
  • JS Engine
  • V8 Engine
  • First-class function
  • Optimized Code
  • Call Stack & Memory heap
  • Single Thread
  • JavaScript RunTime
  • Nodejs
  • Context and Environment
  • Hoisting
  • Functions
  • Arguments
  • Variables
  • Scope
  • IIFE
  • this
  • call(), apply() and bind()
  • currying
  • Types
  • Type Coercion
  • Functions as Object
  • HOF (Higher Order Function)
  • Two pillars of Javascript
  • Closures
  • Prototypal Inheritance
  • OOP and FP
  • OOP
    • 4 principles of OOP
  • FP
    • Pure function
    • Imperative vs Declarative
    • Immutability
    • HOF and Closures
    • Currying
    • Partial Application
    • Compose and Pipe
  • Composition vs Inheritance
  • OOP vs FP
  • JS working
  • Promises
  • Async Await
  • ES5 - ECMAScript 2009
  • ES6 - ECMAScript 2015
  • ES7 - ECMAScript 2016
  • ES8 - ECMAScript 2017
  • ES9 - ECMAScript 2018
  • ES10 - ECMAScript 2019
  • ES11 - ECMAScript 2020
  • ES12 - ECMAScript 2021
  • JOB Queue
  • Promises Execution
Powered by GitBook
On this page

Was this helpful?

  1. FP

Pure function

A function has to always return the same output, given the same input and a function cannot modify outside by itself and no side effects.

Ex 1:
// side effect (data modified outside the function)
const array = [1, 2, 3, 4, 5];
function mutateArray(arr) {
    arr.pop();
}
mutateArray(array); // [1, 2, 3, 4];
mutateArray(array); // [1, 2, 3];

// no side-effect
const array = [1, 2, 3, 4, 5];
function removeLastItem(arr) {
    const newArr = [].concat(arr);
    newArr.pop();
    return newArr;
}
const newArr = removeLastItem(array);
console.log(newArr); // [1, 2, 3, 4];
console.log(array); // [1, 2, 3, 4, 5]; // original data is not affected
// immutable object

Ex 2:
// input --> output
function sum(num1, num2) {
    return num1 + num2;
}

function multiplyBy2(num) {
    return num * 2;
}
// the output is predectable

Every function can't be written as a pure function, because we have difference in data handling things.

It handles with,

  • 1 Task

  • Predictable

  • Immutable state

  • No Shared state

  • Pure,

  • return statement

  • Composable

Idempotence:

The function return the same output how many time you call the function, even it is contact with outside environment. The code output is predictable.

Ex 1:
function notGood(num) {
    console.log(num);
}
notGood(5); // 5

Ex 2:
Math.abs(-50); // 50

How many times we going to call, it is going to return the same output.

PreviousFPNextImperative vs Declarative

Last updated 5 years ago

Was this helpful?