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:
- Grouping ()
- Not!
- Arithmetic Operators
- Comparison Operators
- AND && Operator
- OR || 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.
- (function sayHello()
- {
- alert(‘Hello’);
- })();
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.
- String.prototype.lengthSquare = function()
- {
- return this.Length * this.length;
- };
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:
- Use split instead of delete to remove an element from the array.
- Use push to add a new element at end of the array, by the way, myArray[myArray.length]=somevalue; will do the same.
- Use unshift to insert a new element at the start of the array.
- On arrays use a simple index-based loop instead of a loop iterator. A simple loop may give better performance.
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.
- 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 the 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 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 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:
- 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 the bottom of HTML.
- It is a must to address JavaScript file caching at the browser side.
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):
- 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 a future article.
- Proper code indention and region where possible.
- We may use a switch instead of 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 the last option as it is slow and has security issues.
- Avoid the statement, its usage is generally discouraged. It is forbidden in strict mode.
- Declare variables outside the loop.
- It is better to use Custom objects instead of defining too many global variables.
- If you are interested in code high-performance application then try to avoid dynamically typing. Simple, use the 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 the future to migrate your existing code very easily.