Wednesday, September 28, 2016

JavaScript: Best Practices

Use Strict Mode

'use strict'

JavaScript will not automatically define variables at global scope when such variables are assigned to.

undefined vs. null

Programmer should set a variable to null (for an object).
JavaScript sets an uninitialized variable to undefined. Do not programmatically set variable to undefined.

Math operations

Number.toFixed(2) ; // always round before comparing floating point

Function Expressions

Specify function name (instead of using an anonymous function) when using function expressions. That way, the runtime will correctly report the function in which the error occurred.

var aFunc = function myFunc() {};

Function Object Prototype

Instead of adding functions in function constructor, add functions via the prototype property so that they are not duplicated in every instance of the function object.

The prototype property is accessible when defining a function object using a constructor function. When function object is defined using a JSON object, prototype property is not directory available. It is available via jsonObject.__PROTO__ property.

Use IIFEs to avoid global namespace pollution

(function() {
  console.log("Execute immediately!");
}) ( );

To keep all logic within an application's namespace:

var myApp = {};

(function(ns) {
  // ns points to the global myApp object
  ns.name = "My app library";
})(myApp);

// myApp is the application's name space
console.log(myApp.name);

To guarantee a particular variable points to a certain object in our application code. Say we want make sure $ refers to jQuery library.

var myApp = {};

(function(ns, $) {
  ns.name = 'My app library';
  // $ === jQuery
})(myApp, jQuery);