What is functional programming?Functional programming is centered around building software composed of functions, similar to procedural programming; however, there are subtle differences. We highlight these differences by discussing key concepts of functional programming below. Show
First-class citizensFunctions are treated as primitives. Primitives serve as the simplest elements of a programming language. Thus, a function can be:
Since they have these capabilities, functions are referred to as first-class citizens. The term first-class citizen essentially notates an element that supports all other generally available operations. Pure functionsA goal of functional programming is to write pure functions whenever possible.
Pure functions enable numerous compiler optimizations, leading to significantly reducing a program’s execution time. Furthermore, pure functions are
ideally suited for unit testing. We can unit-test a pure function in isolation without having to worry about where in the code it will be used. Higher-order functions and recursionInstead of iterative loop constructs, such as
A tail call refers to a function call at the end of a function. A tail call may result in a recursive loop when a function calls itself. Many compilers perform tail call optimization (a.k.a. tail call elimination) making recursion as fast as iterative loops. Key reasons for preferring recursion over typical primitive loops are:
Immutability
No value assigned to a variable in functional programming can be changed; the only way to change a value is to create a new variable. It is immutability that enables functional programming to use pure functions. These functions do not mutate their inputs and rely on nothing but the input to achieve results. In this way, functional programming is similar to math. Functional programming was even created for an academic computer science setting through the Haskell language. In summation, functional programming is a declarative programming model that communicates what the program does without specifying the flow of control. It uses pure functions, immutable variables, and tail-call recursion. This results in code that is easier to understand, debug, and unit-test. Furthermore, functional programming enables numerous compiler optimizations for an increase in a program execution speed and reduction in memory requirements. Functional programming is a paradigm of building computer programs using expressions and functions without mutating state and data. By respecting these restrictions, functional programming aims to write code that is clearer to understand and more bug resistant. This is achieved by avoiding using flow-control statements ( In this article, we will talk about doing functional programming using JavaScript. We will also explore various JavaScript methods and features that make it possible. In the end, we will explore different concepts associated with functional programming and see why they are so powerful. Before getting into functional programming, though, one needs to understand the difference between pure and impure functions. Pure vs. Impure FunctionsPure functions take some input and give a fixed output. Also, they cause no side effects in the outside world.
Here,
This is also an impure function, and that too for a couple of reasons—(1) it uses a non-local variable for computing its output, and (2) it creates a side effect in the outside world by modifying a variable in that world. This can be troublesome if we had to debug this code. What’s the current value of Because of these reasons, we only use pure functions in functional programming. Another benefit of pure functions is that they can be parallelized and memoized. Have a look at the previous two functions. It’s impossible to parallelize or memoize them. This helps in creating performant code. The Tenets of Functional ProgrammingSo far, we have learned that functional programming is dependent on a few rules. They are as follows.
When we satisfy these conditions, we can say our code is functional. Functional Programming in JavaScriptJavaScript already has some functions that enable functional programming. Example: String.prototype.slice, Array.protoype.filter, Array.prototype.join. On the other hand, Array.prototype.forEach, Array.prototype.push are impure functions. One can
argue that Also, JavaScript has a const declaration, which is perfect for functional programming since we won’t be mutating any data. Pure Functions in JavaScriptLet’s look at some of the pure functions (methods) given by JavaScript. FilterAs the name suggests, this filters the array.
The condition here is a function that gets each item of the array, and it should decide whether to keep the item or not and return the truthy boolean value for that.
Notice that Map
Reduce
Concat
You can also do the same using the spread operator.
Object.assign
With the advent of ES6, this can also be done using the spread operator.
Creating Your Own Pure FunctionWe can create our pure function as well. Let’s do one for duplicating a string
This function duplicates a string
Higher-order FunctionsHigher-order functions are functions that accept a function as an argument and return a function. Often, they are used to add to the functionality of a function.
In the above example, we create a
One can also call it without defining a combining function.
CurryingCurrying means breaking down a function that takes multiple arguments into one or multiple levels of higher-order functions. Let’s take the
When we are to curry it, we rewrite it distributing arguments into multiple levels as follows.
The benefit of currying is memoization. We can now memoize certain arguments in a function call so that they can be reused later without duplication and re-computation.
This is certainly better than using both arguments everywhere.
We can also reformat our curried function to look succinct. This is because each level of the currying function call is a single line return statement. Therefore, we can use arrow functions in ES6 to refactor it as follows.
CompositionIn mathematics, composition is defined as passing the output of one function into input of another so as to create a combined output. The same is possible in functional programming since we are using pure functions. To show an example, let’s create some functions. The
first function is range, which takes a starting number
Then we have a function multiply that takes an array and multiplies all the numbers in it.
We will use these functions together to calculate factorial.
The above function for calculating factorial is similar to Concluding WordsWe went through pure and impure functions, functional programming, the new JavaScript features that help with it, and a few key concepts in functional programming. We hope that this piece piques your interest in functional programming and possibly motivates you to try it in your code. We are positive that it will be a learning experience and a milestone in your software development journey. Functional programming is a well-researched and robust paradigm of writing computer programs. With the introduction of ES6, JavaScript allows for a much better functional programming experience than ever before. Further Reading on the Toptal Engineering Blog:
What is an example of a language that is based on the functional paradigm?Programming Languages that support functional programming: Haskell, JavaScript, Python, Scala, Erlang, Lisp, ML, Clojure, OCaml, Common Lisp, Racket.
Which of the following is an example of a language that is based on the declarative paradigm?Many languages fall under the banner of declarative programming, but some of the most widely used include HTML, SQL, CSS and XML. Other examples include a mix of functional and logic programming languages, such as Prolog, Haskell, Miranda, XQuery and Lisp.
What paradigm are most machine languages based upon?Since the basic ideas of imperative programming are both conceptually familiar and directly embodied in the hardware, most computer languages are in the imperative style. Assignment statements, in imperative paradigm, perform an operation on information located in memory and store the results in memory for later use.
Which of the following is an example of objectTwo such languages are Python and Ruby. Probably the most commercially important recent object-oriented languages are Java, developed by Sun Microsystems, as well as C# and Visual Basic.NET (VB.NET), both designed for Microsoft's .NET platform.
|