BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage Articles The Modern JavaScript Developer’s Toolbox

The Modern JavaScript Developer’s Toolbox

Leia em Português

The Web Platform has gone a long way since HTML5 was first made popular and people started looking into JavaScript as a language that could do build complex apps. Many APIs have emerged and there is an abundance of content out there about how the browser can leverage all this.

This specific article series will go a step further and focus on how these powerful technologies can be leveraged in practise, not to building cool demos and prototypes, but how real practitioners use them in the trenches. In this (post)HTML5 series, we'll go beyond buzzwords and get practical insight from experts about what has actually worked for them. We'll also talk about technologies (like AngularJS) that go a step further, and define the future of how the standards and web development will evolve.

This InfoQ article is part of the series “Next Generation HTML5 and JavaScript”. You can subscribe to receive notifications via RSS.

 

JavaScript is a scripting language initially designed to enhance web pages, but is now used in almost every way imaginable. Advances have been made that allow JavaScript to run on the server-side as well as be compiled into native phone application code. Today’s JavaScript developer is part of a rich ecosystem filled with hundreds of IDEs, tools, and frameworks. With so many options and resources, some developers may find it difficult to know where to begin. I’d like to discuss and profile the modern JavaScript developer, beginning with a brief history of JavaScript and then covering the most popular frameworks, tools, and IDEs.

A Quick Jaunt Through History

Let’s take a quick trip back to 1995 when Netscape Navigator and Internet Explorer 1.0 were the browsers of choice. Websites had annoying blinking text and far too many GIFs. A site full of rich content could take a full 2 minutes to load on a dial-up connection. Along the way, a web language was born that allowed these ancient websites to execute client-side code. This was the year that gave birth to JavaScript.

The websites of 20 years ago didn’t use JavaScript much, and certainly not to its full potential. Occasionally there’d be an alert popup to tell you something, scrolling text in a box that delivered news, or a cookie that stored your name and displayed it back to you when you returned months later. There were surely no jobs where JavaScript was the primary language, save those lucky few who had the jobs of actually creating JavaScript. In short, it was a gimmick for websites to fancy up their DOM.

Today, JavaScript can be found virtually everywhere. From AJAX, to Bootstrap, to ReactJS, Angular, the ubiquitous jQuery, and even Node.js on the server side, JavaScript has become one of the most important and popular web languages.

Frameworks

One of the biggest ways JavaScript has changed since its inception is in its use. Gone are the days of awkward document.GetElementById calls and cumbersome XmlHttpRequest objects. Instead, helpful libraries have abstracted much of the root functionality making JavaScript more accessible to developers. This is a big part of why you see JavaScript everywhere.

jQuery

jQuery was created in 2006 by John Resig. It provides a rich set of tools that abstract and simplify cryptic and rigid JavaScript commands and methods. The easiest way to demonstrate this is by example.

AJAX request made with vanilla JavaScript:

function loadXMLDoc() {
    var xmlhttp;

    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 ) {
           if(xmlhttp.status == 200){
               alert("success");
           }
           else if(xmlhttp.status == 400) {
              alert("error 400")
           }
           else {
               alert("something broke")
           }
        }
    }

    xmlhttp.open("GET", "test.html", true);
    xmlhttp.send();
}

source: Stack Overflow

AJAX request made with jQuery:

$.ajax({
    url: "test.html",
    statusCode: {
    	200: function() {
    		alert("success");
    	},
    	400: function() {
    		alert("error 400");
    	}
    },
    error: function() {
    	alert("something broke");
    }
});

jQuery made difficult JavaScript functions easy to use and DOM manipulation a snap. As a result, it was one of the first widely used frameworks for JavaScript, and the idea of abstraction that came with it was the basis upon which other frameworks were modeled.

AngularJS

AngularJS, or “Angular” as it is typically called, hit the scene in 2009. It was created by Google to make it much easier to build single page applications (SPAs). Like jQuery, it aims to abstract the difficult work into highly reusable methods. It provides a model-view-controller (MVC) architecture for JavaScript.

ReactJS

ReactJS, or “React” as it is often called, is new to the game. It was created by Facebook and released for the first time in 2013. Facebook considers React to be a new take on the SPA problems that Angular works to solve. You would be correct to consider Angular and React as competing frameworks. However, what really separates React from Angular is that React is a more efficient, higher performance, quantifiably faster library. The below chart shows the time taken by React, Angular, Knockout (a 3rd library not discussed in this article), and vanilla JavaScript to render a list of 1000 items to the DOM:

source: The Dapper Developer

If performance is important to your application, then React is the way to go.

The JavaScript Development Environment

An important part of efficient development is the use of an IDE. An IDE, or Integrated Development Environment, is an application that offers a suite of tools to a developer. The most important of these tools is typically a rich text editor, which often offers syntax highlighting, autocomplete, and keyboard shortcuts that speed up annoying manual processes.

Sublime Text

Sublime Text is not actually an IDE. It is a lightweight, super-fast programming text editor that offers syntax highlighting and intuitive keyboard shortcuts. It’s cross-platform, which is excellent for developers who want to use a Mac in a PC shop (or vice versa). Virtually everything about Sublime Text can be customized. It also offers multiple plugins that enable IDE-like capabilities such as Git integration and linting. This is a terrific choice for enthusiasts and new JavaScript developers alike. A Sublime Text license costs $70 USD at the time of publishing.

source: Sublime Text

WebStorm

WebStorm was created by the JetBrains team as a smart IDE focused on HTML, CSS, and JavaScript. It costs a nominal fee to license ($49 at the time of publishing) and is widely considered the de-facto standard for seasoned JavaScript professionals, and for good reason. The built-in code-completion and inspection tools are second to none. WebStorm also offers a rich JavaScript debugger and integrated unit testing with popular frameworks such as Karma test runner and JSDriver, and even Mocha for Node.js.

One of the nicest features of WebStorm is the Live Edit functionality. By installing a plug-in into both Chrome and WebStorm, a developer can make source code changes that are instantly reflected in the browser. Developers can also configure Live Edit to highlight the changes that are made in the browser window, making both debugging and coding highly productive.

Overall, WebStorm is the IDE to pick if JavaScript is your full-time job.

source: JetBrains

Brackets

Brackets is an open-source, free IDE built with a focus on visual tools. Brackets offers a live editing feature similar to WebStorm that lets you instantly see the results of code changes in a browser window. It also supports side-by-side editing, which allows you to work on the code and see the results simultaneously without the need for tabbing between applications or pop-up windows. One of the most interesting features of Brackets is called Extract. It analyzes Photoshop (PSD) files in order to retrieve font, color, and measurement information. This feature makes Brackets an excellent choice for JavaScript developers who also do design work.

(Click on the image to enlarge it)

source: Brackets

Atom

Atom is an open-source, free rich text editor created by GitHub. It is very approachable and easy to use; you can install and run it without ever touching a configuration file and it “just works.” The most interesting part of Atom is the ability to customize every aspect of it (it is coined “hackable” by GitHub). Atom is built upon a web core, enabling you to customize the look and feel of it by writing standard HTML, CSS, and JavaScript. Want a different background and text color in Atom? Just change the CSS values. Alternatively, you can download and apply one of many themes created for Atom. This allows Atom the flexibility to become anything that you’d like it to be. Atom is an excellent tool for new JavaScript developers and enthusiast hackers alike.

(Click on the image to enlarge it)

source: Atom

Build Tools and Automation

The modern JavaScript project tends to be fairly complex, with many moving parts. This is not due to inefficiencies in the language or tools; it is a direct result of the rich, vibrant, and complex web applications that are being built today. When working on a large project, there will be many repetitive processes that you must do whenever you want to check-in your code or build out to production. These could be things like bundling, minification, compilation of LESS or SASS CSS files, and even running tests. Doing this work manually is frustrating and inefficient. It’s better to automate the work via a build tool that supports tasks.

Bundling and Minification

Most of the JavaScript and CSS that you write will be shared across a few web pages. As a result, you will likely place them in .js and .css files, and then reference those files on your web page. This will cause the visitor’s browser to make an HTTP request to retrieve each of these files (or at least verify that they haven’t changed) in order to fully render your web app.

HTTP requests are expensive. On top of the payload size, you also pay the costs of network latency, headers, and cookies. Bundling and minification tools are designed to reduce or eliminate these costs entirely.

Bundling

One of the simplest things that a developer can do to improve the performance of their web code is to bundle it. Bundling is the process of stitching multiple JavaScript or CSS files into a single JavaScript or CSS file. This is just like stitching the individual pieces of a panoramic photo together at the seams in order to create a single, contiguous photo. By bundling our JavaScript and CSS files, we eliminate much of the HTTP request overhead.

Minification

Another way that a JavaScript developer can improve performance is by minifying their newly bundled code. Minification reduces JavaScript and CSS to their smallest possible forms, while maintaining identical functionality. For JavaScript this means renaming variables to nonsensical single character tokens, and removing all whitespace and formatting. For CSS, which relies on the names of variables, this typically means only removing formatting and white space. Minification offers drastic network performance improvements because it reduces the number of bytes sent in each HTTP response.

Our un-minified segment of AJAX JavaScript code from earlier:

$.ajax({
    url: "test.html",
    statusCode: {
    	200: function() {
    		alert("success");
    	},
    	400: function() {
    		alert("error 400");
    	}
    },
    error: function() {
    	alert("something broke");
    }
});

The same code minified:

$.ajax({url:"test.html",statusCode:{200:function() {alert("success");},
400:function(){alert("error 400");}},error:function(){alert("something broke");}});

Note that I broke the minified output into 2 lines to be able to display it to you in this article. The actual output of minification is typically a single line.

When To Bundle And Minify

Usually, the bundle and minify steps are only done in production. This is so that you can debug your code locally or in a development environment as-is, complete with formatting and line numbers. Debugging the minified code above would be difficult; all of the code would be on line 1. Minification makes the code completely unreadable, which would be useless and frustrating for you to attempt to debug.

Source Map Files

Sometimes a bug occurs in your code that is only reproducible in production. This poses a problem when you need to debug the issue but all of your code is minified. Fortunately, JavaScript supports source code map files that “map” between minified code and the original code. The map file for your code is generated during minification via build tools such as those described below. Your favorite JavaScript debugger then uses the map file to provide you with legible code to debug. You should deploy your production code with map files whenever possible, so that you can debug the code if anything goes wrong.

Linting

A linting tool analyzes your code for common mistakes and deviations from defined formatting rules. The kinds of errors reported are things like using tabs instead of spaces, missing semicolons at the ends of lines, or curly braces without an if, for, or while declaration. Most IDEs come with linting tools; others offer the ability to install a linting plugin.

The most popular JavaScript linters are JSHint and JSLint. JSHint is developed by the community and is a fork of JSLint, the original linting framework built by Doug Crockford. These vary a little in the code format standards they enforce. My advice is to try both and use whichever one best fits your style of coding.

Automating Things: Grunt

Despite the name, Grunt is far from primitive. It is a robust command-line build tool that executes user-defined tasks. By specifying a simple configuration file, you can configure Grunt to compile LESS or SASS, build and minify all of the JavaScript and CSS files in specific folders, or even run a linting tool or test framework. You can also configure Grunt to execute as part of a Git hook - minifying and bundling your code whenever you check something into the source control repository.

Grunt supports named targets so that you can specify different commands for different environments; you could define “dev” and “prod” as targets for example. This is useful for scenarios such as bundling and minifying your code in production but leaving it alone in the development environment so that it is easy to debug.

A useful feature of Grunt is “grunt watch” which monitors a directory or set of files for changes. This can be integrated directly with IDEs such as WebStorm and Sublime Text. By using watch, you can trigger events based on file changes. A practical application of this approach is LESS or SASS compilation. By configuring grunt watch to monitor your LESS or SASS files, you can compile them immediately whenever a file is changed, making the output of the compilation immediately available to your development environment. You could also use grunt watch to automatically run a linting tool against any file that you edit. Real-time execution of tasks via grunt watch is a terrific way to boost your productivity.

Automating Things: Gulp

Grunt and Gulp are direct competitors that strive to solve the same build automation problems. The major difference between Grunt and Gulp is that Grunt focuses on configuration, while Gulp focuses on code. While you’d configure build tasks via declarative JSON in your Grunt file, you’d write JavaScript functions in your Gulp file to accomplish the same.

This is a Grunt file configured to compile SASS files to CSS whenever a file changes:

grunt.initConfig({
  sass: {
    dist: {
      files: [{
        cwd: "app/styles",
        src: "**/*.scss",
        dest: "../.tmp/styles",
        expand: true,
        ext: ".css"
      }]
    }
  },
  autoprefixer: {
    options: ["last 1 version"],
    dist: {
      files: [{
        expand: true,
        cwd: ".tmp/styles",
        src: "{,*/}*.css",
        dest: "dist/styles"
      }]
    }
  },
  watch: {
    styles: {
      files: ["app/styles/{,*/}*.scss"],
      tasks: ["sass:dist", "autoprefixer:dist"]
    }
  }
});
grunt.registerTask("default", ["styles", "watch"]);

source: Grunt vs Gulp - Beyond the Numbers

This is a Gulp file configured to compile SASS files to CSS whenever a file changes:

gulp.task("sass", function () {
  gulp.src("app/styles/**/*.scss")
    .pipe(sass())
    .pipe(autoprefixer("last 1 version"))
    .pipe(gulp.dest("dist/styles"));
});
gulp.task("default", function() {
  gulp.run("sass");
  gulp.watch("app/styles/**/*.scss", function() {
    gulp.run("sass");
  });
});

source: Grunt vs Gulp - Beyond the Numbers

I recommend that you use whichever one you prefer. Both of these tools are typically installed via npm, the Node.js Package Manager.

In Summary

JavaScript has evolved significantly since its birth amidst the early days of the Internet. Today it is a prominent and important feature of interactive web applications.

The developer has also evolved significantly since 1995. Today’s modern JavaScript developer employs rich and robust frameworks, tools, and IDEs to work efficiently and productively.

Building your first modern JavaScript application is easier than you may think! Just choose an IDE (I recommend Atom for beginners), and then install npm and grunt. If you get stuck along the way, Stack Overflow is an excellent resource. With just a little time spent learning the basics, you’ll be well on your way to releasing your first modern JavaScript app.

Resources

Frameworks:

IDEs:

Linting:

Build Tools and Automation

Helpful Resources

About the Author

David Haney is the core team Engineering Manager at Stack Exchange, creators of question and answer websites such as StackOverflow and ServerFault. He spends his days supporting developers by solving problems and improving processes. He was previously a lead developer on Fanatics' e-commerce platform which hosts over 10,000 websites including the NFLShop - The Official Online Shop of the NFL and NBAStore.com - The Official NBA Store. David is the creator of Dache, an open source distributed caching framework. His spare time is spent drinking beer and participating in community user groups and programming events - often simultaneously.

 

The Web Platform has gone a long way since HTML5 was first made popular and people started looking into JavaScript as a language that could do build complex apps. Many APIs have emerged and there is an abundance of content out there about how the browser can leverage all this.

This specific article series will go a step further and focus on how these powerful technologies can be leveraged in practise, not to building cool demos and prototypes, but how real practitioners use them in the trenches. In this (post)HTML5 series, we'll go beyond buzzwords and get practical insight from experts about what has actually worked for them. We'll also talk about technologies (like AngularJS) that go a step further, and define the future of how the standards and web development will evolve.

This InfoQ article is part of the series “Next Generation HTML5 and JavaScript”. You can subscribe to receive notifications via RSS.

Rate this Article

Adoption
Style

BT