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 FilterIt 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:
1schema = ["hi","ihaveboyfriend",null, null, "goodbye"] 2schema = schema.filter(function(n) { 3 return n 4 });
1Output: ["hi","ihaveboyfriend", "goodbye"]
This hack will save some time and lines of codes for developers.
2. Using String replace function to replace all the valuesThe 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:
1var string = "login login"; 2console.log(string.replace("in", "out")); // "logout login" 3console.log(string.replace(/in/g, "out")); //"logout logout"
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 performanceOften 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:
1Use 2~~ (math.random*100) 3Instead of 4math.round(math.random*100)
This technique will help you in resizing and emptying an array.
For deleting n elements in an Array, use array.length.
1array.length = n 2See this example: 3var array = [1, 2, 3, 4, 5, 6]; 4console.log(array.length); // 6 5array.length = 3; 6console.log(array.length); // 3 7console.log(array); // [1,2,3] 8For emptying array use 9array.length = 0;.
Example:
1var array = [1, 2, 3, 4, 5, 6]; 2array.length = 0; 3console.log(array.length); // 0 4console.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 loadIf your requirement is of merging two arrays, use Array.concat() function
For merging two arrays:
1var array1 = [1, 2, 3]; 2var array2 = [4, 5, 6]; 3console.log(array1.concat(array2)); // [1,2,3,4,5,6];
This function works best for small arrays.
To merge large arrays we use
1Array.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:
1var array1 = [1, 2, 3]; 2var array2 = [4, 5, 6]; 3console.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 elementsThis 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
1myArray = ["a", "b", "c", "d"] 2myArray.splice(0, 2) ["a", "b"] 3Result: myArray ["c", "d"]
To check whether an object is empty or not, Â use
1Object.keys(YOUR\_OBJECT).length 2// 0 returns if object is empty
Following code return the number of elements in an Object.
9. Cache the variableCaching 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:
1var cached = document.getElementById('someElement'); 2cached.addClass('cached-element');
It is a simple optimization tip with drastic impact on performance, recommended for processing large arrays in loop(s).
Check http://jquery-howto.blogspot.in/2008/12/caching-in-jquery.html
for performance results.
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 conditionalsShort circuiting  is when a logical operator doesn't evaluate all its arguments.
The code
1if (loggedin) { 2welcome\_messege(); 3 }
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
1loggedin && welcome\_messege();
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.
1var array = [1, 2, 3, 4, 5, 6]; 2console.log(array.slice(-1)); // [6] 3console.log(array.slice(-2)); // [5,6] 4console.log(array.slice(-3)); // [4,5,6]
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.
The developer must check whether there are any conflicting values that might be passed to the function to avoid Bugs.
14. Beautifying JS codeFor 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 PerformanceTo 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 editorJsfiddle 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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4