Functional Programming Using JavaScript

Functional Programming Using JavaScript

Understand functional programming concepts utilizing JavaScript, one of the most recognizable functional programming languages.

Understand functional programming concepts utilizing JavaScript, one of the most recognizable functional programming languages.

I will briefly talk about programming paradigms, then jump into describing functional programming concepts utilizing JavaScript, as it is one of the most recognizable functional programming languages. Readers are encouraged to refer to the references section for further insight into this fascinating concept.

Programming Paradigms

A programming paradigm is a framework for thinking about the problems and the attendant tools to help implement that vision. Many modern languages are polyparadigm (or multiparadigm): they support a number of different programming paradigms, such as object orientation, metaprogramming, functional, procedural, etc.

Functional Programming Paradigm

Functional programming is like a car powered by hydrogen fuel cells—advanced, futuristic, and not yet widely used. In contrast to an imperative program, which consists of a series of statements that change global state when executed, a functional program models computations as the evaluation of expressions. Those expressions are built from pure mathematical functions that are both first-class (can be manipulated like any other value) and free from side effects.

Functional programming cherishes the following values:

Functions Are First Class Things

We should treat functions like any other first class object in the language. In other words, storing functions in a variable, creating functions dynamically, and returning or passing them to other functions. Let’s take a look at an example below.

  • A string can be stored in a variable so can a function

var sayHello = function() { return “Hello” };

  • A string can be stored in an object field and so can a function

var person = {message: “Hello”, sayHello: function() { return “Hello” }};

  • A string can be created as needed and so can a function

“Hello ” + (function() { return “World” })(); //=> Hello World

  • A string can be passed to a function and so can a function

function hellloWorld(hello, world) { return hello + world() }

  • A string can be returned from a function and and so can a function

return “Hello”;

return function() { return “Hello”};

Do It at a Higher Order

Functions that take other functions as arguments or return them as results are called Higher-Order functions. We have already seen an example of this. Now let’s review it in a complex situation.

Example #1

[1, 2, 3].forEach(alert);

// alert box with "1" pops up

// alert box with "2" pops up

// alert box with "3" pops up

Example #2

function splat(fun) {

   return function(array) {

        return fun.apply(null, array);



var addArrayElements = splat(function(x, y) { return x + y });

addArrayElements([1, 2]);

//=> 3

Favor Pure Functions

Pure functions are functions that have no side effects. A side effect is an action that the function creates, modifying the state outside the function. For example:

  • Modifying a variable.
  • Modifying a data structure in place.
  • Setting a field on an object.
  • Throwing an exception or halting with an error.

A simple example of this is a math function. The Math.sqrt(4) function will always return 2. This does not use any hidden information such as a state or settings. A math function will never inflict side effects.

Avoid Mutable State

Functional programming favors pure functions, which can’t mutate data, and therefore creates a need for the substantial use of immutable data. Instead of modifying an existing data structure, a new one is efficiently created.

You may wonder, if a pure function mutates some local data in order to produce an immutable return value, is this okay? The answer is yes.

Very few data types in JavaScript are immutable by default. Strings are one example of a data type that can’t be changed:

    var s = "HelloWorld";


    //=> "HELLOWORLD"


    //=> "HelloWorld"

Benefits of Immutable State

  • Avoids confusion and increases program accuracy: Some of the most difficult bugs to find in large systems occur when state is modified externally, by client code that is located elsewhere in the program.
  • Establishes “quick and easy” multithreaded programming: If multiple threads can modify the same shared value, you have to synchronize access to that value. This is quite tedious and error-prone programming that even experts find challenging.

Software Transactional Memory and the Actor Model provide a direction to handle mutations in a thread safe way.

Recursion Instead of Explicitly Looping

Recursion is the most famous functional programming technique. If you don’t know by now, a recursive function is a function which calls itself.

The classic functional alternative to an iterative loop is to use recursion, where we pass through the function operating on the next item in the collection until a termination point is reached. Recursion is also a natural fit for certain algorithms, such as traversing a tree where each branch is itself a tree.

Recursion is very important to functional programming in any language. Many functional languages go so far as to require recursion for iteration by not supporting while loop statements. This is only possible when tail-call elimination is guaranteed by the language, which is not the case for JavaScript.

Lazy Evaluation Over Eagerly Computing

Mathematics defines some infinite sets, such as the natural numbers (all positive integers). They are represented symbolically. Any particular finite subset of values is evaluated only on demand. We call this lazy evaluation (also known as non-strict evaluation, call-by-need and deferred execution). Eager evaluation would force us to represent all of the infinite values, which is clearly impossible.

Some languages are lazy by default, while others provide lazy data structures that can be used to represent infinite collections and strictly compute a subset of values on demand.

It’s clear that a line of code that states result = compute() is calling for result to be assigned to the returned value by compute(). But what result actually equates to does not matter until it is required.

This strategy can result in a major increase in performance, especially when used with method chains and arrays. These are the favorite program flow techniques of the functional programmer.

This opens the door for many possibilities including asynchronous execution, parallelization, and composition.

However, there’s one problem. JavaScript does not perform Lazy evaluation on its own. That being said, libraries exist for JavaScript that simulate lazy evaluation efficiently.

Take Full Benefit of Closures

All functional languages include closures, yet this language feature is often discussed in almost mystical terms. A closure is a function that carries an implicit binding to all the variables referenced within it. In other words, the function encloses a context around what it is referencing. Closures in JavaScript are functions that have access to the parent scope, even when the parent function has closed.

   function multiplier(factor) {

      return function(number) {

          return number * factor;



  var twiceOf = multiplier(2);


//=> 12

Prefer Declarative Over Imperative Programming

Functional programming is declarative, like mathematics, where properties and relationships are defined. The runtime figures out how to compute final values. The definition of the factorial function provides an example:

factorial(n = 1 if n = 1

    n * factorial(n-1) if n > 1

The definition relates the value of factorial(n) to factorial(n-1), a recursive definition. The special case of factorial(1) terminates the recursion.

var imperativeFactorial = function(n) {

    if(n == 1) {

        return 1

    } else {

        product = 1;

        for(i = 1; i <= n; i++) {

              product *= i;


        return product;



var declarativeFactorial = function(n) {

       if(n == 1) {

             return 1

       } else {

             return n * factorial(n - 1);



The declarativeFactorial might look “imperative" in the sense that it implements a calculation of factorials, but its structure is more declarative than imperative.

The imperativeFactorial uses mutable values, the loop counter, and the result that accumulates the calculated value. The method explicitly implements a particular algorithm. Unlike the declarative version, this method has lots of little mutation steps, making it harder to understand and keep bug free.

Functional Libraries for JavaScript

There are tons of functional libraries out there: underscore.js, lodash, Fantasy Land, Functional.js, Bilby.js, fn.js, Wu.js, Lazy.js, Bacon.js, sloth.js, stream.js, Sugar, Folktale, RxJs etc.

Functional Programmer’s Toolkit

The map(), filter(), and reduce() functions make up the core of the functional programmer’s toolkit; a collection of pure, higher-order functions that are the workhorse of the functional method. In fact, they’re the epitome of what a pure function and higher-order function should emulate; they take a function as input and return an output with zero side effects.

These JavaScript functions are crucial to every functional program. They enable you to remove loops and statements, resulting in cleaner code. While they are standard for browsers implementing ECMAScript 5.1, they only work on arrays. Each time it is called, a new array is created and returned. The existing array is not modified. But wait, there’s more…They take functions as inputs, often in the form of anonymous functions referred to as callback functions. They iterate over the array and apply the function to each item in the array!

myArray = [1,2,3,4];

newArray = {return x*2});

console.log(myArray); // Output: [1,2,3,4]

console.log(newArray); // Output: [2,4,6,8]

Apart from these three, there more functions that can be plugged into nearly any functional application: forEach(), concat(), reverse(), sort(), every(), and some().

JavaScript’s PolyParadigm

Of course JavaScript is not strictly a functional programming language, but instead facilitates the use of other paradigms as well:

  • Imperative programming: Programming based around describing actions in detail.
  • Prototype-based object-oriented programming: Programming based around prototypical objects and instances of them.
  • Metaprogramming: Programming manipulating the basis of JavaScript’s execution model. A good definition of metaprogramming is stated as: “programming occurs when you write code to do something and metaprogramming occurs when you write code that changes the way that something is interpreted.”

Thanks for reading ❤

Mobile App Development Company India | Ecommerce Web Development Company India

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company

JavaScript developers should you be using Web Workers?

JavaScript developers should you be using Web Workers?

Do you think JavaScript developers should be making more use of Web Workers to shift execution off of the main thread?

Originally published by David Gilbertson at

So, Web Workers. Those wonderful little critters that allow us to execute JavaScript off the main thread.

Also known as “no, you’re thinking of Service Workers”.

Photo by Caleb Jones on Unsplash

Before I get into the meat of the article, please sit for a lesson in how computers work:

Understood? Good.

For the red/green colourblind, let me explain. While a CPU is doing one thing, it can’t be doing another thing, which means you can’t sort a big array while a user scrolls the screen.

This is bad, if you have a big array and users with fingers.

Enter, Web Workers. These split open the atomic concept of a ‘CPU’ and allow us to think in terms of threads. We can use one thread to handle user-facing work like touch events and rendering the UI, and different threads to carry out all other work.

Check that out, the main thread is green the whole way through, ready to receive and respond to the gentle caress of a user.

You’re excited (I can tell), if we only have UI code on the main thread and all other code can go in a worker, things are going to be amazing (said the way Oprah would say it).

But cool your jets for just a moment, because websites are mostly about the UI — it’s why we have screens. And a lot of a user’s interactions with your site will be tapping on the screen, waiting for a response, reading, tapping, looking, reading, and so on.

So we can’t just say “here’s some JS that takes 20ms to run, chuck it on a thread”, we must think about where that execution time exists in the user’s world of tap, read, look, read, tap…

I like to boil this down to one specific question:

Is the user waiting anyway?

Imagine we have created some sort of git-repository-hosting website that shows all sorts of things about a repository. We have a cool feature called ‘issues’. A user can even click an ‘issues’ tab in our website to see a list of all issues relating to the repository. Groundbreaking!

When our users click this issues tab, the site is going to fetch the issue data, process it in some way — perhaps sort, or format dates, or work out which icon to show — then render the UI.

Inside the user’s computer, that’ll look exactly like this.

Look at that processing stage, locking up the main thread even though it has nothing to do with the UI! That’s terrible, in theory.

But think about what the human is actually doing at this point. They’re waiting for the common trio of network/process/render; just sittin’ around with less to do than the Bolivian Navy.

Because we care about our users, we show a loading indicator to let them know we’ve received their request and are working on it — putting the human in a ‘waiting’ state. Let’s add that to the diagram.

Now that we have a human in the picture, we can mix in a Web Worker and think about the impact it will have on their life:


First thing to note is that we’re not doing anything in parallel. We need the data from the network before we process it, and we need to process the data before we can render the UI. The elapsed time doesn’t change.

(BTW, the time involved in moving data to a Web Worker and back is negligible: 1ms per 100 KB is a decent rule of thumb.)

So we can move work off the main thread and have a page that is responsive during that time, but to what end? If our user is sitting there looking at a spinner for 600ms, have we enriched their experience by having a responsive screen for the middle third?


I’ve fudged these diagrams a little bit to make them the gorgeous specimens of graphic design that they are, but they’re not really to scale.

When responding to a user request, you’ll find that the network and DOM-manipulating part of any given task take much, much longer than the pure-JS data processing part.

I saw an article recently making the case that updating a Redux store was a good candidate for Web Workers because it’s not UI work (and non-UI work doesn’t belong on the main thread).

Chucking the data processing over to a worker thread sounds sensible, but the idea struck me as a little, umm, academic.

First, let’s split instances of ‘updating a store’ into two categories:

  1. Updating a store in response to a user interaction, then updating the UI in response to the data change
  2. Not that first one

If the first scenario, a user taps a button on the screen — perhaps to change the sort order of a list. The store updates, and this results in a re-rendering of the DOM (since that’s the point of a store).

Let me just delete one thing from the previous diagram:

In my experience, it is rare that the store-updating step goes beyond a few dozen milliseconds, and is generally followed by ten times that in DOM updating, layout, and paint. If I’ve got a site that’s taking longer than this, I’d be asking questions about why I have so much data in the browser and so much DOM, rather than on which thread I should do my processing.

So the question we’re faced with is the same one from above: the user tapped something on the screen, we’re going to work on that request for hopefully less than a second, why would we want to make the screen responsive during that time?

OK what about the second scenario, where a store update isn’t in response to a user interaction? Performing an auto-save, for example — there’s nothing more annoying than an app becoming unresponsive doing something you didn’t ask it to do.

Actually there’s heaps of things more annoying than that. Teens, for example.

Anyhoo, if you’re doing an auto-save and taking 100ms to process data client-side before sending it off to a server, then you should absolutely use a Web Worker.

In fact, any ‘background’ task that the user hasn’t asked for, or isn’t waiting for, is a good candidate for moving to a Web Worker.

The matter of value

Complexity is expensive, and implementing Web Workers ain’t cheap.

If you’re using a bundler — and you are — you’ll have a lot of reading to do, and probably npm packages to install. If you’ve got a create-react-app app, prepare to eject (and put aside two days twice a year to update 30 different packages when the next version of Babel/Redux/React/ESLint comes out).

Also, if you want to share anything fancier than plain data between a worker and the main thread you’ve got some more reading to do (comlink is your friend).

What I’m getting at is this: if the benefit is real, but minimal, then you’ve gotta ask if there’s something else you could spend a day or two on with a greater benefit to your users.

This thinking is true of everything, of course, but I’ve found that Web Workers have a particularly poor benefit-to-effort ratio.

Hey David, why you hate Web Workers so bad?

Good question.

This is a doweling jig:

I own a doweling jig. I love my doweling jig. If I need to drill a hole into the end of a piece of wood and ensure that it’s perfectly perpendicular to the surface, I use my doweling jig.

But I don’t use it to eat breakfast. For that I use a spoon.

Four years ago I was working on some fancy animations. They looked slick on a fast device, but janky on a slow one. So I wrote fireball-js, which executes a rudimentary performance benchmark on the user’s device and returns a score, allowing me to run my animations only on devices that would render them smoothly.

Where’s the best spot to run some CPU intensive code that the user didn’t request? On a different thread, of course. A Web Worker was the correct tool for the job.

Fast forward to 2019 and you’ll find me writing a routing algorithm for a mapping application. This requires parsing a big fat GeoJSON map into a collection of nodes and edges, to be used when a user asks for directions. The processing isn’t in response to a user request and the user isn’t waiting on it. And so, a Web Worker is the correct tool for the job.

It was only when doing this that it dawned on me: in the intervening quartet of years, I have seen exactly zero other instances where Web Workers would have improved the user experience.

Contrast this with a recent resurgence in Web Worker wonderment, and combine that contrast with the fact that I couldn’t think of anything else to write about, then concatenate that combined contrast with my contrarian character and you’ve got yourself a blog post telling you that maybe Web Workers are a teeny-tiny bit overhyped.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

An Introduction to Web Workers

JavaScript Web Workers: A Beginner’s Guide

Using Web Workers to Real-time Processing

How to use Web Workers in Angular app

Using Web Workers with Angular CLI

Hire PHP Developer and Web Developer for your Online Business

Hire PHP Developer and Web Developer for your Online Business

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application...

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application development. To hire PHP developer and web developer at affordable prices contact Mobiweb Technology via [email protected]