Why must use JavaScript Array Functions

Why must use JavaScript Array Functions

In this article, we are going to discuss why must use JavaScript Array Functions

Originally published at https://www.geeksforgeeks.org
Why Must use JavaScript Array Functions – Part 1

In this article, we are going to discuss the following two JavaScript array functions

  1.  Array.prototype.every()
  2.  Array.prototype.some()

Both of these functions are widely used in industry and makes the Javascript code clean, modularized and easy to understand.

Array.prototype.every()

Description: Array.every() function is used when you need to validate each element of a given array. Array.every() accepts a callback function as argument which is called for each element of the array. The callback function has to return either a true or false. If all elements of the array satisfy the validation function and thus callback function returns true on all elements of the array, then Array.every() return true. Otherwise Array.every() returns false,as soon as it encounters the first element which does not satisfy the validator function.

Syntax : arr.every(callback[,thisArg])

Parameters :callback : Function to be called for each element of the array arr

– currentValue: The value of the elements being processed currently

– index(optional): Index of the currentValue element in the array starting from 0

– array(optional): The complete array on which Array.every is called

thisArg (optional): Context to be passed as this to be used while executing the callback function.  If context is passed, it will be used as this for each invocation of callback function, otherwise undefined is used as default.

Sample Use Case:

1.To check if every element of the integer array is less than 100

2. To check if every element of the array is of a specific data type, for example String.

Examples

1 - Given an array, write a function to check if all elements of that array are less than 100 or not.

So the naïve approach is to use for loop as shown below.

function fnIsLEssThan100_loop(arr){ 
for(var i = 0 ; i < arr.length; i ++){ 
	if(arr[i] >= 100){ 
		return false; 
	} 
} 
return true; 
} 
function fnIsLEssThan100_loop([30,60,90]); 
function fnIsLEssThan100_loop([30,60,90,120]); 


true
false

Although the above implementation is easy to understand for any novice programmer but there are some un-necessary checks which the programmer has to take care about. For Example, the short circuiting mechanism i.e. the programmer has to explicitly make sure that as soon as the loop encounters the first element which fails the given condition, the loop should break and return false. Also until and unless the programmer dives deep into the logic of the code, he/she won’t be able to understand what this for loop is doing. But with the use of Array.every(), same behavior can be achieved with much clearer, intuitive and less code.

function fnIsLesThan100_Every(arr){ 
return arr.every(function(element){ 
			return(element < 100): 
		}); 
} 

fnIsLesThan100_Every([30,60,90]) 
fnIsLesThan100_Every([30,60,90,120]) 


true
false

2 - Given an array, write a function to check if all elements of that array are of a specified data type.

Again naïve approach would be to iterate over the array using for loop.

function fnCheckDatatype_loop(arr. sDatatype){ 
for(var i = 0 ; i < arr.length; i ++){ 
if(typeof(arr[i]) !== sDatatype){ 
return false; 

fnCheckDatatype_loop(["Geeks","for","Geeks"],"string") 
fnCheckDatatype_loop(["Geeks",4,"Geeks"],"string") 


true
false

The above code snippet has the same loopholes as the previous example. Using arr.Every() those loopholes are taken care of again in code snippet below. Another point to note in the code snippet below is that we are passing two arguments to the array.every() function. The first one is the callback function (anonymous function in our case) and the second one is sDatatype. Because we need an external variable in each call of callback function, we pass it as a second argument as ‘this’ variable.

function fnCheckDatatype_Every(arr, sDatatype){ 
return arr.every(function(element){ 
return typeof(element) === sDatatype; 
},sDatatype); 

fnCheckDatatype_loop(["Geeks","for","Geeks"],"string") 
fnCheckDatatype_loop(["Geeks",4,"Geeks"],"string") 


true
false

Array.prototype.some()

Description:The JavaScript array function Array.some() is in a way opposite of Array.every(). The Array.some() function is used when you need to check if at least one element of a given array passes the test implemented by the callback function. Array.some() accepts a callback function as argument which has to return either a true or false. The callback function is called for each element of the array until it returns true for at least one element of the array. If neither of the elements in the array pass the test of callback function, Array.some() returns false.

Syntax : Array.some(callback[,thisArg])

Parameters :callback : Function to be called for each element of the array arr

– currentValue : The value of the elements being processed currently

– index (optional) : Index of the currentValue element in the array starting from 0

– array (optional) : The complete array on which Array.some()is called

thisArg (optional):Context to be passed as this to be used while executing the callback function.  If context is passed, it will be used as this for each invocation of callback function, otherwise undefined is used as default.

Sample Use Case:

1.To check if any element of the array greater than 100.

2. To check if any element of the array is even.

Examples

1 - Given an array, write a function to check if array contains any number greater than 100.

Naïve Approach

function fnIsGreaterThan100_loop(arr){ 
for(var i = 0 ; i < arr.length; i ++){ 
if(arr[i] > 100){ 
return true; 


return false; 

fnIsGreaterThan100_loop([30,60,90,120]); 
fnIsGreaterThan100_loop([30,60,90]); 


true
false

Using Array.some()

function fnIsGreaterThan100_some(arr){ 
return arr.some(function(element){ 
return(element . 100): 
}); 

fnIsGreaterThan100_some([30,60,90,120]); 
fnIsGreaterThan100_some([30,60,90]); 


 true
false

2 - Given an array, write a function to check if array contains any even number.

Naïve approach

function fnIsEven_loop(arr){ 
for(var i = 0 ; i < arr.length; i ++){ 
if(arr[i] % 2 === 0){ 
return true; 


return false; 

fnIsEven_loop([1,3,5]); 
fnIsEven_loop([1,3,5,6]); 


 false
true

Using Array.some()

function fnIsEven_some(arr){ 
return arr.some(function(element){ 
return(element %2 === 0): 
}); 

fnIsEven_some([1,3,5]); 
fnIsEven_some([1,3,5,6]); 


 false
true

One of the common mistake programmers do while using array functions like Array.every() and Array.some() is that they forget the return the value in the callback function. Mind it, if you don’t return any value from the callback function, null is returned which will be interpreted as false.

Also, it is important to know that these array functions were introduced in ECMAScript 5. So these functions are supported in IE9 or higher. If you need to use it for older browsers as well, then a library like underscore.js can come to your rescue which has an equivalent implementation of such functions.

Why Must use JavaScript Array Functions – Part 2

In Why Must use Javascript Array Functions – Part 1, we discussed two array functions namely Array.Prototype.Every() and Array.prototype.some(). It is important to note that both of these array functions accessed the array elements but did not modify/change the array itself. Today we are going to look at 2 array methods which modify the array and return the modified array.

Array.Prototype.filter()

Description: Array.prototype.filter() is used to get a new array which has only those array elements which pass the test implemented by the callback function. It accepts a callback function as argument. This callback function has to return a true or false. Elements for which the callback function returned true are added to the newly returned array.

Syntax:arr.filter(callback[, thisArg])

Parameters:

callback: callback function to be called for each element of the array arr

– currentValue: The value of the elements being processed currently

– index(optional): Index of the currentValue element in the array starting from 0

– array(optional): The complete array on which Array.prototype.filter() is called

thisArg: Context to be passed as this when used while executing the callback function. If no context is passed, undefined will be used as default value.

Sample use Cases:

1. Scenario where user has to remove all null values from an array.

2. Scenario where user has to filter out the array based on value of a particular property of objects in the array.

Example:

1.Function to filter out the students who got more than 80 percent marks.

Naïve Method using loop

<script> 
function fnFilterStudents_loop(aStudent){ 
var tempArr = []; 
for(var i = 0 ; i< aStudent.length; i ++){ 
if(aStudent[i].fPercentage > 80.0){ tempArr.push(aStudent[i]);} 

return tempArr; 

aStudent = [ 
{sStudentId : "001" , fPercentage : 91.2}, 
{sStudentId : "002" , fPercentage : 78.7}, 
{sStudentId : "003" , fPercentage : 62.9}, 
{sStudentId : "004" , fPercentage : 81.4}]; 

console.log(fnFilterStudents_loop(aStudent));&nbsp;

</script> 

Output:

[{sStudentId : "001" , fPercentage : 91.2},
{sStudentId : "004" , fPercentage : 81.4}];

Using Array.prototype.filter()

<script> 
function fnFilterStudents_filter(aStudent){ 
return aStudent.filter(function(oStudent){ 
return oStudent.fPercentage > 80.0 ? true : false; 

	});&nbsp;
}&nbsp;
aStudent = [&nbsp;
	{sStudentId : "001" , fPercentage : 91.2},&nbsp;
	{sStudentId : "002" , fPercentage : 78.7},&nbsp;
	{sStudentId : "003" , fPercentage : 62.9},&nbsp;
	{sStudentId : "004" , fPercentage : 81.4}];&nbsp;
	
console.log(fnFilterStudents_filter(aStudent));&nbsp;

</script> 

Output:

[{sStudentId : "001" , fPercentage : 91.2},
{sStudentId : "004" , fPercentage : 81.4}];

2. Function to remove undefined elements from an array

<script> 
function removeUndefined(myArray){ 
return myArray.filter(function(element, index, array){ 
return element; 
}); 

var arr = [1,undefined,3,undefined,5];&nbsp;

console.log(arr);&nbsp;

console.log( removeUndefined(arr));&nbsp;

</script> 

Output:

[1,undefined,3,undefined,5];
[1,3,5];

In the callback function of above example, we are returning element directly. So if the element has value, it will be treated as true and if element is undefined, it will be automatically treated as false.

Array.Prototype.map()

Description:Array.prototype.map() is used to modify each element of the array according to the callback function. Array.prototype.map() calls the callback function once for each element in the array in order. The point to note is that callback function is called on indexes of elements who has assigned value including undefined.

Syntax:arr.map(callback[, thisArg])

Parameters:

callback : Callback function to be called for each element of the array arr

– currentValue: The value of the elements being processed currently

– index(optional): Index of the currentValue element in the array starting from 0

– array(optional): The complete array on which Array.prototype.map() is called

thisArg: Context to be passed as this when used while executing the callback function. If no context is passed, undefined will be used as default value.

Sample use Cases:

1. Scenario where user has to reduce each amount in an array by a specific tax value

2. Scenario where user has to create a new property of every object in an existing array of objects.

Example:

1.Function to add property bIsDistinction to each object in the array.

Using Loop

<script> 
function fnAddDistinction_loop(aStudent){ 
for(var i = 0 ; i< aStudent.length; i ++){ 
aStudent[i].bIsDistinction = (aStudent[i].fPercentage >= 75.0) ? true : false; 

return aStudent; 

aStudent = [ 
{sStudentId : "001" , fPercentage : 91.2}, 
{sStudentId : "002" , fPercentage : 78.7}, 
{sStudentId : "003" , fPercentage : 62.9}, 
{sStudentId : "004" , fPercentage : 81.4}]; 

console.log(fnAddDistinction_loop(aStudent));&nbsp;

</script> 

Output:

[{sStudentId : "001" , fPercentage : 91.2 , bIsDistiction : true},
{sStudentId : "002" , fPercentage : 78.7 , bIsDistiction : false},
{sStudentId : "003" , fPercentage : 62.9 , bIsDistiction : false},
{sStudentId : "004" , fPercentage : 81.4 , bIsDistiction : true}];

Using Array.prototype.map()

<script> 
function fnAddDistinction_map(aStudent){ 
return aStudent.map(function(student, index, array){ 
aStudent.bIsDistinction = (aStudent.fPercentage >= 75.0) ? true : false; 
return aStudent; 
}); 

aStudent = [ 
{sStudentId : "001" , fPercentage : 91.2}, 
{sStudentId : "002" , fPercentage : 78.7}, 
{sStudentId : "003" , fPercentage : 62.9}, 
{sStudentId : "004" , fPercentage : 81.4}]; 

console.log(fnAddDistinction_map(aStudent));&nbsp;

</script> 

Output:

[{sStudentId : "001" , fPercentage : 91.2 , bIsDistiction : true},
{sStudentId : "002" , fPercentage : 78.7 , bIsDistiction : false},
{sStudentId : "003" , fPercentage : 62.9 , bIsDistiction : false},
{sStudentId : "004" , fPercentage : 81.4 , bIsDistiction : true}];

2. Scenario where Array.prototype.Map() is used with standard JavaScript functions.

For example, with Math.sqrt to calculate square root of each element in an array or to parse string values to float.

[1,4,9].map(Math.sqrt); // Output : [1,2,3] 
["1.232","9.345","3.2345"].map(parseFloat) // Output : [1.232, 9.345, 3.2345] 

One has to be careful while using Array.prototype.map() with standard functions because something like this can happen.

["1","2","3"].map(parse.Int); 
//Output : [1, NaN, NaN] 

Why did the above code snippet return NaN? This happened because parseInt function accepts two arguments, First one being the element to be parsed to Integer and second as the radix which acts as base for conversion. When we use it with Array.prototype.map(), although the first argument is the element, the second argument is the index of the array element being processed currently. For first iteration, the index being 0 is passed as radix to parseInt which defaults it to 10 and thus you see first element parsed successfully. After that it gets messed up.

Below is the fix for above mess up.

["1","2","3"].map(function(val{return parseInt(val,10)}); 
// output : [1, 2, 3] 

All code snippets used in this tutorial is available at: https://github.com/hjaintech/GeeksForGeeks/blob/master/Array_Functions_2.html

As shown in the above examples, both Array.prototype.filter() and Array.prototype.map() can be implemented using for loops. But in the above scenarios, we are trying to work on very specific use cases. Keeping a counter variable, then a checking against array length and then incrementing the counter variable. Keeping these things in mind is not only a hassle, but also make code prone to bugs. For example, developer might accidently misspell “array.length” as “array.lenght”. So as a rule of thumb, the best way to avoid programming bugs is to reduce the number of things that you are keeping track of manually. And these Array Functions do just that.

Browser support is really good for these functions but they are still not supported in IE8 or below as these array functions were introduced in ECMAScript 5. If you need to use it for older browsers as well, then you can either use es5-shim or any library like Underscore or Lodash can come to your rescue which has equivalent utility function.

Why Must use JavaScript Array Functions – Part 3

In this article, we are going to discuss the following JavaScript array functions

  1. prototype.reduce()
  2. prototype.concat()
  3. prototype.sort()
  4. prototype.reverse()

1. Array.Prototype.reduce()

Description: Array.prototype.reduce() function is used when the programmer needs to iterate over a JavaScript array and reduce it to a single value. A callback function is called for each value in array from left to right. The value returned by callback function is available to next element as an argument to its callback function. In case the initialValue is not provided, reduce’s callback function is directly called on 2nd elementwith 1st element being passed as previousValue. In case the array is empty and initial value is also not provided, a TypeError is thrown.

Syntax:

arr.reduce(callback[, initialValue])

Parameters:

callback: callback function to be called for each element of the array arr

  • previousValue: Value returned by previous function call or initial value.
  • currentValue:Value of current array element being processed
  • currentIndex:Index of the current array element being processed
  • array: The original array on which reduce is being called.

initialValue(optional): Initial value to be used as previousValue when callback function is invoked for first time.

Sample Use Cases:

1 - To find sum of an array of integers.

function reduceFun1(previousValue, currentValue, index, array){ 
return previousValue + currentValue; 

var result = [1,2,3,4,5].reduce(reduceFun1); 

console.log(result); // Output : 15 

2 - Given an array of objects containing addresses of sales locations and find the total sales done in NY   

var arr=[{name: "customer 1", sales: 500, location: "NY"}, 
{name: "customer 1", sales: 200, location: "NJ"}, 
{name: "customer 1", sales: 700, location: "NY"}, 
{name: "customer 1", sales: 200, location: "ORD"}, 
{name: "customer 1", sales: 300, location: "NY"}]; 

function reduceFun2(previousValue, currentValue, index, array){ 
if(currentValue.location === "NY"){ 
return previousValue + currentValue.sales; 

return previousValue; 

var totalSalesInNY = arr.reduce(reduceFun2); 

console.log(totalSalesInNY); // Output: 1500 

In the above example, an initial value 0 is provided while calling the Array.reduce() on arr. In this case it is necessary to provide an initial integer value. This is because for each iteration of callback function, the variable previousValue has to have an integer value and not whole object. If we don’t pass the initialValue as 0, then for first iteration, the previous value will become the whole object and will try to add an integer value to it, thereby giving junk output.

2. Array.prototype.concat()

Description:Array.prototype.concat() is used to concatenate an array with another array/value. It does not change any existing array, instead, it returns a modified array. It accepts both new arrays and values as an argument which it concatenates with the array calling the function and returns the resultant array.

Syntax:

 NewArray = Array1.concat(value1[, value2[, ...[, valueN]]])

Parameters:

valueN : New array or value to be concatenated to Array1.

Sample Use Case:

Concatenate 2 integer arrays:

var arr1 = [1,2,3,4]; 
var arr2 = [5,6,7,8]; 
var arr3 = arr1.concat(arr2); 
console.log(arr3); // Output : [1, 2, 3, 4, 5, 6, 7, 8] 

Concatenate 3 integer arrays:

var arr1 = [1,2,3,4]; 
var arr2 = [5,6]; 
var arr3 = [7,8]; 
var arr4 = arr1.concat(arr2,arr3); 
console.log(arr4); // Output : [1, 2, 3, 4, 5, 6, 7, 8] 

Concatenate an array with individual integer values:

var arr1 = [1,2,3,4]; 
var arr2 = arr1.concat(5,6,7,8); 
console.log(arr2); // Output : [1, 2, 3, 4, 5, 6, 7, 8] 

Concatenate an array with another array and other multiple values:

var arr1 = [1,2,3,4]; 
var arr2 = [5,6]; 
var arr3 = arr1.concat(arr2, 7, 8); 
console.log(arr3); // Output : [1, 2, 3, 4, 5, 6, 7, 8] 

3. Array.prototype.sort()

Description: Array.prototype.sort() is used to sort an array. It accepts an optional argument compareFunction which defines the criteria to determine which element of the array is small and which is bigger. The compareFunction accepts 2 arguments i.e. the values being compared. If value1 is smaller then compare function should return a negative value. If value2 is smaller, compareFunction should return a positive value. In case compare function is not provided, the default compareFunction converts the array elements into strings and then compares those strings in Unicode point order.

Syntax:

arr.sort([compareFunction])

Parameters:

compareFunction (optional): Function to define the sort order.

Sample Use Case:

Sort a simple integer array:

var arr = [3, 1, 5, 4, 2].sort(); 
console.log(arr); // Output : [1, 2, 3, 4, 5] 

Sort a string array:

var arr = ["Orange", "Apple", "Banana"].sort(); 
console.log(arr); // Output : ["Apple", "Banana", "Orange"] 

Sort another integer array:

var arr = [1, 30, 5].sort(); 
console.log(arr); // Output : [1, 30, 5] 

Here, the order of resultant sorted array is not correct. This is because as we are using the default sortFunction, it converts all integers into strings and then compares them based on their Unicode value. Since 30 < 5 in Unicode, Hence the incorrect sort order.

Sort the integer array using sort function:

function sortFun(a,b){ 
return a - b; 

var arr = [1, 30, 5].sort(sortFun); 
console.log(arr); // Output : [1, 5, 30] 

Here, the order is correct because we didn’t use the default sortFunction but our own sortFunction which compares the integer values to decide the sort order.

Sort an object array using sort function:

var arr = [{name:"NY", count: 20}, 
{name:"NJ", count: 5}, 
{name:"JFK", count: 60}, 
{name:"ORD", count: 1}]; 
function sortFun(obj1, obj2){ 
return obj1.count - obj2.count; 

arr.sort(sortFun); 
console.log(arr); // Output [{name:"ORD", count: 1}, 
// {name:"NJ", count: 5}, 
// {name:"NY", count: 20}, 
// {name:"JFK", count: 60}] 

4. Array.prototype.reverse()

Description: Array.prototype.reverse() is used to reverse a JavaScript array. Reverse() function modifies the calling array itself and returns a reference to the now reversed array.

Syntax:

array.reverse()

Parameters:

Not Applicable

Sample Use Case:

var arr = [1,2,3,4,5,6,7,8,9,10]; 
arr.reverse(); 
console.log(arr); //Output : [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 

All code snippets used in this article are available at https://github.com/hjaintech/GeeksForGeeks/blob/master/Array_Functions_3.html

Additionally, if you wish you dive deeper into the above functions, you can refer to the following official links.

  1. http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.21
  2. http://www.ecma-international.org/ecma-262/5.1/#sec-15.5.4.6
  3. http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.11
  4. http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.8

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

Top 10 JavaScript array methods you should know

All about JavaScript Arrays Methods


Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

What’s new in HTML6

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

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