Functional Programming With JavaSript Basics and Getting Started

Jamilur Rahman
React A-Z
Published in
2 min readOct 9, 2019
Functional programing / lambda function

React and other JavaScript frameworks are heavily based on functional programming. You may already have used or written functional code without realizing it. If you have mapped or reduced an array then you have already used functional programming techniques. React, Flux and Redux are heavily based on functional programming. So you have to be familiar with functional programming techniques in order to take full advantage of React, Flux and Redux.

What is functional?

JavaScript supports functional programming as it treats functions as a first-class citizen. This means that JavaScript treats functions as variables. A function in JavaScript has the same characteristics as a variable. ES6 add more features to a function to beef up functional programming such as Arrow function, Promises, the Spread operator. Functional programmers write a lot of small functions and arrow functions make it easier to track. Moreover, as JavaScript treats functions as variable we can add function in an Object. For example:

Similarly, we can add functions in an array and send functions as an argument of another function. ES6 also allows functions to be returned from another function.

Imperative vs Declarative Programming

Imperative programming is a coding style where the main focus of the developer is to define or tell the application how it should be done. On the other hand, developer following declarative approach tells or designs the application based on the concept of what should happen. Let us see how we can solve a problem in each approach. To do that let us define a function that makes a string URL friendly. Here our problem is to remove spaces from the string as URL does not respond to space in URL.

Here we are using “string.replace” along with a regular expression to replace all
instances of spaces with hyphens. Using string.replace is a way of describing what is supposed to happen: spaces in the string should be replaced. The details of how spaces are dealt with are abstracted away inside the replace function. In a declarative program, the syntax itself describes what should happen and the details of how things happen are abstracted away.

By comparing both approach we can all agree that the declarative approach is much easier to understand and it is much shorter as we only have to think about what the code should do not how it should do.

--

--

Jamilur Rahman
React A-Z

Hi, I am Jamilur Rahman, web / android developer. I have been working with web and android frameworks for more than a year.