An Introduction to Javascript and Functional Programming

An Introduction to Javascript and Functional Programming

An Introduction to Javascript and Functional Programming

I’ve always been about the bottom line. Uninterested in pseudo intellectual concepts, fancy terminology and hype. Instead, I always reach for the tools and technologies that help me ship code as soon as possible. This approach was initially productive — specifically when I was building smaller “proof of concept” applications.

Unfortunately, this approach did not scale. As I progressed as a developer I started feeling the law of diminishing return on my productivity. Setting up a project, and reaching basic functionality was fast. But the real problems started creeping up when my applications started growing in complexity. I found that as a project’s lifecycle advanced I was writing complex code. Code that I had written become harder to reason about. In order to understand it, I had to be extremely concentrated.

I had this itching feeling that a better, cleaner approach to developing software had to exist. I had heard whispers about functional programming, and how it allows developers to write more concise and elegant code. I was unknowingly exposed to functional paradigms and patterns for the first time while working with React and Redux. They both incorporated some of the principles, and I liked them. I read about FP — to my initial dismay I saw its paradigms were based on abstract mathematical concepts and that it was very prevalent in academia. Being that my goal is to ship products as fast as possible, this seemed like a counterintuitive approach to what I was trying to achieve. After 4 years in engineering school, I was pretty set on the opinion that academia only tackled theoretical problems, and was unlikely to ever help me in my day-to-day of building things.


But FP kept haunting me. Elegant solutions and paradigms were sprinkled online in all my favorite open source projects, blog posts and tutorials. I put my skeptecism aside and started delving into FP.

Although the concepts involve new jargon, and include a steep learning curve, I was amazed and really excited about this “new approach”. This series of articles shares my learning experience, and aims at extracting and summarizing the pearls of FP which enable a cleaner, more concise development experience. I will attempt to build an intuitive understanding of the patterns I discuss and frame the problems and the provided solutions as simply as possible, overstepping unnecessarily complex definitions. Learning FP has a reputation for being a bit daunting, but by breaking down the concepts into smaller bits, we will make the ideas easier to digest.

The main difference in FP in comparison to other programming paradigms is a declarative approach (FP) versus an imperative one. Before we dive into formal definitions, let’s explore the differences by looking at an example.


// triple the value of every element in a given array
const triple = (arr) => {
  let results = []
  for (let i = 0; i < arr.length; i++){
    results.push(arr[i] * 3)
  return results

// sum all the elements in a given array
const sum = (arr) => {
let result = 0
for (let i = 0; i < arr.length; i++){
result += arr[i]
return result

Imperative functions in the wild

Does this code seem evil? It should! What are the similarities between the methods above?

  1. The main complexity of this code snippet derives from the fact that instead of telling the computer what we want it to do, we are instructing it on how to do it. Code that tells the computer how to operate — ie. go to the array at index i and mutate or swap a value is called imperative code.
  2. This code isn’t readable (😱😱😱). This is a toy example, but as your program grows and your functionality becomes more sophisticated, using for loops like this creates code that is non trivial, and requires our brain to analyze the inner working of the loop while keeping track of indexes, variables and more. Imperative code increases the cognitive load when reading, and over time makes it easier to faulter in reasoning and logic.


Let’s rewrite this snippet of code, but in a declarative manner.

// triple the value of every item in a given array
const triple = (arr) => => currentItem * 3)

// sum all the elements in a given array
const sum = (arr) => arr.reduce((prev, current) => prev + current, 0)

.map? .reduce? What is this black magic?

First off, I promise that given the same input, these two methods produce the same output every single time.

A quick aside on the declarative snippet -

.map()is a method accessible from every array in JS. The .map() method creates a new array with the results of calling a provided function on every element in the calling array.

.reduce() is a method that applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

Don’t fret about these just yet. We’re going to explore these handy array-native methods in depths in upcoming posts. But it is clear that the declarative snippet is more concise than the imperative one. It’s also a lot easier to read. Instead of instructing the program on which indexes I want it to access etc, I am simply supplying an expression to .map() and** .reduce()** (an anonymous function in our case) which tells the program what I want it do to every element in the array.

This declarative approach is going to serve us well across the board by:

  1. Learning and using patterns in your code that are well-known, understandable, and proven to keep away the mistakes that make code harder to understand.

2. Composing shorter, expressive and concise code. After all, the less code we write the less we have to debug.

Most importantly, these tools and paradigms are going to help us achieve our (my) ultimate goal of shipping products faster. Check out the next post, where we discuss functions in JS, why they are special and how their characteristics enable functional programming.

Javascript and Functional Programming — Pt.2 : First Class Functions

Welcome to the Upside Down

Before we get started, there’s something you need to know … If you’ve ever programmed in JS you’ve probably used FP patterns before! These patterns and paradigms have been there all along, we just haven’t been able to see them properly. We are going to start from the familiar and explore new territory. Things may get a bit … well … strange. But fear not! Together we will survive!

First Class Functions

In Javascript, functions are first class objects. Like I mentioned earlier, we don’t like cryptic terminology, so let’s explain. According to the Mozilla developer glossary:

A programming language is said to have First-class functions when functions in that language are treated like any other variable. For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable.

Functions as constants

In the following example we will declare a const and assign it an anonymous arrow functions.

After the initial assignment constFunction is a constant with a value of a function. We verify that by logging the constFunction variable in the Chrome inspector. Because constFunction is a function we can also invoke it.

Functions as values of keys of an object

Now that we understand that variables can hold functions, let’s demonstrate a function as a value of a key in an object. This should be familiar for anyone who has done any object oriented programming before.

const functionAsObjectProperty = {
print: (value) => console.log(value)

functionAsObjectProperty.print("mic check"); // "mic check"

Functions as array items

When functions are first class objects we can pass them as data to an array, just like any other data type. Let’s use the Chrome console and check this out.

Higher order functions

Now that we’ve warmed up, let’s get to the interesting stuff :) JS developers see functions that accept other functions as arguments on a daily basis. If you’re coming from a language that doesn’t support FP this should seem a bit weird 😳😳😳😳😳😳😳 Let’s acquaint ourselves with this concept by looking at some examples.

An asynchronous function that accepts a callback function.

const jsonfile = require('jsonfile')

const file = '/tmp/data.json'
const obj = {name: 'JP'}

const errorLoggerFunction = (err) => console.error(err);

jsonfile.writeFile(file, obj, errorLoggerFunction)

errorLoggerFunction is defined as a function with the ES6 arrow syntax

We’re using the jsonfile npm module in this example for the _writeFile m_ethod. The third parameter that writeFile is expecting is a function. When the jsonfile.writeFile method executes it will either succeed or fail. If it fails it will execute the errorLoggerFunction. Alternatively, we could have gone for a more terse syntax, and dropped the named function:

const jsonfile = require('jsonfile')

const file = '/tmp/data.json'
const obj = {name: 'JP'}

jsonfile.writeFile(file, obj, (err) => console.error(err))

It’s an anonymous function because we didn’t name it


const timeout = () => {
setTimeout(() => alert("WoW"), 1000);

Classic callback example

This example shows the built in asynchronous setTimeout method which accepts 2 arguments. Let’s formalize this a little bit and explain the setTimeout function in functional programming terms.

Let’s start by reading the signature of the function. We can observe that the number of arguments that setTimeout takes is two. In functional programming the number of arguments a function takes is called its Arity, from words like unary, binary, ternary etc. So we can say that setTimeout is of arity 2, or equivalently say that is a binary function.

The arguments that setTimeout expects is a function and a time interval to wait before executing the given function. Hmmm … another function that accepts a function as input?

In functional programming this is so common that these types of functions even have a name! They are called higher order functions.

A higher order function is a function that takes a function as an argument, or returns a function.

There you go. Now you can drop this term low key in any random conversation at work / with friends and sound like a boss! 😂😂😂

const add = (x,y) => x + y;
const subtract = (x,y) => x - y;
const multiply = (x,y) => x * y;

const arrayOfFunctions = [add, subtract, multiply];

arrayOfFunctions.forEach(calculationFunction => console.log(calculationFunction(1,1))); // 2 0 1

On line 5 we are declaring an array of functions. We are then using the forEach method to iterate over the array. forEach is a natively supported ES6+ function, that accepts a function to execute on every item in the array. Therefore, forEach is also a higher order function!

Our forEach accepts an anonymous function as input. forEach will iterate over the array and implicitly access the current item in the array and call it getCalculation. It is worth noting that forEach implicitly accesses array elements, in comparison to how we would have accessed the current element if we had used a regular for loop — ie. arrayOfFunctions[i]. Every item in our array is a function, therefore we invoke getCalculation with the arguments that it is expecting.

Fantastic. This example illustrates that functions in functional programming can be passed into arrays (lists) just like any other data type. Functions can go anywhere!

Now let’s build our own higher order function!

const addWrapper = () => (x,y) => x + y;

const add = addWrapper();

const sum1 = add (1,2); // 3

// Or we could do it like this

const sum2 = addWrapper()(4,4); // 8
view raw
functionThatReturnsFunction.js hosted with ❤ by GitHub

The addWrapper function returns a simple addition function when called. By invoking the result of the addWrapper function and supplying it two arguments, we have access to the anonymous addition function.

We could get even crazier with our level of indirection and write a function that returns a function, that in turn returns its own function!

const bankStatement =
name =>
location =>
balance =>
Hello ${name}! Welcome to the bank of ${location}. Your current balance is ${balance};

const statementExpectingLocation = bankStatement("Omer");
const statementExpectingBalance = statementExpectingLocation("NYC");
const bankStatementMsg = statementExpectingBalance("100 million"); // wishful thinking?

console.log(bankStatementMsg); // Hello Omer! Welcome to the bank of NYC. Your current balance is 100 million

// We could also call the function with all the arguments up front
const msg = bankStatement("Jeff Bezos")("Silicon Valley")("97.7 billion");
console.log(msg); // Hello Jeff Bezos! Welcome to the bank of Silicon Valley. Your current balance is 97.7 billion

I hope you like curry!

This is a very powerful pattern in functional programming. We will explore it in depth in the coming posts when we talk about currying and partial applications.

First class functions are the cornerstones of any functional programming language. The main point that you should take away from our discussion about first class functions is that functions can be assigned as constants, variables, placed as array elements and even set as values of keys on an object. Additionally, (and most importantly ?!) functions can be returned to and from functions —** just like any other data type!**

Javascript and Functional Programming — Pt. 3: Pure FunctionsPurity


So many of our bugs are rooted in IO related, data mutation, side effect bearing code. These creep up all over our code base — from things like accepting user inputs, receiving an unexpected response via an http call, or writing to the file system. Unfortunately, this is a harsh reality that we should grow accustomed to dealing with. Or is it?

What if I told you, that we could minimize the parts of our code which executed the critical / volatile bits of our program? We could enforce (by convention) that the large majority of our code base would be pure, and limit IO related / side effect bearing code to a specific part of our codebase. This would make our debugging process a lot easier, more coherent and easier to reason about.

So, what is this mythical pure function? A pure function has two main characteristics:

1. A pure function is deterministic. This means, that given the same input, the function will always return the same output. To illustrate this as a function in mathematical terms (this will be quick!) it is a well defined function. Every input returns a single output, every single time.

![Javascript and Functional Programming ](Javascript and Functional Programming "Javascript and Functional Programming ")

A pure function

const add = (x, y) => x + y // A pure function

add is a pure function because it’s output is solely dependent on the arguments it receives. Therefore, given the same values, it will always produce the same output.

How about this one?

const magicLetter = '*'
const createMagicPhrase = (phrase) => ${magicLetter}abra${phrase}

Something about this one is fishy…. The createMagicPhrase function is dependent on a value which is external to its scope. Therefore, it is not pure!

An impure function

const fetchLoginToken = externalAPI.getUserToken

Is fetchLoginToken a pure function? Does it return the same value every single time? Absolutely not! Sometimes it will work — sometimes the server will be down and we will get a 500 error — and at some point in the future the API may change so that this call is no longer valid! So, because the function is non-deterministic, we can safely say that it is an impure function.

2. A pure function will not cause side effects. A side effect is any change in the system that is observable to the outside world.

const calculateBill = (sumOfCart, tax) => sumOfCart * tax

Is calculateBill pure? Definitely :) It exhibits the two necessary characteristics:

  • The function depends only on its arguments to produce a result
  • The function does not cause any side effects

The Mostly Adequate Guide states that side effects include, but are not limited to:

  • changing the file system
  • inserting a record into a database
  • making an http call
  • mutations
  • printing to the screen / logging
  • obtaining user input
  • querying the DOM
  • accessing system state

Why should our functions be pure?

Readability -> Side effects make our code harder to read. Since a non pure function is not deterministic it may return several different values for a given input. We end up writing code that needs to account for the different possibilities. Let’s look at another http based example:

async function getUserToken(id) {
const token = await getTokenFromServer(id);
return token;

This snippet can fail in so many different ways. What if the id passed to the getTokenFromServer was invalid? What if the server crashed and returned an error, instead of the expected token? There are a lot of contingencies that need to be planned for, and forgetting one (or several!) of them is very easy.

Additionally, a pure function is easier to read, as it requires no context. It receives all of its needed parameters up front, and does not talk / tamper with the state of the application.

Testability -> Because pure functions are deterministic by nature, writing unit tests for them is a lot simpler. Either your function works or it doesn’t 😁

Parallel Code -> Since pure functions only depend on their input, and will not cause side effects, they are great for scenarios where parallel threads run and use shared memory.

Modularity and Reusability -> Think of pure functions as little units of logic. Because they only depend on the input you feed them, you can easily reuse functions between different parts of your codebase or different projects altogether.

Referential Transparency -> This one sounds so complicated 🙄🙄 When I first read the title I wanted a coffee break! Simply put, referential transparency means that a function call could be replaced by its output value, without changing the overall behavior of our program. This is mostly useful as a framework of thought when creating pure functions.

It’s pure and all…. but does it do anything?

It’s important to note that although pure functions offer a ton of benefits, it’s not realistic to only have pure functions in our applications. After all, if we did our application would have no side effects, thus not produce any observable effects to the outside world. That would be pretty boring 😥😥😥. Instead we will try to encapsulate all of our side effects to specific parts of our codebase. That way, assuming we have written unit tests for our pure functions and know they are working, if something breaks in our app, it will be a lot easier to track down.

Let’s get pure

Let’s conclude our discussion by converting the following non pure function to pure. This is a contrived example, but demonstrates how we can easily refactor unpure code to pure.

let a = 4;
let b = 5;
let c = 6;
const updateTwoVars = (a) => {
c = a * b;

console.log(b,c); // b = 6, c = 24

Let’s start by reviewing why this function is unpure. Our function is unpure because it depends on a and b, which are external to its scope. In addition, it is also directly mutating (changing) the values of the variables. The quickest way to refactor this function is

  • First ensure that all the variables that the function depends on are passed as arguments
  • Instead of mutating (manipulating) b and c, we can return new values which will reflect the new values.
let a = 4;
let b = 5;
let c = 6;
const updateTwoVars = (a, b, c) => [b++, a * b];

const updateRes = updateTwoVars(a,b,c);
b = updateRes[0]
c = updateRes[1]


We’ve covered a lot of the benefits of transitioning our code base to include more pure functions. It makes our code easier to reason about, test, and most importantly more predictable. Remember, pure functions are not about completely ridding our code base of side effects. It’s about constraining them to a definitive location and eliminating as much of them as possible. This approach will justify itself many times over, when your programs start growing in size and complexity.

Javascript and Functional Programming: Currying (Pt.4)

Currying is when we call a function with fewer arguments than it expects. In turn, the invoked function returns a function that takes the remaining arguments.

const magicPhrase =
(magicWord) =>
(muggleWord) =>
magicWord + muggleWord

We could then invoke this function with the following pattern

Call it maaagic

Writing functions that return functions, that in turn return some output (possibly another function!) can get quite cumbersome. Luckily we have functional JS helper libraries like Ramda and lodash which provide us with utility methods such as curry. The curry utility wraps normally declared functions and transforms them into a series of one-argument functions. So we could convert the previous code to:

import _ from "lodash"

const magicPhrase = _.curry((magicWord, muggleWord) => magicWord + muggleWord)

const muggleWordAccepter = magicPhrase("Abra kedabra ")


Another example would be a revamped implementation of our favorite add function

import _ from "lodash"

const addFunction = _.curry((a, b) => a + b)

const addOne = add(1)


So we are essentially, “pre loading” the add function with the first variable. Our function has the ability to remember the first value passed thanks to JS closure.

Why You Should Care About Currying

  1. Currying gives us the ability to compose terse, concise and reusable functions.

2. We use these functions as clean, testable units of logic to compose the more logically complex parts of our programs.

3. With currying, any function that works on single elements can be converted into a function that works on arrays (lists), simply by wrapping it with map.

const getObjectId = (obj) => // works on single object

const arrayOfObjects = [{id: 1}, {id: 2}, {id: 3}, {id: 4}]

const arrayOfIDs =

BAM! Our function that worked on single elements can work on arrays!


The only real way to get familiar with these concepts is to practice :) Let’s get to it. We shall start with one more example of converting a function that operates on a single element to a function that operates on an array.

const getFirstTwoLettersOfWord = (word) => word.substring(0,2)

// We can convert it, by wrapping it in the map method

["aabb", "bbcc", "ccdd", "ddee"].map(getFirstTwoLettersOfWord)

The next example comes out of the amazing Mostly Adequate guide, with a small ES6 refactors :)

Let’s refactor the max function so that it won’t reference any arguments.

arr = [2,4,6,8,9]

const getMax = (x, y) => {
return x >= y ? x : y;

const max = (arr) => {
return arr.reduce((acc, x) => {
return getMax(acc, x);
}, -Infinity);

const max = arr.reduce(getMax, -Infinity)

Let’s wrap the native JS slice method so that it functional and curried.

import _ from "lodash"

const arr = ["barney", "fred", "dave"]

arr.slice(0, 2) // ["barney", "fred"]

const slice = _.curry((start, end, arr) => arr.slice(start, end));
const sliceWithSetIndexes = slice(0,2)

sliceWithSetIndexes(arr) // ["barney", "fred"]


We’ve seen several examples where we curry JS functions. Currying refers to the process of transforming a function with multiple arity (arguments accepted) into the same function with less arity. It utilizes JS closure to remember the arguments used in the previous invocations. Currying twists functions around so that they can work more naturally together. Its biggest advantage is that it easily allows for function composition, which we will explore in depth in the next post!

Learn More

10 JavaScript array methods you should know

Introducing TensorFlow.js: Machine Learning in Javascript

Machine Learning in JavaScript with TensorFlow.js

5 ways to build real-time apps with JavaScript

Full Stack Developers: Everything You Need to Know

5 Javascript (ES6+) features that you should be using in 2019

The Complete JavaScript Course 2019: Build Real Projects!

JavaScript: Understanding the Weird Parts

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

The Full JavaScript & ES6 Tutorial - (including ES7 & React)

Originally published by Omer Goldberg at

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]