Javascript tips and tricks you should be aware
By NTh Hai - 15 min read
JS, also known as JavaScript, enables the implementation of complex functionalities on web pages. While many developers understand the significance of a minified JavaScript file, only a few are familiar with the concept of optimized JavaScript code. Optimized code involves the clever programming of logical operations and small hacks to enhance performance, speed, and efficiency, ultimately saving time.
I have collected some tips and tricks for optimizing Javascript to improve JS performance and improve execution time without affecting server resources. May as well save it here as well as in my head.
Use Array Filter
It is a small hack to filter out bucket of elements from the array pool. This method creates an array filled with all array elements that pass a test (provided as a function). According to requirement create a callback function for non-required elements.
In below example the bucket elements are null and are ready to get filtered out.
Example:
schema = ["hi","ihaveboyfriend",null, null, "goodbye"]
schema = schema.filter(function(n) {
return n
});
Output: ["hi","ihaveboyfriend", "goodbye"]
Using String replace function to replace all the values
The String.replace() function allows you to replace strings using String and Regex.
Basically this function replaces the string at its first occurrence. But to replace all using replaceAll() function, use /g at the end of a Regex:
Example:
var string = "login login";
console.log(string.replace("in", "out")); // "logout login"
console.log(string.replace(/in/g, "out")); //"logout logout"
Convert to floating number without killing performance
Often we use math.floor, math.ceil and math.round for eliminating decimals. Instead of using them use “~~” to eliminate decimals for a value.
It is also helpful in increasing performance when it comes to micro optimizations in a code.
Example:
Use
~~ (math.random*100)
Instead of
math.round(math.random*100)
Using length to delete empty in an array
This technique will help you in resizing and emptying an array.
For deleting n elements in an Array, use array.length.
array.length = n
See this example:
var array = [1, 2, 3, 4, 5, 6];
console.log(array.length); // 6
array.length = 3;
console.log(array.length); // 3
console.log(array); // [1,2,3]
For **emptying array** use
array.length = 0;.
Example:
var array = [1, 2, 3, 4, 5, 6];
array.length = 0;
console.log(array.length); // 0
console.log(array); // []
Merging arrays without causing server load
If your requirement is of merging two arrays, use Array.concat() function
For merging two arrays:
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
console.log(array1.concat(array2)); // [1,2,3,4,5,6];
This function works best for small arrays.
To merge large arrays we use
Array.push.apply(arr1, arr2)
Reason is using Array.concat() function on large arrays will consume lot of memory while creating a separate new array.
In this case, you can use Array.push.apply(arr1, arr2) which instead will merge the second array in the first one, hence reducing the memory usage.
Example:
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
console.log(array1.push.apply(array1, array2)); // [1,2,3,4,5,6];
It will also optimize the performance of your Javascript code irrespective of size of array.
Use splice to delete array elements
This is probably the one of the best optimization tips for javascript. It optimizes speed of your JS code.
Using splice instead of delete is a good practice, it will save some”null/undefined space” in your code.
The downside of using delete is it will delete the object property, but will not reindex the array or update its length, leaving undefined values. Also it consumes a-lot of time in execution.
Using splice
Example
myArray = ["a", "b", "c", "d"]
myArray.splice(0, 2) ["a", "b"]
Result: myArray ["c", "d"]
Checking values in an Object
To check whether an object is empty or not, use
Object.keys(YOUR\_OBJECT).length
// 0 returns if object is empty
Following code return the number of elements in an Object.
Cache the variable
Caching the variable tremendously increase javascript performance.
Everytime we use document.getElementById() or getElementsByClassName(), JS travels through all elements repeatedly upon each similar element request.
In Order to boost performance, cache your selections to some variable (if using the same selection multiple times).
Example:
var cached = document.getElementById('someElement');
cached.addClass('cached-element');
It is a simple optimization tip with drastic impact on performance, recommended for processing large arrays in loop(s).
Use switch case instead of if/else
Generally switch cases are used over if/else statements to perform almost the same tasks.
The fact that in switch statements expression to test is only evaluated once, execution time becomes less for the script compared to if/else where for every if , it has to be evaluated.
Short-circuits conditionals
Short circuiting is when a logical operator doesn't evaluate all its arguments.
The code
if (loggedin) {
welcome\_messege();
}
Make it short by using combination of a verified variable and a function using && (AND operator) in between both.
Now above code can be made in one line
loggedin && welcome\_messege();
Default values using || operator
In JS there is a basic rule of having a default value otherwise process will halt at undefined values.
To provide default value in a variable use || to stay away from this most common issue.
var a = a || 'hello'
The developer must check whether there are any conflicting values that might be passed to the function to avoid Bugs.