Best Practices in JavaScript

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 the 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:

var txt = '{ "employees" : [' +
'{ "firstName":"Rao" , "lastName":"Duvvara" },' +
'{ "firstName":"Rama" , "lastName":"Rao" },' +
'{ "firstName":"Divya" , "lastName":"Rawat" } ]}';

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

//is transformed to

Example 2

// Semicolon Insertion
var foo = function(){

Example 3

{ 1
2 } 3
// is transformed to
{ 1
;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

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.

// JavaScript Code Snippet
Var names = [ 'Ram', 'mohan', 'Sashi'];
Use braces for key => value arrays and objects/properties.
Var programmer = {'name':'jagan mohan', 'url':'','girl':'Ruhi'};

Rule 6 : Be Careful while using type of

The typeof operator returns a string that identifies the type of its operand.

Example 1: typeof 17.6

produces 'number'.


Example 2: typeof null

returns 'object' instead of 'null'.

A better test for null is simply:
my_value === null

A bigger problem is testing a value for objectness. typeof cannot distinguish between null and objects, but you can because null is false and all objects are true:

if (my_value && typeof my_value === 'object') {
// my_value is an object or an array!

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

//Falsy values are not interchangeable.
var myObject = {};
var value = myObject[name];
               if (value === null) {
               console.log(name + ' not found.');

Up Next
    Ebook Download
    View all
    View all