A few months ago, we did training on some of the fundamentals of writing proper Javascript. From that training session, we decided to note down a few core guidelines:

Avoid Global Variables

  • Minimize the use of global variables.
  • This includes all data types, objects, and functions.
  • Global variables and functions can be overwritten by other scripts.
  • Use local variables instead, and learn how to use closures.

Always Declare Local Variables

  • All variables used in a function should be declared as local variables.
  • Local variables must be declared with the var keyword, otherwise they will become global variables.

Declarations on Top

It is a good coding practice to put all declarations at the top of each script or function. This will:

  • Give cleaner code
  • Provide a single place to look for local variables
  • Make it easier to avoid unwanted (implied) global variables
  • Reduce the possibility of unwanted re-declarations
// Declare and initiate at the beginning
var firstName = "",  
    lastName = "",
    price = 0,
    discount = 0,
    fullPrice = 0,
    myArray = [],
    myObject = {};

Initialise Variables

It is a good coding practice to initialise variables when you declare them. This will:

  • Give cleaner code
  • Provide a single place to initialise variables
  • Avoid undefined values
// Declare and initiate at the beginning
var firstName = "",  
    lastName = "",
    price = 0,
    discount = 0,
    fullPrice = 0,
    myArray = [],
    myObject = {};

Never Declare Number, String, or Boolean Objects

Always treat numbers, strings, or booleans as primitive values. Not as objects.

Declaring these types as objects, slows down execution speed, and produces nasty side effects:

var x = "John";  
var y = new String("John");  
(x === y) // is false because x is a string and y is an object.

//The above is minor - check this:

var x = new String("John");  
var y = new String("John");  
(x == y) // is false because you cannot compare objects.

Don't Use new Object()

Use {} instead of new Object()
Use "" instead of new String()
Use 0 instead of new Number()
Use false instead of new Boolean()
Use [] instead of new Array()
Use /()/ instead of new RegExp()
Use function (){} instead of new function()

Beware of Automatic Type Conversions

Beware that numbers can accidentally be converted to strings or NaN (Not a Number).

JavaScript is loosely typed. A variable can contain different data types, and a variable can change its data type:

var x = "Hello";     // typeof x is a string  
x = 5;               // changes typeof x to a number

"Hello" - "Dolly"    // returns NaN

Use === Comparison

The == comparison operator always converts (to matching types) before comparison.

The === operator forces comparison of values and type:

0 == "";        // true  
1 == "1";       // true  
1 == true;      // true

0 === "";       // false  
1 === "1";      // false  
1 === true;     // false  

Use Parameter Defaults

If a function is called with a missing argument, the value of the missing argument is set to undefined.

Undefined values can break your code. It is a good habit to assign default values to arguments.

function myFunction(x, y) {  
    if (y === undefined) {
        y = 0;
    }
}

End Your Switches with Defaults

Always end your switch statements with a default. Even if you think there is no need for it.

switch (new Date().getDay()) {  
    case 0:
        day = "Sunday";
        break;
    case 1:
        day = "Monday";
        break;
    case 2:
        day = "Tuesday";
        break;
    case 3:
        day = "Wednesday";
        break;
    case 4:
        day = "Thursday";
        break;
    case 5:
        day = "Friday";
        break;
    case 6:
        day = "Saturday";
        break;
    default:
        day = "Unknown";
}