Like any kind of apps, JavaScript apps also have to be written well.
Otherwise, we run into all kinds of issues later on.
In this article, we’ll look at some best practices we should follow when writing JavaScript code.
The RAIL Model
The RAIL model is created by Google to let us think about performance from the user’s perspective.
RAIL stands for Response, Animation, Idle, and Load.
Response is when the page first responds to user input.
Animation is when the page moves.
Idle is how long the page stays idle.
Load is long the page takes to load.
We should make our app respond to interaction as quickly as possible.
Find Memory Leaks
We should check for memory leaks with various tools.
One good tool is the Chrome dev tools, which has the Performance to show what’s using memory in our app.
We can also check for memory usage of a tab with the Chrome Task Manager.
Timeline recordings, visualize memory usage over time.
Heap snapshots help us identify detached DOM trees.
Allocation timeline recordings let us find out when a new memory is being allocated in our JS heap.
We know that we have memory leaks if the memory usage increases over time until all available memory is used.
Use Web Workers for Intensive Tasks
If we have intensive tasks on our app, we can use web workers to run them in the background.
It works by sending input to the worker and then when the worker is done, the results is sent back to the main app.
They work on a different thread so they won’t hold up the main thread.
Beware of Computational Complexity
We should be aware of computational complexity of the algorithms we’re using.
Things like nested loops and other slow code should be avoided.
Simplify
If we can write something in a simpler way, then we should do so.
Avoid Recursive Calls
If there’s an iterative way to do something instead of recursion, then we should use iteration.
It’s easier to read and the performance is good.
Regex
We can use regex to search for patterns in strings.
So we can use them to extract information.
For instance,e we can write:
str.replace(/\s+/g, '');
to trim whitespace.
We can also check email address format with:
function validateEmail(email) {
const re = /\S+@\S+\.\S+/;
return re.test(email);
}
Use Search Arrays
We can search arrays with the find
function.
For example, we can write:
let array = [1, 2, 3, 4, 5];
let found = array.find((element) => {
return element > 2;
});
to find elements in an array.
We can also use this to avoid switch
statements by checking for something in an array instead of using each array entry as a case
.
Use Google Lighthouse
Lighthouse is a good tool for checking the performance of our browser app.
It checks for performance, accessibility, best practices, and SEO.
Lighthouse runs in Chrome dev tools in the Lighthouse tabs and it’s also available as a Node package so we can run the checks automatically.
Google PageSpeed
Google PageSpeed lets us understand a website’s performance optimizations and find areas that we can improve on.
It’s used to identify issues with compliance with Google’s web performance best practices.
JavaScript Navigation Timing API
The JavaScript navigation timing API lets us measure the performance of our website.
We can use it by writing:
const perfData = window.performance.timing;
const pageLoadTime = perfData.loadEventEnd - perfData.navigationStart;
We just subtract the loadEventEnd
and navigationStarty
timestamps to get the loading time.
We can also calculate request response time with:
const connectTime = perfData.responseEnd - perfData.requestStart;
and page rendering time with:
const renderTime = perfData.domComplete - perfData.domLoading;
This describes the level 1 API, which is deprecated, but level 2 is coming.
We can use this until level 2 is available.
Test Our Code
We should test our code with unit tests, integration tests, and user interface tests.
Unit tests test small parts of the code like functions.
Integration tests test bigger parts of the code like multiple functions or classes.
UI tests test from the perspective of the user but in an automated fashion.
Clicks and visual checks are done.
Conclusion
We should make sure the performance of our app is good.
Also, we should test our code in various ways.