Functional Programming in JavaScript

In this article, we will learn about declarative pattern, pure function, Immutability and side effects.

What is Functional Programming

  • In computer science, functional programming is a programming paradigm or pattern (a style of building the structure and elements of computer programs)
  • Functional Programming treats computation as the evaluation of mathematical functions.
  • Functional Programming avoids changing-state and mutable data.

The above definition is taken from Wikipedia, now let’s try to understand the value and benefits of FP(functional programming) in this article.

Other Major programming paradigm or pattern

  • Procedural Programming
  • Object Oriented Programming
  • Meta Programming
  • Imperative Programming
  • Declarative Programming

Procedural Programming based upon the concept of the procedure call_, s_imply contain a series of computational steps to be carried out. Any given procedure might be called at any point during a program’s execution, including by other procedures or itself. Major procedural programming languages are COBOL, BASIC, C, ADA and GO

Object Oriented Programming based on the concept of objects, which contains data(attributes) and procedures(methods). This pattern is more closer to Functional Programming. Significant object-oriented languages include C++, Java, PHP, C#, Python, Ruby, Swift etc.

Meta Programming have the ability to treat programs as their data. It means that a program can be designed to read, generate, analyze or transform other programs, and even modify itself while running.

Imperative Pattern vs Declarative Pattern

  • Imperative Pattern focuses on describing how a program operates, it consists of commands for the computer to perform.
  • Declarative Pattern focuses on what the program should accomplish without specifying how the program should achieve the result.
  • Functional programming follows declarative pattern.
var books = [
  {name:'JavaScript', pages:450}, 
  {name:'Angular', pages:902},
  {name:'Node', pages:732}
];
/* Imperative Pattern */
for (var i = 0; i < books.length; i++) {
  books[i].lastRead =  new Date();
}
/* Declarative Pattern */
books.map((book)=> {
  book.lastReadBy = 'me';
  return book;
});
console.log(books);

  • In the above code snippet, we have added new attributes to each book(element) of books array and it has implemented in two different approaches.
  • First approach is with help of for loop, iterating over the array based on its length, then checking array index counter against array length and incrementing the index counter on each iteration. So, this is more like program/code is focusing or describing on how to operate for the desired output.
  • Second approach is with help of native JavaScript array method map() which takes function as argument and that function gets each element. So in this case code is not describing about how to operate but talking about what to accomplish and map() method behind the scene takes care of actual operation.

Mathematical Function or Pure Function

In mathematics, a function is a relation between a set of inputs and a set of permissible outputs with the property that each input combination is related to exactly one output.

In functional programming, these kinds of functions called pure function which only depends on the received input data to the function and does not alter the input data except the returned data.

Math.random() is not pure function because it always returns new value on each call.

Math.min(1,2) is an example of pure function which always returns same value with same set of inputs

Why Functional Programming

  • Its pure function, provides confidence of not changing things outside of its scope.
  • Its reduces the complexity, need not to worry about how it is doing it, focus will be only on what it is doing.
  • Ease of testing, because it does not depend on state of the application and result verification also will be easy.
  • It makes the code more readable.
  • Functional programming makes code easier to understand.

Examples of Functional Programming

Array Functions

In the above example, we are trying to filter only active meet-ups and we can see it can be achieved with two different approach. Here, second approach is Functional Programming where filter() method takes care of “how program operates” and program focuses only on input i.e. meetups array and care about output activeMeetupsFP but in first approach program cares about how to operate as well with for loop.

Similarly, below are other Array methods which help to achieve functional programming and reduce the complexity of the code.

  • find
  • map
  • reduce
  • every
  • some

Refer this github repo for the usage of above methods https://github.com/npatro/functional-programming/tree/master/code

Function Chaining

It’s a mechanism for invoking multiple method calls, each method returns an object, allowing the calls to be chained together in a single statement without requiring variables to store the intermediate results.

In the above code snippet, we want to print total members of all active meetups, considering 10% members might be duplicate.

Libraries to support FP

There are libraries which provide utility functions to make code more declarative.

  • RamdaJS
  • UnderscoreJS
  • lodash

Side Effects

Function or expression is said to have a side effect if it modifies some state of the program, which is outside of its own scope or has an observable interaction with its calling functions or the outside program besides returning a value.

let meetup = {name:'JS',isActive:true,members:49};
const scheduleMeetup = (date, place) => {
  meetup.date = date;
  meetup.place = place;
  if (meetup.members < 50)
    meetup.isActive = false;
}
const publishMeetup = () => {
  if (meetup.isActive) {
    meetup.publish = true;
  }
}
scheduleMeetup('today','Bnagalore');
publishMeetup();
console.log(meetup);

The program is having side effect because the actual responsibility of function scheduleMeetup is to add the dateand place of the meetup but it’s modifying the value of isActive as well on which some other functionpublishMeetup is depended upon and as a side effect the publishMeetup function will not have desired output because it’s input has changed in between. In the big program (real program), it’s really tough to debug the side effects.

Side effects are not always bad but we should be careful on when to have it.

Immutability

Immutability is important to make sure one function does not change the original data rather than should return new copy of the data after manipulation.

Like if Array and Objects are passing around multiple functions and we are not maintaining immutability then functions might not get the original copy of the array and object.

It is really hard to debug if something goes wrong in case of mutable object and array.

Mutability is not bad but it should be when to have it.

Immutable Libraries

JavaScript by-default does not provide anything to make the object and array Immutable. There are libraries which can help us to achieve the immutability.

  • Seamless-immutable
  • Immutable JS

Summary

The main aspects of Functional Programming is Pure and smaller Functions, Immutability and less Side Effects.

#javascript

What is GEEK

Buddha Community

Functional Programming in JavaScript
Nat  Kutch

Nat Kutch

1596848280

From imperative to declarative JavaScript

Introduction

In this post, I will explain why declarative code is better than imperative code.

Then I will list some techniques to convert imperative JavaScript to a declarative one in common situations, defining key terms along the way.

Why declarative ?

First, let’s define what declarative and imperative mean.

Declarative code is one that highlights the intent of what it’s doing.

It favors the “what” over the “how”.

In other words, the exact implementations actually doing the work (aka the “how”) are hidden in order to convey what that work actually is (aka the “what”).

At the opposite, imperative code is one that favors the “how” over the “what”.

Let’s see an example:

The snippet below perform two things: it computes the square of x, then check if the result is even or not.

// imperative way

	const x = 5;

	const xSquared = x * x;

	let isEven;

	if (xSquared % 2 === 0) {
	  isEven = true;
	} else {
	  isEven = false;
	}
view raw
block1.js hosted with ❤ by GitHub

Here, we can see that we finally get isEven after several steps that we must follow in order.

These steps describe “how” we arrive to know if the square of x is even, but that’s not obvious.

If you take a non-programmer and show him this, he might have a hard time deciphering it.

Now let’s see another snippet where I introduce a magic isSquareEven function that performs the two same things than the previous one.

#functional-programming #javascript #javascript-tips #programming #declarative-programming #function

Vincent Lab

Vincent Lab

1605017502

The Difference Between Regular Functions and Arrow Functions in JavaScript

Other then the syntactical differences. The main difference is the way the this keyword behaves? In an arrow function, the this keyword remains the same throughout the life-cycle of the function and is always bound to the value of this in the closest non-arrow parent function. Arrow functions can never be constructor functions so they can never be invoked with the new keyword. And they can never have duplicate named parameters like a regular function not using strict mode.

Here are a few code examples to show you some of the differences
this.name = "Bob";

const person = {
name: “Jon”,

<span style="color: #008000">// Regular function</span>
func1: <span style="color: #0000ff">function</span> () {
    console.log(<span style="color: #0000ff">this</span>);
},

<span style="color: #008000">// Arrow function</span>
func2: () =&gt; {
    console.log(<span style="color: #0000ff">this</span>);
}

}

person.func1(); // Call the Regular function
// Output: {name:“Jon”, func1:[Function: func1], func2:[Function: func2]}

person.func2(); // Call the Arrow function
// Output: {name:“Bob”}

The new keyword with an arrow function
const person = (name) => console.log("Your name is " + name);
const bob = new person("Bob");
// Uncaught TypeError: person is not a constructor

If you want to see a visual presentation on the differences, then you can see the video below:

#arrow functions #javascript #regular functions #arrow functions vs normal functions #difference between functions and arrow functions

Giles  Goodwin

Giles Goodwin

1603176407

The real reason why JavaScript has arrow functions

Nowadays, all my code is based on the use of arrow functions. If you are still not using them yourself, then don’t be ashamed of who you are. That’s your parent’s job. Instead, find about all the benefits that you can get by using arrow functions like the cool kids.

This is an example of arrow function and the same code written traditionally:

const arrowFunction = (arg1, arg2) => arg1 + arg 2;

const traditionalFunction = function(arg1, arg2) {
  return arg1 + arg2;
};

You may notice that the code is shorter and that there is an arrow. Everything before the arrow is arguments of the function and everything after the arrow is always returned as the result of the function.

If you need a function that contains multiple statements you can still do this:

const arrowFunction = (arg1, arg2) => {
  const result = arg1 + arg2;
  return result;
};

#javascript #js #functional-javascript #functional-programming #javascript-tips

Tia  Gottlieb

Tia Gottlieb

1596300660

Functional Programming Series (2): What Is a Monoid?

For those interested in functional programming, I’ll talk about monoids and why they’re very important to understand ahead of time.

Don’t get confused: This isn’t monad — it’s monoid. I’m pretty sure you already know of monoids and you use them almost every day — you just didn’t know the term for them.


Prior to Reading

This is a series on functional programming, so you might not understand what this article is going to talk about if you haven’t read the previous posts.

You can check out other posts related to this topic


Identity Function

Let’s assume there’s a function named identity that takes A and returns A.

const identity: <A>(a: A): A => a;

interface Student {
  name: string;
  age: number;
}
identity<number>(3) // 3
identity<string>('hello') // hello
identity<Student>({ 
  name: 'Bincent',
  age: 5
}); // { name: 'Bincent', age: 5 }

In functional programming, this useless function (seems useless) is an important factor for many other concepts (such as monoids) that we’re about to talk about.

Image for post

Basically, a monoid is a set of elements that holds the rules of the semigroup and the identity-element rule.

If S is a set of elements, a is a member of S, and · is a proper binary operation, a·e = e·a ∈ S must be satisfied to be a monoid.

Identity: a ∈ S, a·e = e·a = a ∈ S

Some documentation calls this using the number 1 and the any alphabet in subscript — for example, 1x referring to the identity on the variable x. Or some documentation uses just a single alphabet letter, such as or e.

That’s all there is to know about monoids, let’s practice with some simple examples.

#typescript #programming #functional-programming #javascript #coding #function

Let’s Talk Functional Programming

Most of what I will discuss in this article is knowledge accumulated from reading, “Functional Programming in JavaScript”, by Luis Atencio. Let’s dig right in…

What is functional programming?

In simple terms, functional programming is a software development style that places a major emphasis on the use of functions. You might say, “Well, I already use functions daily, what’s the difference?” Well, it’s not a matter of just applying functions to come up with a result. The goal, rather, is to abstract control flows and operations on data with functions in order to avoid side effects and reduce mutation of state in your application.

#programming #javascript #functional #web-development #functional-programming