All You Need to Know About JavaScript Arrays with Example

All You Need to Know About JavaScript Arrays with Example

All You Need to Know About JavaScript Arrays with Example. What is JavaScript? What are Arrays? How can JavaScript be used while designing a website? JavaScript arrays are used to store multiple values in a single variable. Adding items to an array. Looping through array. Quickly Fill Arrays.

Everything you ever needed to know about JavaScript Arrays.

Arrays are a neat way to store continuous items in memory in a single variable. You can access elements in the array by its index. The index of the array starts with 0.

Let us create an empty array in multiple ways.

let tasks = [];
let projects = new Array();

Arrays in JavaScript are denoted by square bracket []. To get the length of array or count of elements in the array we can use the length property.

tasks.length;   // returns 0;
projects.length; // return 0;

One thing that you can do with an Array constructor that you cannot do with an array literal created with bracket notation is that you can set an initial length.

For example.

let projects = new Array(10);

console.log(projects.length); // Outputs 10

The recommended way is to use [] notation to create arrays.

We will talk on some performance issues, and creating holes in an array that results in lower performance etc, in later part of the article as an update.

So, all exercises going forward will use the [] notation.

Let us store some values in an array and access it by index

NOTE: You can store anything in an array but for best performance use only one type of data in one array, for eg. array of strings, an array of numbers, an array of objects etc. Don’t mix types (at least try to avoid mixing types)

let projects = ['Learn Spanish', 'Learn Go', 'Learn Erlang'];

We can access the array elements by index as shown below.

console.log(projects[0]);  // Outputs  'Learn Spanish'
console.log(projects[2]);  // Outputs  'Learn Erlang';
console.log(projects[3]);  // Outputs  'undefined' 
Adding items to an array

Adding items to the end of an array (push method)

Let us add some items to the end of an array. We use the push() method to do so.

projects.push("Learn Malayalam");

console.log(projects); 

// ["Learn Spanish", "Learn Go", "Learn Erlang", "Learn Malayalam"]

NOTE: Push() method mutates the array. Also, check Pop() method to remove an element from the array.

Adding items to the beginning of an array (unshift)

Let us add some items to the beginning of an array. We use the unshift() method to do so.

projects.unshift("Learn Tamil");
console.log(projects);

// ["Learn Tamil", "Learn Spanish", "Learn Go", "Learn Erlang", "Learn Malayalam"]

NOTE: unshift() mutates the array.

To add multiple items to the beginning of the array, just pass the required arguments to unshift method.

projects.unshift("Learn French", "Learn Marathi");

console.log (projects);

// ["Learn French", "Learn Marathi", "Learn Tamil", "Learn Spanish", "Learn Go", "Learn Erlang", "Learn Malayalam"]

Adding items to the beginning of an array ES6 (spread operator)

let projects = ['Learn Spanish', 'Learn Go', 'Learn Erlang'];

projects = ['Learn Malayalam', ...projects];

console.log(projects);
//Outputs-> ['Learn Malayalam', 'Learn Spanish', 'Learn Go', 
               'Learn Erlang']
Adding items to the end of an array ES6 (spread operator)
let projects = ['Learn Spanish', 'Learn Go', 'Learn Erlang'];

projects = [...projects,'Learn Malayalam'];

console.log(projects);
//Outputs-> ['Learn Spanish', 'Learn Go', 
               'Learn Erlang','Learn Malayalam']

NOTE: The es6 approach does not mutate the array and gives a new array back.

Remove first item from the array -> shift() method

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array. It returns undefined if the array is empty.

let numbers = [1,2,3,4];
let firstNo = numbers.shift();
console.log(numbers); // [2,3,4];
console.log(firstNo); // 1
Remove portion of an array, slicing -> slice() method

Slice method MDN Reference is a pretty useful method as it enables to cut the array from any position.

The **slice()** method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

arr.slice([begin[, end]])

Let us have a look at some examples.

var elements = ['Task 1', 'Task 2', 'Task 3', 'Task 4', 'Task 5'];

elements.slice(2) //["Task 3", "Task 4", "Task 5"]

elements.slice(2,4)  // ["Task 3", "Task 4"]

elements.slice(1,5) // ["Task 2", "Task 3", "Task 4", "Task 5"]

Remove /adding portion of an array -> splice() method

The **splice()** method changes the contents of an array by removing existing elements and/or adding new elements. Be careful, splice() method mutates the array.

A detailed reference here at MDN splice method.

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

Parameters

startIndex at which to start changing the array (with origin 0).

deleteCount (Optional)An integer indicating the number of old array elements to remove.

item1, item2, _..._ (Optional)The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array.

Return value

An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

var months = ['Jan', 'March', 'April', 'June'];

months.splice(1, 0, 'Feb');
// inserts at 1st index position

console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'June']

months.splice(4, 1, 'May');
// replaces 1 element at 4th index

console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'May']
Remove last item from the array -> pop() method

The **pop()** method removes the last element from an array and returns that element. This method changes the length of the array.

var elements = ['Task 1', 'Task 2', 'Task 3'];

Merging two arrays -> concat() method

The **concat()** method is used to merge two or more arrays. This method does not change the existing arrays but instead returns a new array.

let array1 = ['a', 'b', 'c'];
let array2 = ['d', 'e', 'f'];

let merged = array1.concat(array2);

console.log(merged);
// expected output: Array ["a", "b", "c", "d", "e", "f"]

Merging two arrays -> es6 (spread operator)

let array1 = ['a', 'b', 'c'];
let array2 = ['d', 'e', 'f'];

let merged = [...array1, ...array2];

console.log(merged);
// expected output: Array ["a", "b", "c", "d", "e", "f"]
Joining arrays -> Join () method

The **join()** method joins all elements of an array (or an array-like object) into a string and returns this string. This is a very useful method.

var elements = ['Task 1', 'Task 2', 'Task 3'];

console.log(elements.join());
// expected output: Task 1,Task 2,Task 3

console.log(elements.join(''));
// expected output: Task 1Task 2Task3

console.log(elements.join('-'));
// expected output: Task 1-Task 2-Task 3

The output

Array Custom Slice Helper function

The slice function is very handy but a more useful function that is needed is the ability to slice an array given the starting index and the length. Let’s write one (after all we are programmers).

I named the function as slicex (slice-extended, just for the lack of better name).

/* slicex
     parameters:  
        arr (the array element to be sliced)
        begin (the start index)
        length (the number of items to be extracted)*/function slicex(arr, begin, length) {
  return arr.slice(begin, begin + length);
}

The above function can be used as follows.

var elements = ['Task 1', 'Task 2', 'Task 3', 'Task 4'];

let g1 = slicex(elements,0,2);  
console.log(g1); // outputs -> ['Task 1','Task 2']

let g2 = slicex(elements,1,3);  
console.log(g2);// outputs -> ['Task 2','Task 3','Task 4']
Looping through array

There are various ways to loop through an array. Let’s see the simple example first.

Looping through array — forEach Loop

The forEach loop takes a function, a normal or arrow and gives access to the individual element as a parameter to the function. It takes two parameters, the first is the array element and the second is the index.

projects.forEach((e) => {
  console.log(e);
});

projects.forEach(function (e) {
  console.log(e);
});

Let’s see how we can access the index in forEach. Below I am using the arrow function notation, but will work for es5 function type as well.

projects.forEach((e, index) => {
  console.log(e, index);
});

Finding Elements in an array — find method

The **find()** method returns the value of the first element in the array that satisfies the provided testing function. Otherwise [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) is returned.

The syntax is given below.

  • callback — Function to execute on each value in the array, taking three arguments
  • ***** element — The current element being processed in the array
    ***** index (optional) — The index of the current element
    ***** array (optional) — The array find was called upon.
  • thisArg (optional) — Object to use as this when executing callback.

Return value
A value in the array if any element passes the test; otherwise, undefined.

arr.find(callback[, thisArg])

var data = [51, 12, 8, 130, 44];

var found = data.find(function(element) {
  return element > 10;
});

console.log(found);  // expected output: 51

Looping through an array — for in Loop

A for...in loop only iterates over enumerable properties and since arrays are enumerable it works with arrays.

The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor's prototype (properties closer to the object in the prototype chain override prototypes' properties).

More reading at MDN for in loop

for(let index in projects) {
   console.log(projects[index]);
}

Note in the above code, a new index variable is created every time in the loop.

Looping through array — map function ()

The map() function allows us to transform the array into a new object and returns a new array based on the provided function.

It is a very powerful method in the hands of the JavaScript developer.

NOTE: Map always returns the same number of output, but it can modify the type of output. For example, if the array contains 5 element map will always return 5 transformed element as the output.

let num = [1,2,3,4,5];

let squared = num.map((value, index, origArr) => {
   return value * value;
});

The function passed to map can take three parameters.

  • squared — the new array that is returned
  • num — the array to run the map function on
  • value — the current value being processed
  • index — the current index of the value being processed
  • origArr — the original array

Map () — Example 1 — Simple

let num = [1,2,3,4,5];

let squared = num.map((e) => {
   return e * e;
});

console.log(squared);

In the above code, we loop through all elements in the array and create a new array with the square of the original element in the array.

A quick peek into the output.

Map () — Example 2— Simple Transformation

Let us take an input object literal and transform it into key-value pair.

For example, let’s take the below array

let projects = ['Learn Spanish', 'Learn Go', 'Code more'];

and transform into key-value pair as shown below.

{
  0:  "Learn Spanish",
  1:  "Learn Go",
  2:  "Code more"
}

Here is the code for the above transformation with the output.

let newProjects = projects.map((project, index) => {
   return {
     [index]: project
   }
});
console.log(newProjects);

Map () — Example 3 — Return a subset of data

Lets take the below input

let tasks = [
   { "name": "Learn Angular",
     "votes": [3,4,5,3]
   },
   { "name": "Learn React",
     "votes": [4,4,5,3]
   },
];

The output that we need is just the name of the tasks. Let’s look at the implementation

let taskTitles = tasks.map((task, index, origArray) => {
   return {
     name: task.name
   }
});

console.log(taskTitles);

And here is the output.

Looping through an array — filter function ()

Filter returns a subset of an array. It is useful for scenarios where you need to find records in a collection of records. The callback function to filter must return true or false. Return true includes the record in the new array and returning false excludes the record from the new array.

It gives a new array back.

Let’s consider the below array as an input.

let tasks = [
   { "name": "Learn Angular",
     "rating": 3
   },
   { "name": "Learn React",
     "rating": 5
   },
   { "name": "Learn Erlang",
     "rating": 3
   },
   { "name": "Learn Go",
     "rating": 5
   },];

Now lets use the filter function to find all tasks with a rating of 5.

Let’s peek into the code and the result.

let tasks5 = tasks.filter((task) => {
    return task.rating === 5;
});
console.log(tasks5);

And the output is shown below.

Since we are only using one statement in the filter function we can shorten the above function as shown below.

tasks.filter(task => task.rating === 5);

NOTE: Filter function cannot transform the output into a new array.

Looping through an array — reduce function ()

Reduce function loops through array and can result a reduced set. It is a very powerful function, I guess, more powerful than any other array methods (though every method has its role).

From MDN, The **reduce()** method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

Reduce — Simple Example — 1

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer)); // expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

Note: The first time the callback is called, accumulator and currentValue can be one of two values. If initialValue is provided in the call to reduce(), then accumulator will be equal to initialValue, and currentValue will be equal to the first value in the array. If no initialValue is provided, then accumulator will be equal to the first value in the array, and currentValue will be equal to the second.

The reason reduce is very powerful is because just with reduce() we can implement our own, map(), find() and filter() methods.

Using reduce to categorize data

Assume you have the below data structure which you would like to categorize into male and female dataset.

let data = [
  {name: "Raphel", gender: "male"},
  {name: "Tom", gender: "male"},
  {name: "Jerry", gender: "male"},
  {name: "Dorry", gender: "female"},
  {name: "Suzie", gender: "female"},
  {name: "Dianna", gender: "female"},
  {name: "Prem", gender: "male"},
];

And we would like the output to be as below

{"female" : [
    {name: "Dorry", gender:"female"},
    {name: "Suzie", gender: "female"},
    {name: "Dianna", gender: "female"},
 ],
 "male" : [
    {name: "Raphel", gender:"male"},
    {name: "Tom", gender:"male"},
    {name: "Jerry", gender:"male"},
    {name: "Prem", gender:"male"},
 ]
}

So, lets get to the code and understand how to achieve the above categorization.

let genderwise = data.reduce((acc,item, index) => {
  acc[item.gender].push(item);
  return acc;    
}, {male: [], female:[]});

console.log(genderwise);


The important point above is the reduce function can be initialized with any type of starting accumulator, in the above case an object literal containing

{ male: [], female: []}

I hope this is sufficient to demonstrate the power of reduce method.

Using reduce to implement custom map() function

function map(arr, fn) {
  return arr.reduce((acc, item) => [...acc, fn(item)], []);
}

The above is the implementation of custom map function. I

n the above function we are passing empty array [] as the initial value for the accumulator and the reduce function is returning a new array with the values from the accumulator spread out and appending the result of invoking the callback function with the current item.

Let's see the usage and the output.

Using reduce to implement custom filter() function

Let’s implement the filter() method using reduce().

function filter (arr, fn) {
  return arr.reduce(function (acc, item, index) {
    if (fn(item, index)) {
      acc.push(item);
    }
    return acc;
  },[]);
}

Let’s see the usage and the output below. I could have overwritten the original Array.prototype.filter, but am doing so to avoid manipulating built-in methods.

Inside our custom filter, we are invoking the reduce function and only adding those items to the accumulator which matches the predicate that the callback function to filter returns.

Using reduce to implement custom forEach function

Let us know implement our own forEach function.

function forEach(arr, fn) {
  arr.reduce((acc, item, index) => {
    item = fn(item, index);
  }, []);
}

The implementation is very simple compared to other methods. We just grab the passed in array and invoke the reduce, and return the current item as a result of invoking the callback with the current item and index.

Let us see the usage and the output.

Using reduce to implement custom pipe() function

A pipe function sequentially executes a chain of functions from left to right. The output of one function serves as the input to the next function in the chain.


Implementation of pipe function

function pipe(...fns) {
  // This parameters to inner functions 
  return function (...x) { 
    return fns.reduce((v, f) => {
      let result = f(v);
      return Array.isArray(result) ? result: [result];
     },x)
   }
}

Usage

const print = (msg) => {
 console.log(msg);
 return msg;
}
const squareAll = (args) => {
   let result = args.map((a) => {
     return a * a;
   });
   return result;
}const cubeAll = (args) => {
   let result = args.map((a) => {
     return a * a * a;
   });
   return result;
}

pipe(squareAll,cubeAll, print)(1,2,3); // outputs => [1, 64, 729]

Holes in arrays

Holes in arrays means there are empty elements within the array. This may be because of couples of operations like delete or other operations that left these holes accidentally.

Now having ‘holes’ in an array is not good from a performance perspective. Let us take an example below.

let num = [1,2,3,4,5];  // No holes or gaps

delete num[2];  // Creates holes

console.log (num);  [1, 2, empty, 4, 5]

So, do not use delete method on array, unless you know what you are doing. delete method doesn’t alter the length of the array.

You can avoid holes in an array by using the array methods splice(), pop() or shift() as applicable.

Changing array length and holes

You can quickly change the length of the array as below.

let num = [1,2,3,4,5];  // length = 5;
num.length = 3; // change length to 3

//The below logs outputs
// [1,2,3] -> The last two elements are deleted
console.log(num);

Now, increasing the length this way creates holes.

let num = [1,2,3,4,5];

num.length = 10;  // increase the length to 10

console.log(num);  // See holes here

Quickly Fill Arrays

Let’s take a look at how to quickly fill or initialize an array.

The Array.prototype.**fill()** method

The fill method (modifies) all the elements of an array from a start index (default zero) to an end index (default array length) with a static value. It returns the modified array.

Syntax (from MDN)

Description

The fill method takes up to three arguments value, start and end. The start and endarguments are optional with default values of 0 and the length of the this object.

If start is negative, it is treated as length+start where length is the length of the array. If end is negative, it is treated as length+end.

fill is intentionally generic, it does not require that its this value be an Array object.

fill is a mutable method, it will change this object itself, and return it, not just return a copy of it.

When fill gets passed an object, it will copy the reference and fill the array with references to that object.

Example 1 — Simple fill

new Array(5).fill(“hi”)

Output => (5) [“hi”, “hi”, “hi”, “hi”, “hi”]

Example 2 — Fill with object

new Array(5).fill({'message':'good morning'})

The output is shown below.

Example 3 — Generate sequence

Array(5).fill().map((v,i)=>i);

The output will be

[0,1,2,3,4,5]

Example 4— More examples

[1, 2, 3].fill(4);               // [4, 4, 4]
[1, 2, 3].fill(4, 1);            // [1, 4, 4]
[1, 2, 3].fill(4, 1, 2);         // [1, 4, 3]
[1, 2, 3].fill(4, 1, 1);         // [1, 2, 3]
[1, 2, 3].fill(4, 3, 3);         // [1, 2, 3]
[1, 2, 3].fill(4, -3, -2);       // [4, 2, 3]
[1, 2, 3].fill(4, NaN, NaN);     // [1, 2, 3]
[1, 2, 3].fill(4, 3, 5);         // [1, 2, 3]
Array(3).fill(4);                // [4, 4, 4]
The Array.from method (static method)

NOTE: The from method is on the Array itself and not on the prototype.

Syntax (from MDN)

Observe here, the from method can take a mapping function.

Example 1 — Simple example

console.log(Array.from('foo'));

The output will be

["f", "o", "o"]

Example 2 — Object length

Array.from({ length: 5 });

The output will be

[undefined, undefined, undefined, undefined, undefined]

You can pass an object literal with a length property set to the desired array size since it’s the only required property for an array-like object. If you only pass the first argument, the resulting array will be filled with undefined values.

Example 3 — Sequence Generator(from MDN)

// Sequence generator function (commonly referred to as "range", e.g. Clojure, PHP etc)
const range = (start, stop, step) => 
       Array.from({ length: (stop - start) / step + 1}, 
             (_, i) => start + (i * step));

A brief explanation
Our custom range function takes 3 parameters, the start value, the stop value and the step (the step value has to be positive). We generate the array, the length is calculated as

(stop-start) / step + 1;

For. e.g. using range(1,10,2) => The start is 1, the stop is 10 and the step is two the expected output will be [1,3,5,7,9]

So, (10–1)/2+1

9/2+1 = 5.5 (we don’t need to ceil/floor here as the floor value is automatically considered) which is 5.

So, the output will be an array with alternating elements.

Range generation example

// Generate numbers range 0..4
range(0, 4, 1);
// [0, 1, 2, 3, 4] 

// Generate numbers range 1..10 with step of 2 
range(1, 10, 2); 
// [1, 3, 5, 7, 9]range(2,10,2)  // Start value is 2 and increment of 2
// [2, 4, 6, 8, 10]

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Hire Now: https://bit.ly/394wdOx

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 https://medium.com

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:

Hmmm.

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?

No.

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