JavaScript or JS helps implement complex things on web pages. Many of the developers know the importance of an minified Javascript file but few are aware of an Optimized Javascript code.
An optimized code is a combination of smartly programmed logics and small hacks to optimize performance, speed and save time.
Here are sweet 16 JS hacks and tips for developers for optimizing Javascript to improve JS performance and improve execution time without affecting server resources.
1. 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"]
This hack will save some time and lines of codes for developers.
2. 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"
3. Use breakpoints and Console for Debugging
With the help of breakpoints or debugging points you can set multiple barriers to rectify source of error at every barrier.
Press F11 for next call function and f8 to resume script execution.
You can also check what dynamic values are generated by a function, using console and can check output on different values.
4. 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)
5. 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); // []
This technique is mostly preferred over any other methods to resize/unset the array elements and is one of the best javascript practices most of the developers follow.
6. 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.
7. 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"]
8. 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.
9. 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).
Check this link for performance results.
10. 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.
11. 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();
12. Getting the last item in the array
Array.prototype.slice(begin, end) is used to cut arrays when you set the start and end arguments. But if you don't set the end argument, this function will automatically set the max value for the array.
A smart hack is it can also accept negative values and by setting a negative number as begin argument, you will get the last elements from the array.
var array = [1, 2, 3, 4, 5, 6];
console.log(array.slice(-1)); // [6]
console.log(array.slice(-2)); // [5,6]
console.log(array.slice(-3)); // [4,5,6]
13. 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.
14. Beautifying JS code
For beautifying your Javascript code use jsbeautifier. It formats a clumsy JS code into well structured code.
Code before Beautifying
Code after Beautifying
15. Checking JS Performance
To check how well a Javascript code is performing and share results use jsperf. It is easiest way to create and share testcases.
16. Online javascript editor
Jsfiddle and jsbin is a tool for experimenting with your Javascript code and other web languages.
It is also a code sharing site. As you type into one of the editor panels the output is generated in real-time in the output panel.
These are some useful hacks and tips for optimizing javascript performance. It is not mandatory to use them all the time because cases and conditions will vary. If you have tricks other than these, do share with us in comment section.