Monday, 7 December 2015

Code Standards and Conventions for JavaScript Programmers

Code Standards and Conventions for JavaScript Programmers

Although, coding standards and general conventions are important, but in tools like JavaScript, where concept of code validation and or compilation is very weak, these things become very important. Generally, conventions like naming conventions, commenting and code indention may not give any benefit in performance (these will make your code easy to understand and easy to maintain), but coding standards can make a lot of difference.
I may recommend to review my previous article Tips for JavaScript Programmers, from there you can find few important good practices to standardize JavaScript code.  

Important Points

  • JavaScript is case sensitive.
  • Avoid special character in names. Dollar sign and underscore are exceptional cases where required.
  • Generally use camel case.
  • It is better to use complete descriptive name instead of abbreviations, except industry well know abbreviations and acronyms. Index variable like in for are also be an exception.
  • Use proper indention for coding, we generally use 4 character indention.
  • If possible the try to make your function limited to visibility of your screen. So in general 25 lines are more than enough.
  • Always consider minification and bundling.
  • We may try to avoid data type dependent naming.
  • We may try to use name similar to data provider. It is a debatable point as using names similar to data provide may cause security risk, but it will give you ease to maintain code.
  • Always address JavaScript Injection or Cross Site Scripting XSS.
  • Use proper spacing between operators and operands.

File Name

If your application is going to be hosted on Linux environment then keep in mind file names are also case sensitive there. But it is not similar for Windows, in windows file and director names are not case sensitive. It is better to end JavaScript file to have .js extension.

Local Variable

We may prefer following rules for local variables:
  • Use singular name in camel case for local variable of primitive type.
    var topicLength = 10000;
  • Use plural name in camel case for local variable of array and other collections.
    var coloNames = [“Red”, “Green”, “Blue”];

Global Variable

We may prefer following rules for global variables:
  • Use singular name in pascal case for local variable of primitive type.
    var TopicLength = 10000;
  • Use plural name in pascal case for local variable of array and other collections.
    var ColoNames = [“Red”, “Green”, “Blue”];

Private Variable

We may prefer following rules for private variables:
  • Use singular name in camel case starting with underscore for private variable of primitive type.
    var _topicLength = 10000;
  • Use plural name in camel case starting with underscore for private variable of array and other collections.
    var _coloNames = [“Red”, “Green”, “Blue”];

Public Function Name

For public functions, we may prefer to use camel case:
function sayHello(person){
    return ‘Hello ’ + person;
}

Private Function Name

For private functions, we may prefer to use camel case starting with underscore:
function _sayHello(person){
    return ‘Hello ’ + person;
}

Class Name

For classes, we may prefer to use constructor to create and initialize object (by the way, there is a good audience, whom are against new in JavaScript). We may prefer to us pascal case for class constructor name, but its variable may use camel case:
function Car(carName, carModle, carColor){
    this.name = carName;
    this.modle = carName;
    this.color = carName;  
    function carData(){
        return this.name + ‘ ‘ + this.modle + ‘ ‘+ this.color;
    }
}
var myCar = new Car(‘Hona’, ‘City’, ‘Blue’);
alert(myCar. carData ());

Module Name

For modules, we may prefer to use pascal case:
var Config = (function(){
   var baePath = ‘’;

   var _getPath = function(){
      return _basePath;
   };

    var _setPath = function(basePath){
      _basePath = basePath;
   };
    return{
        getPath: _getPath,
        setPath: _setPath
    };
})();

if Statement

It is better to avoid single line if. I always recommend to use parenthesis with if and else part even there is single statement.
if(condition){
    //do your action
}

Loop Statement

It is better to avoid single line loop. I always recommend to use parenthesis with for even there is single statement.
for(var i=0; i<=10; i++){
    //do your action
}

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.  

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. For file naming we may use camel case: viewName.js, controllerName.js, libraryName.js and etc.
  • 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.

return Statement

Make sure return statement and expression are on same line and end with semicolon.

Comment

For comments we may consider following:
  • Always comment your code, particularly functions and complex scenarios.
  • It is better to use single line comments using // instead of block comment syntax using /* … */.
  • It is better to comment before code.
  • It is better to end comment with full stop.

Sunday, 6 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() {
     alert(‘Hello’);
})();

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.

Array

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. 

Saturday, 5 December 2015

Misconception about JavaScript

There are lot of misconceptions about JavaScript. Let us discuss few of them. 

JavaScript is not Java

It is very much necessary to clear that JavaScript has no relation with Java. It was initially named as LiveScript. It has been compliance with ECMAScript 5 Language Specifications. Just keep in mind, both Java and JavaScript are different animals.

JavaScript is not Just a Web Development or Client Side Tool

JavaScript is a complete programming language and it is not only used in as front end technology, it has emerged as strong candidate for future in Server Side Development i.e. Node.js.  

JavaScript is not Typeless

JavaScript is not typless, like most scripting languages, it associates type with values, not with variables. It is described as Dynamic Typing. It has six primitive data types: Boolean, Number, String, Null, Undefined and Object

JavaScript is Object Oriented Language

Most of use thing JavaScript is a structural language, but in actual it is an Object Oriented Language. Everything in JavaScript is an object and it supports both of inheritance and aggregation. It is described as Prototype Based Object Oriented Programming Language.

Browser API is not part of JavaScript

Things like Window Object, Location Object, DOM are not part of JavaScript itself, these are browser features and JavaScript just provides API to use them. These API in general called as Browser API, and they can vary from browser to browser. And this dependency is main reason to have problems to program for cross browser site development.

Block Scope

Unfortunately, JavaScript does not respect block scope for undefined variables (variables without var, they are treated as global variables). So be careful with implicit variable declaration. Furthermore, in JavaScript block scope is at function level not set of curly brackets.

JavaScript is not Context Free

In general, we consider it does not matter either a line is ended with semicolon or not, but it can cause many issues particularly in case of minification.

Validation of JavaScript

Now many IDEs provide JavaScript validation, even you can use tools/sites like JSLint with manual efforts. It’s not bad idea to use JavaScript strict mode.

Synchronous

JavaScript is basically single threaded.

this Keyword

this keyword may refer to different things with respect to context. For example, in constructor this refers to object, in simple function this refers to window .

JavaScript Custom Objects are not JSON

JavaScript Custom Objects are not JSON. JSON cannot have functions, JSON is a data interchange format.

Closures

A closure is a function having access to the parent scope, even after the parent function has closed. Closures are very interesting feature and very similar to delegates with persisted state of outer function.

Debugging

It is little tricky yet very simple to debug JavaScript code. We may discuss this topic in detail in future articles.

Context and Scope are Different things

Context and Scope are different things, in simple we can say Scope defines accessibility and life span, on other hand Context refers to what and where.

JavaScript Libraries and Frameworks

There are lot of hot topics like Jquery/ Jquery UI/ Jquery Mobile, AngularJS/Ember, Knockout JS, Kendo UI, Node JS, Lo Dash, React JS, Chart JS, Ionic and etc. these all are libraries and or frameworks developed in JavaScript. These are add-ons not the competitors.

Thursday, 3 December 2015

Tips and Rules for Email

We are technical folks. We always like to talk about tools and technologies and of course, it should be focused mainly. But with this attitude we generally ignore few important things including communication skills.  I am going leave topic for open debate if it is Technical or Non-Technical topic. A good alternate title can be "Email Ethics".

Always Respond, Never React

 "You may not be able to control the events that occur during the day, especially those events that are unexpected and challenging. But, you definitely have a choice whether you are going to allow these events to ruin your day, and how you are going to face these challenges."
Barry Gottlieb
Don't send e-mail when you're tired or furious. E-mail can easily be angry, hurtful, or critical. It takes a lot of time to undo the damage.

Delete Unnecessary Email

You have several choices, Scan headers, and delete/archive everything you don't need to know or act upon materially. It's okay to ignore an e-mail the same way you might a letter or a phone message.

Attachments

When replying to an email be sure to make sure if you want to send the attachment already with the email. Otherwise KINDLY use the reply button instead of forward. Also when sending an attachment, make sure the reader is able to open the attachment - use the lowest common denominator for sending files. Mention Attachments with brief description and use logical name for attachments.

Targeted and Relevant Audience Only

 Treat email like letters and phone calls; wait for a calmer moment to respond. Remove irrelevant people from To/CC/BCC. Rule of thumb; think once before “Reply All”.

Email Subject

Be specific with Subject. Ideally subject must be relevant to email. A good idea is to begin subject with the project name, followed by context. Many among us are working on multiple projects.

Email Signature

Keep proper email signatures. It is recommended for everyone to keep the same signature format with/without logo within a company. And if possible then consider including name of your backup resource.

A Stitch in Time

Take advantage of the timesaving bells and whistles your e-mail program offers. Be responsive to your emails and try to respond within reasonable timeframe.

Avoid Time Wastage

There is considerable time being wasted which must be conserved so that it can be put to other important things. Email is for communicating, but communicating effectively and clearly.

Address Book

Keep an up-to-date address book, and never delete names and addresses. You never know when someone will come back into your digital life.

Break the chain

Chain email is not only tacky, it's banned on many corporate networks. Try and keep the chains small. For example, if this is the fifth revision of FS then please state so in the Subject line.

Email is not for Chatting

Email is not a communication medium for rapid interactive communication, if you need rapid interactive discussion then it is better to consider some other alternatives like phone call or IM tool.

General Rules

In general it is always good to consider following, believe me, these may help you directly or indirectly.
·         Always perform spelling and grammar checking. Few email clients provide the facility to perform spelling checking before sending email.
·         Avoid shortcuts, emoticons and slangs.
·         If you are on leaves or out for long meeting then consider features like auto responder.