Functional Programming : Declarative

Functional Programming : Declarative

Declarative programming is pattern which executes the codes without disclosing it's implementation.

In layman terms "Doing without doing".

Assume the following imperative example :

ip.png

If I were to explain the code to a kid then i would explain it in this way :

const number = [0,1,2,3,4,5];
  • Declare the number for which you want to find out the cube of and store it in "number" array.
  • "const" is a keyword and variable defined in "const" cannot be redeclared.
const findcube = function(number) { }
  • number is a parameter of the function findcube. Basically we are instructing the machine to find out the cube of the numbers declared.

Inside the block

{ } -> is known as Block.

Block Start

const cube = [ ];
  • The output of the cube of the numbers would be returned in an array. [ ] -> stands for an array
for (let i = 0; i < number.length; i++)
  • The machine is being instructed to run in circles till it finishes finding out the cube of the number.
  • let i = 0 initialises or begins the loop at i = 0
  • i < number.length The code will run till there's no number left to find out the cube for. number.length represents the length of the number array

  • i++ is the increment operator. It tells the after each increment.
{
   cube[i] = Math.pow(number[i], 3);
 }
  • cube[i] is the output array.
  • Math.pow is the operator which would operate upon the number[i] array and raise it up to the power 3.
return cube;
  • It returns the cube of the argument.

Block ends

Outside Block

console.log(findcube(number));
  • This logs the value of the findcube function.

Output in the console : Screen Shot 2022-03-23 at 12.48.24 PM.png

At every step, the implementation of each and every line was described.

How about programming using declarative function without disclosing it's implementation.

Declarative Programming

Dp.png

Map function : map( )

  • It calls a function once for each element in an array
number.map

Since number is an array, therefore

[ ].map( ) -> It's used to transform an array

The entire structure of the code has changed using Array.map( ) . The programmer doesn't have to bother about the loops. A loop signifies imperative control structure. A loop keeps changing the code. However, the crux of functional programming is immutability or statelessness, where the probability of breaking the global state is minimal.

Arrow Functions or Lambda Functions

The previous code could be written using the Lambda functions or Arrow functions as per ES6 JS.

ARL.png

num => Math.pow(num, 3)

is similar to

function num( ) {
  return Math.pow(num,3)
}

Thanks for reading.

#JavaScript

Did you find this article valuable?

Support Devkant Swargiary by becoming a sponsor. Any amount is appreciated!