This is the first part of a new blog series on the topic ‘Best Practice – JavaScript’. The series will focus on various aspects of the development process with JavaScript.

This article will cover the characteristics of JavaScript code quality and how we at AlfaPeople ensure we write maintainable JavaScript code for our clients.

A Look forward to the upcoming articles, which will cover the following topics:

Performance

  • High Performance JavaScript
  • Optimization technics for JavaScript

Tools & Utilities

Testing

  • Headless JavaScript testing
  • Testing frameworks: Mocha and Jasmine
  • Chutzpah (Visual Studio Extension)

Challenges with complex JavaScript

The increase in popularity of JavaScript, which results from the improved performance in modern browsers, the availability of solid frameworks /libraries, and new environments that can be addressed, such as server-side programming with Node.js, Windows App development, Client-Apps, etc.

As a programming language it definitely provides a huge potential, because you can implement more and more requirements with JavaScript.

The popularity and extended areas of application for JavaScript customizations in Dynamics CRM leads to a growing code-base, which bring new challenges for managing the code-base. Other programming languages, like C# or Java, already have a set of patterns and tools for development workflow. Only in recent years have these concerns gained more validity in the JavaScript community.

Maintainable Code

Why should a developer /team or the entire organisation be interested in maintainable code and why should these group invest in this area? The answer to this question based on the following find:

The maintainability of code is critical for any organisation because the time spending on reading and understanding the source code will increased in larger projects (in terms of lines of code, team size and /or duration).

This assumption and the general topic maintainable JavaScript and why we should care is covered in a wonderful talk by Nicholas Zakas.

When we set the goal to write “maintainable” code it must be defined what properties tells us if our code is maintainable or not. Stoyan Stefanov defines the following set of attributes that apply:

  • Is readable
  • Is consistent
  • Is predictable
  • Looks as if it was written by the same person
  • Is documented

Now that we have the “metrics” that separate maintainable code from bad code, we can focus on how to enforce these rules.

One option which addresses these concerns is a coding or style-guideline that is developed in the team /organisation and all developers are committed to this guidelines. The coding-guidelines defines the baseline for the code structure and code organisation like naming conventions (variables, functions), patterns to use (e.g.: IFEE) and patterns to avoided (e.g. global variables). The article Why Coding Style Matters by Nicholas Zakas is a great read for this topic.

The just published (and free) book “Speaking JavaScript” by Dr. Axel Rauschmayer covers this topic in great detail in chapter 26. The chapter contains a superb set of “Commonly Accepted Best Practices“. In this chapter, the author makes the very valid point, that in some cases is hard to accept, that no matter your personal preferences, you must always comply with set guidelines.

“The second rule is that, if you are joining an existing project, you should follow its rules rigorously (even if you don’t agree with them).”

Static Code Analysis

Another option to ensure the compliance of the coding rules is the use of a static code analysis tool. This tool parses the source code and generate warnings or errors whenever a code-fragment violates the convention.

JSHint is an excellent tool that provides this kind of static code analysis. A key feature of JSHint is the ability to configure the required or permitted options. The available options for JSHint could be found in the option-documentation. A good example of an option is the “curly”. If used, it will be required to put curly braces around blocks in loops and conditionals.

// bad

if( someCondition )

console.log("bad");

// better

if( someCondition ) {

console.log('better');

}

The options representing the applied set of rules, could be grouped in a “.jshintrc” file. This single file is easy to share and should be used in all projects in the entire organisation.

This is the .jshintrc file we use at AlfaPeople:

{

"strict": true,

"undef": true,

"unused": true,

"curly": true,

"eqeqeq": true,

"latedef": true,

"node": true,

"browser": true,

"noarg": true,

"newcap": true,

"immed": true,

"sub": true,

"forin": true,

"globals": {

"CrmFetchKit": false,

"Xrm": false,

"_": false

}

}

Copying the JavaScript source-code every time to the JSHint website to execute the analysis is a bit cumbersome. The real gain of this kind of tools is achieved when the code-analysis is automatically applied whenever the source-code is modified. There are tools and plugins available that allow the execution on the developer’s machine.

In the following, we will cover the setup of a build-task that invokes the JSHint node.js package form the command line to analyse our script files.

In the simplest situation, the developer execute the following command and JSHint will analyse the stated file and generate a simple report:

To manually invoke JSHint for every file is not a good development process. We improve this by using build-tools (the topic build-tools will be covered in our next blog-post): The execution of the of JSHint in multiple script files could be automated with the build-tool gulp (will be covered in details in a upcoming article). The following code (“gulpfile.js” see gist) will setup the task that will generate an error report when it detects a problem in one of the specified script files:

"use strict";

var gulp = require('gulp');

var gutil = require('gulp-util');

var stylish = require('jshint-stylish');

var jshint = require('gulp-jshint');

gulp.task('lint', function() {

// includes all .js-files, but will exclude the modules folder (dependencies)

var sourcefiles = [

'./**/*.js',

'!./node_modules/**',

'!gulpfile.js'

];

gulp.src( sourcefiles )

.pipe(jshint( '.jshintrc' ))

.pipe( jshint.reporter(stylish) );

});

gulp.task('watch', function(){

// adds a watch that executes the lint task everytime

// a file is modified

gulp.watch( ['.jshintrc', '*.js', 'lib/*.js'], ['lint'] );

});

// define the default task that is invoked

// when "gulp" is executed on the cmd-line

gulp.task('default', [ 'watch' ]);

When the developer enters “gulp lint” in the command line the following report is generated by JSHint that show eight potential errors found in the script “alfa.main.samle.js”:

The gulp task “watch” will initialise a process, which triggers when a developer modifies a file, that matches the “sourcefiles” selector. Using this on-going static code analysis, will ensure detection of defects or issues at an early stage of the development process.

Summary

This article gave a brief introduction on how to write maintainable JavaScript code and introduce the various options and approaches. Even though we could utilize different tools or concepts, it is a fundamental and quite challenging aspect of the process to define a set of guidelines and metrics for an organisation. These are guidelines and metrics all the developers must share. This part is the most challenging. Nevertheless, obliging to these rules is a crucial investment in having a clean and maintainable code-base. It is vital for the success of development organisation as well as for the customers who may have to maintain code on their end. Please share this blog if you found it helpful, and bookmark our Blogs to read more in the series.