Introduction

Today, I am going to elaborate on a few tips for JavaScript programmers. These may help you to code better quality, easy to maintain with better performance. I would recommend reviewing my earlier post Misconception about JavaScript to get better results.

Always End a Statement with Semicolon

In JavaScript it is not required to close a statement with a semicolon (;), a new line will also serve the purpose. But it is highly recommended to close each statement with a semicolon. This becomes particularly critical when you go for minification. It not only makes your code clean, but it is also considered to perform relatively better.

Single Quotation or Double Quotation for String Values

There is no difference either you use a single quotation or double quotations to represent a string. Even you can use both in a program, but it is recommended to use only one of them in a project. I personally recommend using a single quotation.

Explicit Variable Declaration

It is highly recommended to always declare a variable with var instead of using implicit variable declaration. Keep in mind if you use some variable name, JavaScript considers it as a global variable.

Use Strict Mode

It is highly recommended to use strict mode. It can be invoked by using the following statement in code: "use strict"; It makes JavaScript code secure, clear, and reliable. It is not guaranteed, but with strict mode code is considered to perform better.

Validation of JavaScript

Now many IDEs provide JavaScript validation, even you can use tools/sites like JSLint with manual efforts.

Avoid Expensive Task in Main Thread

JavaScript is basically single-threaded. So try to avoid tasks like long loops in the main thread instead try to use Web Worker. Web Worker is executed by the browser as a background task.

False Result

If you check any of the following in condition, they will return false: null, false, 0 undefined, NaN, and empty string. It is interesting that Infinity will return true.

Operator Precedence

Like most of the languages JavaScript has the following operator precedence for main operators:

Short Circuit Operators

JavaScript has && and || operators are short circuit.

Immediately Invoked Function Expressions (IIFE)

Immediately Invoked Function Expressions (IIFE) are executed right after loading automatically.
  1. (function sayHello()
  2. {
  3. alert(‘Hello’);
  4. })();

    Working with JSON

    JavaScript Custom Objects are not JSON. JSON cannot have functions, it is a data-interchange format, and JavaScript supports JSON, but old browsers may have old JavaScript Engine which may not support it. To JSON object from string use JSON.parse and to convert JSON object to the string, we can use JSON.stringify. Consider using JSON to handle complex data.

    Constructor for Custom Objects

    It is recommended to use Constructor to initialize and create objects instead of creating an object by directly assigning value to properties dynamically. It will make your code clean, easy to maintain, and faster. Changing the schema of an object is relatively slow.

    Adding Extension Methods to JavaScript Core

    We can add new features in existing JavaScript Core like the following example, but it is not recommended to change the core library.
    1. String.prototype.lengthSquare = function()
    2. {
    3. return this.Length * this.length;
    4. };
      Strict Equality Operator === is preferred over Equality Operator ==
      It is preferred to use === over == until unless we don’t have to compare data of different types. Furthermore, in general === is considered to have better performance.

      Array

      In JavaScript Array is a datatype. When playing with arrays please consider the following:

      Default Parameter Value

      JavaScript does not provide any feature to specify a default value for the parameter, but it allows to skip parameter. So we can check and assign default value manually. A good hack is to use conditional or operator, if the parameter has been provided to function then its value will be used otherwise provide value will be assigned to the parameter as default value.
      1. function myFunction(parameter)
      2. {
      3. parameter = parameter || 0;
      4. }

        Module Pattern

        Module Pattern is a very good option if you want to control access to functions and data elements. Furthermore, Modules are very helpful if you want to create some common custom repository or common library in your project.

        DOM Access

        DOM manipulation in JavaScript is always slow. This case cannot be avoided but can be optimized by considering the following:

        Minification and Bundling

        It is always recommended to go for minification and bundling of resources like JavaScript and CSS. It not only decrease load time, but it also reduces network cost. Don’t forget to add minification safe syntax and practices even you are not planning for Minification and Bundling.

        Commenting and Beautification

        For production, it is recommended to not have extra spacing and comments in JavaScript. It costs extra resources including bandwidth, processing. But for maintenance, it will be preferred to comment code particularly complex code, indent code, create regions, proper indention. If you are going for minification then these will be removed from the minified version.

        JavaScript Code Placement

        Please consider the following recommendations for JavaScript placement in the project:
        Important Readings
        If someone is interested to master a tool then it is always required to explore a tool thoroughly. I may recommend reviewing the following topics again (every item is a complete topic):
        Miscellaneous Tips