Monday 7 December 2015

Tips for JavaScript Programmers

Today, I am going to elaborate few tips for JavaScript programmers. These may help you to code of better quality, easy to maintain with better performance. I would recommend to review 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 semicolon (;), a new line will also serve the purpose. But it is highly recommended to close each statement with semicolon. This becomes particularly critical when you go minification. It not only make your code clean, it is also considered to perform relatively better.

Single Quotation or Double Quotation for String Values

There is no difference either you use 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 to use single quotation.   

Explicit Variable Declaration

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

Use strict Mode

It is highly recommended to us strict mode. It can be invoked by using following statement in code: "use strict"; It make 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 task like long loops in main thread instead try to use Web Worker. Web Worker are executed by browser as background task.

False Result

If you check any of 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 languages JavaScript has following operator precedence for main operators:
  • Grouping ()
  • Not !
  • Arithmetic Operators
  • Comparison Operators
  • AND && Operator
  • OR || Operators

Short Circuit Operators

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

Immediately Invoked Function Expressions (IIFE)

Immediately Invoked Function Expressions (IIFE) are executed right after loading automatically.
(function sayHello() {

Working with JSON

JavaScript Custom Objects are not JSON. JSON cannot have functions, JSON 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 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 object by directly assigning value to properties dynamically. It will not only make your code clean, easy to maintain and faster. Changing schema of an object is relatively slow.

Adding Extension Methods to JavaScript Core

We can add new features in existing JavaScript Core like following example, but it is not recommended to change core library.
String.prototype.lengthSquare = function()
      return this. Length * this.length;

Strict Equality Operator === is preferred over Equality Operator ==

It is prefer to use === over == until unless we don’t have to compare data of different types. Furthermore, in general === is considered to have better performance.


In JavaScript Array is a datatype. When playing with arrays please consider following:
  • Use split instead of delete to remove an element from array.
  • Use push to add new element at end of array, by the way myArray[myArray.length]=somevalue; will do same.
  • Use unshift to insert new element at start of array.
  • On arrays use simple index based loop instead of loop iterator. Simple loop may give better performance.

Default Parameter Value

JavaScript does not provide any feature to specify default value for 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 parameter has been provide to function then its value will be used otherwise provide value will be assigned to parameter as default value.
function myFunction(parameter){
    parameter = parameter || 0;

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 following:
  • Cache references, e.g. save a reference to call in variable and then use this variable again and again instead of calling method to get reference again.
  • When playing with control addition dynamically, it is better to initialize all required properties of a control before adding to DOM.
  • For existing objects, make display:none before changes, and then restore old value of display.

Minification and Bundling

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

Commenting and Beautification

For production, it is recommended to not to 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 miification then these will be removed from minfied version.

JavaScript Code Placement

Please consider following recommendations for JavaScript placement in project:
  • It is always recommended to avoid inline JavaScript coding. Please consider placing JavaScript code in separate file/s.
  • It is better to place script reference and or code at bottom of HTML.
  • It is must to address JavaScript file caching at browser side.

Important Readings

If someone is interested to mastering a tool then it is always required to explore a tool thoroughly. I may recommend to review following topics again (every item is a complete topic):
  • Error Handling
  • Regular Expressions
  • Object Oriented Programming
  • Module Pattern
  • DOM
  • Browser API
  • Local Storage
  • Offline Browsing
  • Event
  • Form and Client Side Validation
  • AJAX (Asynchronous JavaScript And Xml)
  • Animation, Graphics, SVG, Canvas
  • Cookies
  • Web Workers
  • JavaScript Libraries
  • Debugging
  • JavaScript Code Validation/Error Checking

Miscellaneous Tips

  • It is always good to device some naming conventions. We will have a detailed manuscript on this topic in future article.
  • Proper code indention and region where possible.
  • We may use switch instead if cascade if wherever possible, because it is cleaner and faster.
  • String concatenation is an expensive action.       
  • Be specific to use eval(). Use this feature as last option as it is slow and have security issues.
  • Avoid with statement, its usage is generally discouraged. It is forbidden in strict mode.
  • Declare variable outside the loop.
  • It is better to use Custom objects instead of defining too many global variables.
  • If you are interested to code high performance application then try to avoid dynamically typing. In simple, use same type of variables in an expression.
  • Never forget to address JavaScript cache management to handle script changes in web applications.
  • I may highly recommend, to get prepared for ECMAScript 6. If possible then try to code close to this standard, this habit may help you a lot in future to migrate your existing code very easily. 

No comments:

Post a Comment