Best Practices in JavaScript

Introduction

 
Recently I attended a JavaScript day event at the Delhi Chapter of C# Corner and began exploring JavaScript code more in my current working products using Dojo. I explored some lessons that have been learned and I feel I have a good workable set of JavaScript standards. I have decided to present these in a series of posts. 
 
Rule 1: Use JSON. parse method instead of eval
 

JSON Parsing

 
JSON is a subset of JavaScript and json.parse just parses JSON whereas eval( ) would leave the door open to all JS expressions. The advantage of JSON.parse is that it verifies the argument is correct JSON syntax. 
 
The eval() function can compile and execute any JavaScript. This represents a potential security problem. It is safer to use a JSON parser to convert a JSON text to a JavaScript object. A JSON parser will recognize only JSON text and will not compile scripts.
 

JavaScript Code Snippet

 
The eval() function uses the JavaScript compiler that will parse the JSON text and produce a JavaScript object. The text must be wrapped in parenthesis to avoid a syntax error as in the following:
  1. var txt = '{ "employees" : [' +  
  2. '{ "firstName":"Rao" , "lastName":"Duvvara" },' +  
  3. '{ "firstName":"Rama" , "lastName":"Rao" },' +  
  4. '{ "firstName":"Divya" , "lastName":"Rawat" } ]}';  
  5.   
  6. var obj = eval ("(" + txt + ")"); 
Rule 2: Remember the statements are affected by the automatic semicolon insertion (also known as ASI for brevity)
 

Semicolon Insertion

 
JavaScript syntax comes from C. In all other C-like languages, a block (a set of statements wrapped in curly braces) creates a scope. Variables declared in a block are not visible outside of the block. JavaScript has a mechanism that tries to correct faulty programs by automatically inserting semicolons. Do not depend on this. It can mask more serious errors.
 
First of all, you should know which statements are affected by the automatic semicolon insertion (also known as ASI for brevity):
  • Empty statement
  • Var statement
  • Expression statement
  • Do-while statement
  • Continue statement
  • Break statement
  • Return statement
  • Throw statement
Java Script Code Snippet
 
Example 1
  1. a+b  
  2. c  
  3. //is transformed to  
  4. a+b;  
  5. c; 
Example 2
  1. // Semicolon Insertion  
  2. var foo = function(){  
  3. return{  
  4. status:"returned"  
  5. };  
  6. };  
  7. console.log(foo()); 
Example 3
  1. { 1  
  2. 2 } 3  
  3. // is transformed to  
  4. { 1  
  5. ;2;}3; 
Rule 3: Always use "===" and "!==" for comparison
 
"===" and "!==" are strict comparison operators.
 
JavaScript has both strict and type-converting equality comparisons. For strict equality the objects being compared must have the same type and:
  • Two strings are strictly equal when they have the same sequence of characters, the same length, and the same characters in corresponding positions.
  • Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
Code Snippet in Java Script
  • '' == '0' // false
  • 0 == '' // true
  • 0 == '0' //true
  • 0==false //true
  • 0===false //false, because they are of a different type
  • 1=="1" // true, auto type coercion
  • 1==="1' // false, because they are of a different type
Rule 4: Always prefer to use JSLint
 
Use the JSLint code quality tool for JavaScript
 
JSLint is a code quality tool for JavaScript. It takes a source text and scans it. If it finds a problem then it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems.
 
JSLint can be found at http://www.JSLint.com/.
 
Visual Studio has an add-in for JSLint that will allow you to check for errors at compile-time (or manually).
 
Rule 5 : Remember The Difference Between [] and { } in JavaScript Arrays
 
In some JavaScript libraries, I always wondered what was the difference between arrays using brackets ([]) and braces ({}).
 
Use brackets for an array of simple values.
  1. // JavaScript Code Snippet  
  2. Var names = [ 'Ram''mohan''Sashi'];  
  3. Use braces for key => value arrays and objects/properties.  
  4. Var programmer = {'name':'jagan mohan''url':'http://google.com','girl':'Ruhi'}; 
Rule 6: Be Careful while using a type of
 
The typeof operator returns a string that identifies the type of its operand.
 
Example 1: typeof 17.6
 
produces 'number'.
 
Unfortunately:
 
Example 2: typeof null
 
returns 'object' instead of 'null'.
 
A better test for null is simply:
 
my_value === null
 
A bigger problem is testing value for objectness. typeof cannot distinguish between null and objects, but you can because null is false and all objects are true:
  1. if (my_value && typeof my_value === 'object') {  
  2.    
  3. // my_value is an object or an array!  
  4.    

Rule 7: Rules to remember how to handle False values
 
Handle the False Values
 
JavaScript has a surprisingly large set of false values as mentioned below:
  • 0 Number
  • NaN (not a number) Number
  • '' (empty string) String
  • false Boolean
  • null Object
  • undefined Undefined
Java Script Code Snippet
  1. //Falsy values are not interchangeable.  
  2. var myObject = {};  
  3. var value = myObject[name];  
  4.                if (value === null) {  
  5.                console.log(name + ' not found.');