How to Manipulate Arrays in JavaScript

How to Manipulate Arrays in JavaScript

How to Manipulate Arrays in JavaScript - An important part of any programming language. Most times we need to do several operations on arrays. In this article, I would show you various methods of manipulating arrays in JavaScript ...

How to Manipulate Arrays in JavaScript - An important part of any programming language. Most times we need to do several operations on arrays. In this article, I would show you various methods of manipulating arrays in JavaScript ...

What are Arrays in JavaScript?

Before we proceed, you need to understand what arrays really mean.

In JavaScript, an array is a variable that is used to store different data types. It basically stores different elements in one box and can be later assesssed with the variable.
Declaring an array:

let myBox = [];   // Initial Array declaration in JS

Arrays can contain multiple data types

let myBox = ['hello', 1, 2, 3, true, 'hi'];

Arrays can be manipulated by using several actions known as **methods. **Some of these methods allow us to add, remove, modify and do lots more to arrays.

I would be showing you a few in this article, let’s roll :)

NB: I used Arrow functions in this post, If you don’t know what this means, you should read here. Arrow function is an ES6 feature.### toString()

The JavaScript method toString() converts an array to a string separated by a comma.

let colors = ['green', 'yellow', 'blue'];
colors.toString();
console.log(colors); // "green,yellow,blue"

join()

The JavaScript join() method combines all array elements into a string.

It is similar to toString() method, but here you can specify the separator instead of the default comma.

let colors = ['green', 'yellow', 'blue'];
colors.join('-');
console.log(colors); // "green-yellow-blue"

concat

This method combines two arrays together or add more items to an array and then return a new array.

let firstNumbers = [1, 2, 3];
let secondNumbers = [4, 5, 6];
let merged = firstNumbers.concat(secondNumbers);
console.log(merged); // [1, 2, 3, 4, 5, 6]

push()

This method adds items to the end of an array and changes the original array.

let browsers = ['chrome', 'firefox', 'edge'];
browsers.push('safari', 'opera mini');
console.log(browsers); 
// ["chrome", "firefox", "edge", "safari", "opera mini"]

pop()

This method removes the last item of an array and returns it.

let browsers = ['chrome', 'firefox', 'edge'];
browsers.pop(); // "edge"
console.log(browsers); // ["chrome", "firefox"]

shift()

This method removes the first item of an array and returns it.

let browsers = ['chrome', 'firefox', 'edge'];
browsers.shift(); // "chrome"
console.log(browsers); // ["firefox", "edge"]

unshift()

This method adds an item(s) to the beginning of an array and changes the original array.

let browsers = ['chrome', 'firefox', 'edge'];
browsers.unshift('safari');
console.log(browsers); //  ["safari", "chrome", "firefox", "edge"]

You can also add multiple items at once### splice()

This** **method changes an array, by adding, removing and inserting elements.

The syntax is:

array.splice(index[, deleteCount, element1, ..., elementN])

  • <strong>Index</strong>** **here is the starting point for removing elements in the array
  • <strong>deleteCount</strong> is the number of elements to be deleted from that index
  • <strong>element1, …, elementN</strong> is the element(s) to be added

Removing items

*after running ****splice() ***, it returns the array with the item(s) removed and removes it from the original array.

let colors = ['green', 'yellow', 'blue', 'purple'];
colors.splice(0, 3);
console.log(colors); // ["purple"]
// deletes ["green", "yellow", "blue"]

NB*: The deleteCount does not include the last index in range.*
If the second parameter is not declared, every element starting from the given index will be removed from the array:

let colors = ['green', 'yellow', 'blue', 'purple'];
colors.splice(3);
console.log(colors); // ["green", "yellow", "blue"]
// deletes ['purple']

In the next example we will remove 3 elements from the array and replace them with more items:

let schedule = ['I', 'have', 'a', 'meeting', 'tommorrow'];
// removes 4 first elements and replace them with another
schedule.splice(0, 4, 'we', 'are', 'going', 'to', 'swim');
console.log(schedule); 
// ["we", "are", "going", "to", "swim", "tommorrow"]

Adding items

To add items, we need to set the deleteCount to zero

let schedule = ['I', 'have', 'a', 'meeting', 'with'];
// adds 3 new elements to the array
schedule.splice(5, 0, 'some', 'clients', 'tommorrow');
console.log(schedule); 
// ["I", "have", "a", "meeting", "with", "some", "clients", "tommorrow"]

slice()

This method is similar to <em>splice()</em> but very different. It returns subarrays instead of substrings.
This method **copies **a given part of an array and returns that copied part as a new array. It does not change the original array.

The syntax is:

array.slice(start, end)

Here’s a basic example:

let numbers = [1, 2, 3, 4]
numbers.slice(0, 3)
// returns [1, 2, 3]
console.log(numbers) // returns the original array

The best way to use slice() is to assign it to a new variable.

let message = 'congratulations'
const abbrv = message.slice(0, 7) + 's!'; 
console.log(abbrv) // returns "congrats!"

split()

This method is used for strings. It divides a string into substrings and returns them as an array.

Here’s the syntax:string.split(separator, limit);

  • The <strong>separator</strong> here defines how to split a string either by a comma.
  • The <strong>limit</strong> determines the number of splits to be carried out
let firstName = 'Bolaji';
// return the string as an array
firstName.split() // ["Bolaji"]

another example:

let firstName = 'hello, my name is bolaji, I am a dev.';
firstName.split(',', 2); // ["hello", " my name is bolaji"]

NB:* If we declare an empty array, like this <em>firstName.split('');</em> then each item in the string will be divided as substrings:*

let firstName = 'Bolaji';
firstName.split('') // ["B", "o", "l", "a", "j", "i"]

indexOf()

This method looks for an item in an array and returns the index where it was found else it returns -1

let fruits = ['apple', 'orange', false, 3]
fruits.indexOf('orange'); // returns 1
fruits.indexOf(3); // returns 3
friuts.indexOf(null); // returns -1 (not found)

lastIndexOf()

This method works the same way indexOf() does except that it works from right to left. It returns the last index where the item was found

let fruits = ['apple', 'orange', false, 3, 'apple']
fruits.lastIndexOf('apple'); // returns 4

filter()

This method creates a new array if the items of an array pass a certain condition.

The syntax is:

let results = array.filter(function(item, index, array) {
  // returns true if the item passes the filter
});

Example:

Checks users from Nigeria

const countryCode = ['+234', '+144', '+233', '+234'];
const nigerian = countryCode.filter( code => code === '+234');
console.log(nigerian); // ["+234", "+234"]

map()

This method creates a new array by manipulating the values in an array.

Example:

Displays usernames on a page. (Basic friend list display)

const userNames = ['tina', 'danny', 'mark', 'bolaji'];
const display = userNames.map(item => {
return '<li>' + item + '</li>';
})
const render = '<ul>' + display.join('') + '</ul>';
document.write(render);

another example:

// adds dollar sign to numbers
const numbers = [10, 3, 4, 6];
const dollars = numbers.map( number => '### **reduce()**

This method is good for calculating totals.

**reduce()** is used to calculate a single value based on an array.

let value = array.reduce(function(previousValue, item, index, array) {
// ...
}, initial);


example:
> *To loop through an array and sum all numbers in the array up, we can use the for of loop.*

const numbers = [100, 300, 500, 70];
let sum = 0;
for (let n of numbers) {
sum += n;
}
console.log(sum);


Here’s how to do same with ```reduce()```

const numbers = [100, 300, 500, 70];
const sum = numbers.reduce((accummulator, value) =>
accummulator + value
, 0);
console.log(sum); // 970

> *If you omit the initial value, the total will by default start from the first item in the array.*

const numbers = [100, 300, 500, 70];
const sum = numbers.reduce((accummulator, value) => accummulator + value);
console.log(sum); // still returns 970


The snippet below shows how the **reduce()** method works with all four arguments.

**source: MDN Docs**

![](https://cdn-images-1.medium.com/max/800/1*Cbd9qR_vy71qZjEQCFpCLQ.png)

More insights into the **reduce()** method and various ways of using it can be found [here](https://medium.freecodecamp.org/reduce-f47a7da511a9 "here")and [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce "here").
### **forEach()**

This method is good for iterating through an array.

It applies a function on all items in an array

const colors = ['green', 'yellow', 'blue'];
colors.forEach((item, index) => console.log(index, item));
// returns the index and the every item in the array
// 0 "green"
// 1 "yellow"
// 2 "blue"


iteration can be done without passing the index argument

const colors = ['green', 'yellow', 'blue'];
colors.forEach((item) => console.log(item));
// returns every item in the array
// "green"
// "yellow"
// "blue"

### **every()**

This method checks if all items in an array pass the specified condition and return```true``` if passed, else ```false```.
> *check if all numbers are positive*

const numbers = [1, -1, 2, 3];
let allPositive = numbers.every((value) => {
return value >= 0;
})
console.log(allPositive); // would return false

### **some()**

This method checks if an item (one or more) in an array pass the specified condition and return true if passed, else false.
> *checks if at least one number is positive*

const numbers = [1, -1, 2, 3];
let atLeastOnePositive = numbers.some((value) => {
return value >= 0;
})
console.log(atLeastOnePositive); // would return true

### **includes()**

This method checks if an array contains a certain item. It is similar to ```.some()```, but instead of looking for a specific condition to pass, it checks if the array contains a specific item.

let users = ['paddy', 'zaddy', 'faddy', 'baddy'];
users.includes('baddy'); // returns true


If the item is not found, it returns ```false```

There are more array methods, this is just a few of them. Also, there are tons of other actions that can be performed on arrays, try checking MDN docs [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ "here")for deeper insights.
### **Summary**
* **toString() **converts an array to a string separated by a comma.
* **join() **combines all array elements into a string.
* **concat** combines two arrays together or add more items to an array and then return a new array.
* **push()** adds item(s) to the end of an array and **changes** the original array.
* **pop()** removes the last item of an array and **returns** it
* **shift()** removes the first item of an array and **returns** it
* **unshift()** adds an item(s) to the beginning of an array and **changes** the original array.
* **splice()** c**hanges** an array, by adding, removing and inserting elements.
* **slice()** copies** **a given part of an array and returns that copied part as a new array. **It does not change the original array.**
* **split()** divides a string into substrings and returns them as an array.
* **indexOf()** looks for an item in an array and returns **the index** where it was found else it returns ```-1```
* **lastIndexOf()** looks for an item from right to left and returns the last index where the item was found.
* **filter()** creates a new array if the items of an array pass a certain condition.
* **map()** creates a new array by manipulating the values in an array.
* **reduce()** calculates a single value based on an array.
* **forEach()** iterates through an array, it applies a function on all items in an array
* **every()** checks if all items in an array pass the specified condition and return true if passed, else false.
* **some() **checks if an item (one or more) in an array pass the specified condition and return true if passed, else false.
* **includes()** checks if an array contains a certain item.

Let’s wrap it here; Arrays are powerful and using methods to manipulate them creates the Algorithms real-world applications use.

Let's do a create a small function, one that converts a post title into a urlSlug.
> ***URL slug**** is the exact address of a specific page or post on your site.*
When you write an article on **Freecodecamp News **or any other writing platform, your post title is automatically converted to a slug with white spaces removed, characters turned to lowercase and each word in the title separated by a hyphen.

Here’s a basic function that does that using some of the methods we learnt just now.

const url = 'https://bolajiayodeji.com/'
const urlSlug = (postTitle) => {
let postUrl = postTitle.toLowerCase().split(' ');
let postSlug = ${url} + postUrl.join('-');
return postSlug;
}
let postTitle = 'Introduction to Chrome Lighthouse'
console.log(urlSlug(postTitle));
// https://bolajiayodeji.com/introduction-to-chrome-lighthouse


in ```postUrl```, we convert the string to lowercase then we use the **split()**method to convert the string into substrings and returns it in an array

["introduction", "to", "chrome", "lighthouse"]


in ```post slug``` we join the returned array with a hyphen and then concatenate it to the category string and main ```url```.

let postSlug = ${url} + postUrl.join('-');
postUrl.join('-') // introduction-to-chrome-lighthouse


That’s it, pretty simple, right? :)

If you’re just getting started with JavaScript, you should check this repository [here](https://github.com/BolajiAyodeji/js-code-snippets "here"), I’m compiling a list of basic JavaScript snippets ranging from
* Arrays
* Control flow
* Functions
* Objects
* Operators

Don’t forget to Star and share! :)

Originally published by** Bolaji Ayodeji ***at**** **freecodecamp.org*

============================================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on [**Facebook**](https://www.facebook.com/nodejstutorial4u "**Facebook**") | [**Twitter**](https://twitter.com/codek_tv "**Twitter**")

☞ [GraphQL with React: The Complete Developers Guide](http://learnstartup.net/p/BkXcNtAMYx "GraphQL with React: The Complete Developers Guide")

☞ [The Modern GraphQL Bootcamp (with Node.js and Apollo)](http://learnstartup.net/p/j0jmDDNdH "The Modern GraphQL Bootcamp (with Node.js and Apollo)")

☞ [Build a Realtime App with React Hooks and GraphQL](http://learnstartup.net/p/2YOi0C9Qg "Build a Realtime App with React Hooks and GraphQL")

☞ [Full-Stack React with GraphQL and Apollo Boost](http://learnstartup.net/p/iPbGZ_yC_ "Full-Stack React with GraphQL and Apollo Boost")

☞ [The Complete JavaScript Course 2019: Build Real Projects!](http://learnstartup.net/p/rJWeUz65Z "The Complete JavaScript Course 2019: Build Real Projects!")

☞ [Docker for Node.js Projects From a Docker Captain](http://learnstartup.net/p/8oetVmxT4 "Docker for Node.js Projects From a Docker Captain")

☞ [Intro To MySQL With Node.js - Learn To Use MySQL with Node!](http://learnstartup.net/p/WKC5faEeb "Intro To MySQL With Node.js - Learn To Use MySQL with Node!")

☞ [Node.js Absolute Beginners Guide - Learn Node From Scratch](http://learnstartup.net/p/TKydAphkN "Node.js Absolute Beginners Guide - Learn Node From Scratch")

☞ [React Node FullStack - Social Network from Scratch to Deploy](http://learnstartup.net/p/C3uq0BAYL "React Node FullStack - Social Network from Scratch to Deploy")

☞ [Selenium WebDriver - JavaScript nodeJS webdriver IO & more!](http://learnstartup.net/p/EulR5bsYy "Selenium WebDriver - JavaScript nodeJS webdriver IO & more!")

☞ [Complete Next.js with React & Node - Beautiful Portfolio App](http://learnstartup.net/p/Eb7zdbhcX "Complete Next.js with React & Node - Beautiful Portfolio App")

☞ [Build a Blockchain & Cryptocurrency | Full-Stack Edition](http://learnstartup.net/p/_W4WzZ5gw "Build a Blockchain & Cryptocurrency | Full-Stack Edition")



 + number);
console.log(dollars);
// ['// adds dollar sign to numbers
const numbers = [10, 3, 4, 6];
const dollars = numbers.map( number => '$' + number);
console.log(dollars);
// ['$10', '$3', '$4', '$6'];
0', '$3', '$4', '$6'];

reduce()

This method is good for calculating totals.

reduce() is used to calculate a single value based on an array.

let value = array.reduce(function(previousValue, item, index, array) {
  // ...
}, initial);

example:

To loop through an array and sum all numbers in the array up, we can use the for of loop.

const numbers = [100, 300, 500, 70];
let sum = 0;
for (let n of numbers) {
sum += n;
}
console.log(sum);

Here’s how to do same with reduce()

const numbers = [100, 300, 500, 70];
const sum = numbers.reduce((accummulator, value) =>
accummulator + value
, 0);
console.log(sum); // 970

If you omit the initial value, the total will by default start from the first item in the array.

const numbers = [100, 300, 500, 70];
const sum = numbers.reduce((accummulator, value) => accummulator + value);
console.log(sum); // still returns 970

The snippet below shows how the reduce() method works with all four arguments.

source: MDN Docs

More insights into the reduce() method and various ways of using it can be found hereand here.

forEach()

This method is good for iterating through an array.

It applies a function on all items in an array

const colors = ['green', 'yellow', 'blue'];
colors.forEach((item, index) => console.log(index, item));
// returns the index and the every item in the array
// 0 "green"
// 1 "yellow"
// 2 "blue"

iteration can be done without passing the index argument

const colors = ['green', 'yellow', 'blue'];
colors.forEach((item) => console.log(item));
// returns every item in the array
// "green"
// "yellow"
// "blue"

every()

This method checks if all items in an array pass the specified condition and returntrue if passed, else false.

check if all numbers are positive

const numbers = [1, -1, 2, 3];
let allPositive = numbers.every((value) => {
return value >= 0;
})
console.log(allPositive); // would return false

some()

This method checks if an item (one or more) in an array pass the specified condition and return true if passed, else false.

checks if at least one number is positive

const numbers = [1, -1, 2, 3];
let atLeastOnePositive = numbers.some((value) => {
return value >= 0;
})
console.log(atLeastOnePositive); // would return true

includes()

This method checks if an array contains a certain item. It is similar to .some(), but instead of looking for a specific condition to pass, it checks if the array contains a specific item.

let users = ['paddy', 'zaddy', 'faddy', 'baddy'];
users.includes('baddy'); // returns true

If the item is not found, it returns false

There are more array methods, this is just a few of them. Also, there are tons of other actions that can be performed on arrays, try checking MDN docs herefor deeper insights.

Summary

  • **toString() **converts an array to a string separated by a comma.
  • **join() **combines all array elements into a string.
  • concat combines two arrays together or add more items to an array and then return a new array.
  • push() adds item(s) to the end of an array and changes the original array.
  • pop() removes the last item of an array and returns it
  • shift() removes the first item of an array and returns it
  • unshift() adds an item(s) to the beginning of an array and changes the original array.
  • splice() changes an array, by adding, removing and inserting elements.
  • slice() copies** **a given part of an array and returns that copied part as a new array. It does not change the original array.
  • split() divides a string into substrings and returns them as an array.
  • indexOf() looks for an item in an array and returns the index where it was found else it returns -1
  • lastIndexOf() looks for an item from right to left and returns the last index where the item was found.
  • filter() creates a new array if the items of an array pass a certain condition.
  • map() creates a new array by manipulating the values in an array.
  • reduce() calculates a single value based on an array.
  • forEach() iterates through an array, it applies a function on all items in an array
  • every() checks if all items in an array pass the specified condition and return true if passed, else false.
  • **some() **checks if an item (one or more) in an array pass the specified condition and return true if passed, else false.
  • includes() checks if an array contains a certain item.

Let’s wrap it here; Arrays are powerful and using methods to manipulate them creates the Algorithms real-world applications use.

Let's do a create a small function, one that converts a post title into a urlSlug.

URL slug* is the exact address of a specific page or post on your site.*
When you write an article on **Freecodecamp News **or any other writing platform, your post title is automatically converted to a slug with white spaces removed, characters turned to lowercase and each word in the title separated by a hyphen.

Here’s a basic function that does that using some of the methods we learnt just now.

const url = 'https://bolajiayodeji.com/'
const urlSlug = (postTitle) => {
let postUrl = postTitle.toLowerCase().split(' ');
let postSlug = `${url}` + postUrl.join('-');
return postSlug;
}
let postTitle = 'Introduction to Chrome Lighthouse'
console.log(urlSlug(postTitle));
// https://bolajiayodeji.com/introduction-to-chrome-lighthouse

in postUrl, we convert the string to lowercase then we use the **split()**method to convert the string into substrings and returns it in an array

["introduction", "to", "chrome", "lighthouse"]

in post slug we join the returned array with a hyphen and then concatenate it to the category string and main url.

let postSlug = `${url}` + postUrl.join('-');
postUrl.join('-') // introduction-to-chrome-lighthouse

That’s it, pretty simple, right? :)

If you’re just getting started with JavaScript, you should check this repository here, I’m compiling a list of basic JavaScript snippets ranging from

  • Arrays
  • Control flow
  • Functions
  • Objects
  • Operators

Don’t forget to Star and share! :)

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