JavaScript Best Practices

It is important to write clean and manageable code all the time. In fact, the kind of dependencies we humans have on technology, I will go one step further and say that there is no excuse to write poor quality code.

Intentionally people don’t want to write poor quality code. However, we do see a lot of poor quality code getting written and that does seem to mount huge technical debt on the business.

The common reasons that I have seen for low quality code, are

  • The lack of availability of coding guidelines
  • The lack of awareness about the coding guidelines
  • The MYTH that following coding guidelines will take longer to deliver and hence this is something which can be taken care at later stage

By keeping that in perspective, I have listed the best practices that one must follow while coding in JavaScript. Also, I am committed to improve the overall quality of coding in JavaScript at the global level and would love to connect with people who are into the development of  important and critical software / solutions using JavaScript.

Naming Conventions

Variable Names

  • Choose a meaningful name so that the code is readable
  • Use camelCase while using multi-word variable names – for example currentState.
  • Start all the names with letters
    • Start variable name with $ or _ ONLY when you have a strong reason
  • Use UPPERCASE for the global variables and constants
  • Always capitalize the name of the constructor
  • You MUST NOT use reserved words

File Names

  • The files meant for defining the objects shall start with a Capital letter and follow the camelCase naming convention
  • Otherwise keep the file name to the lowercase letters with NO camelCase.

Statements and Declarations

Variable Declaration

  • Always use var to declare a variable
    • Sometimes people do tend to make use of let, which provides block level scope. However, when we don’t expect people to write huge methods or use too much nesting and use same name again and again, I feel that the usage of more popular cousin, var, is a better choice.
    • Use const keyword while defining constant references or primitive values.
      • Like let, const is also block scoped
  • Avoid global variables
  • Reduce global footprint by putting them into relevant Javascript Object, which will eventually form a JSON object
  • Put all the variable declarations at the top of the script or function
  • While declaring, always treat numbers, strings and boolean as primitive values, instead of Object. Remember that “cx-labs” and new String(“cx-labs”) are two separate things. Try comparing them to understand the difference.
    • Primitives are numbers, boolean, string, null and undefined. Rest of the things in Javascript are objects.

Initialization

  • Initialize variable when you declare them to ensure that you achieve the intended use all the time
  • Understand that undefined is NOT null.
    • To be null an object still need to be defined. It just indicates that there is no value assigned to the variable / object.

Switch Statement

  • Even if you don’t feel a need, consider ending your switch statement with the default

Breaking a Statement

  • Never break a return statement (into two or more lines) because javascript will think that you are returning (return;) unidentified.
    • If a statement is incomplete then javascript goes to the next line and tries to complete the expression / declaration.
  • By default Javascript tries to close statement at the end of the line. Hence, build a habit of using semicolons (;) explicitly.

Scoping

  • JavaScript doesn’t follow block scoping and hence you should try to declare variables / functions on top of the scripts

Functions and Objects

Functions and Objects are the main reason, why Javascript looks so strong. Hence, it is important to pay closer attention to these two concepts.

Definition

  • The optional arguments must be defined towards the end of the parameter lists
  • Wrap immediately invoked function expressions in parentheses as it improves the overall readability
(function () {
  console.log('This way I am more readbale.');
}());
  • Use default parameter syntax while defining function and avoid mutating function arguments
function findJobs(jobCriteria = {}) {
  // The code like jobCriteria = jobCriteria || {}; can work, but it is not a great idea to have such code 
}

Inheritance

  • Use extends on the classes to achieve inheritance
  • While inheriting, of course, you can override a method or a property of an object. However, you must perform the impact analysis and ensure that you are doing this consciously.
    • While overriding built-in objects you must pay extra caution.
      • Don’t override following properties
        • constructor
        • hasOwnProperty
        • isPropertyOf
        • propertyIfEnumerable

Class and Constructors

  • Instead of manipulating prototypes, always use class
  • If a constructor has a lot of parameters, consider using a JSON objects to pass the parameters. Of course, you can group them into multiple objects, if it makes sense.
  • Whenever there is potential for chaining on a method, return this object from the method

Objects

  • By default, the window object is considered the default object. Hence, when you call methods like setInterval, setTimeout, onload, alert, etc. you must interpret that they are equivalent to window.setInterval, window.setTimeout, etc.
  • While creating an object, if the object declaration is long (say it has more than 3 properties) and it may not fit in single line then you should have one property on each line

Events

  • Most of the DOM events will have an event object passed along with it, which contains the general information about the event. Many times people are not aware of this and they end up passing extra parameters to get some of these properties

Performance

DOM Access and Manipulation

  • Watch out for the redundant access to DOM. For example, if you place a DOM query inside a loop, which could have been outside as well then that is not good

Instead of

for(var i = 0; i < arrayName.length; i++) {
   var myElement = document.getElementById(“myelement”);
   myElement.innerHtml += 'my element is: ' + i;
}

You should use following

var myElement = document.getElementById(“myelement”);
for(var i = 0; i < arrayName.length; i++) {
   myElement.innerHtml += 'my element is: ' + i;
}

Eliminate Redundancies

  • Instead of using the statements like
for(var i = 0; i < arrayName.length; i++) {
   myElement.innerHtml += 'my element is: ' + i;
}

Consider using

for(var i = 0, len=arrayName.length; i < len; i++) {
   myElement.innerHtml += 'my element is: ' + i;
}

Here you minimize the invocation of the length function.

  • Avoid usage of unnecessary variables. For example:

Instead of

var fullName = firstName + " " + lastName;
document.getElementById("demo").innerHTML = fullName;

Use

document.getElementById("demo").innerHTML = firstName + " " + lastName

Debugging

  • Identify expensive JavaScript functions and code blocks and replace them
    • Use timer methods like Console.time (to start the timer for the given label) and Console.timeEnd (to end the timer for the same label) methods to find out the elapsed time in a given piece of code. Thus you can experiment and improve the performance by using more efficient codes.
    • Use timeline, profiling, etc. capabilities of the developers tool to identify more such bottlenecks
  • Use console.log instead of alert to know the value of a variable while trying to debug
  • Ensure that you remove console.log or console.warn or similar statements before making the code production ready

Loading of Javascript Files

  • Place javascripts at the bottom of your HTML page
    • The primary goal is to ensure that you don’t make your users wait. Hence, load the HTML contents as quickly as possible.

Readability

  • Avoid using shortcuts

Instead of

If (valueIsTrue) 
 functionCall();
  • Use curly brackets to enclose the statements
If (valueIsTrue) {
  functionCall();
  anotherFunctionCall()
}
  • Ensure consistent indentation of code blocks. I usually recommend 1-tab space ( and I set 1-tab space to 4-spaces).
  • Put the opening bracket at the end of the first line of a function or Object or any code block
  • Put the closing brackets on the new line with appropriate indentation
  • Comment your code
    • I recommend using /* */ style for function headers and // for the internal statement.
    • Also, it improves readability when you don’t have any comments on the starting and ending line of the comment block.
  • When there are multiple variables to be declared, exclude the repeating var keyword and use comma to separate variables.
    • I do like variables to appear on new (nextline) line. Sometimes people put the variables on the same line and that looks cluttered.
  • Always put ONE space around operators (=, /, *, +, -, etc.)
  • There shall be one space after comma (e.g. in the arguments and parameters)
  • The comma (,) and semicolon (;) should not have any preceding space
  • Keep the line length to less than 80-characters

Things to Avoid

  • Avoid using == operator for the equality comparison, use === instead to ensure that you compare for value as well as type of the object.
    • The == operator always converts the values to the matching types before they compare
    • Similarly, avoid using != and use !== instead
  • Avoid using new operator, unless you really need to use them.
    • Sometimes people use new operator (e.g. new Object()) to create an empty object.
    • Instead you shall consider using
      • {} – for new Object
      • “” – for new String()
      • false – for new Boolean()
      • [] – for defining an empty array (new Array())
      • /()/ – for new RegExp()
      • function(){} – for new Function()
    • Also, note that you should not use filler space between the braces or brackets or the empty object
  • Avoid trailing comma in objects, arrays, etc
    • For example – var technologies = [“CSS”, “HTML”, “Javascript”, ], the last comma is not good. Some of the browsers may give error.
  • Avoid using with statement
  • Avoid using assignments (=) inside conditionals and be watchful of this

What next?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s