X

JavaScript tips and tricks, Part 2

  1. Minify your code

Minifying your code makes it smaller in size which increases the website’s loading speed, which increases the ranking of the website in search engine and so on. There are many tools, even online ones, which allow you to minify JavaScript. Minification itself refers to modifying the code from a human-friendly version to a version that works but takes the least amount of physical space (such as reducing all newlines, extra whitespaces and so on).

A tool that you can try out to see minification in action is: https://jscompress.com/

  1. Obfuscate your code

If you are worried that someone will take advantage of your JavaScript logic or try to copy,paste and enhance it you can obfuscate your JavaScript logic. This will make it a little bit harder for someone to understand the logic  behind your application. Obfuscation typically makes the logic harder to understand by renaming variables to random characters, performing different types of encodings and decodings to mask the source and so on.

  1. Avoid polluting the global scope by anonymous functions

In the previous part of the article, we have talked about how you may prevent polluting the global scope by using objects or classes. You can also wrap your logic within anonymous functions which are immediately called to leave the entire global scope intact. Here is a simple example of how you may achieve that:

// An anonymous function

(function () {

   var myVariable= 1;



// myVariable is defined within a local scope and does not pollute the window object

   console.log(window.myVariable);

   // undefined

   console.log(myVariable);

   // 1

})();

// Called immediately

You can use such immediately invoked functions in all kinds of cases when you want to create a new scope. You will still be able to use the variables defined in the parent scope but would create an entirely new scope to define new variables in the anonymous immediately invoked function. You can also use immediately invoked functions with the ternary operator. For example, you may want to execute some particular piece of logic if a condition is true and another piece of logic if it is not and also keep a separate scope for those pieces of logic. Below is an example of that usage:

divsShineRed ? (function() {

            jQuery("div").css("background-color", "crimson");

})() :  (function() {

            jQuery("div").css("background-color", "darkgreen");

})();

Huzoor Bux: I am a PHP Developer