Vanilla JavaScript: pros and cons

The term vanilla JavaScript refers to the use of JavaScript without the aid of any framework, that is, pure and simple JavaScript code. In this post I'd like to discuss the pros and cons of this approach.

Pros

The major benefit of this approach is that you're the sole master of your code. You don't have to wonder how the $.extend() method works of if it may have bugs because you're responsible of every bit of the code you write. And this is great.

Another advantage is that you can increase your coding skills by studying web standards such as the DOM or ECMAScript directly, in the sense that you don't have to deal with a wrapper that hides the inner details of how a specific feature works.

Also, you learn how to deal with browser discrepancies and bugs so you can be more proficient when it comes to debugging. The more bugs you fix, the better code you are able to write. Typically a framework does the bug hunting for you when they release a new version.

In short, you have JavaScript, a web browser and your skills: nothing more, nothing less.

Cons

The major disadvantage of a similar approach is that often we don't have enough time to write our code from scratch. For example, consider the simple and trivial case of changing the paths of several images after a site migration.

In jQuery:


$( "img[src^='http://oldsite.com']" ).each(function() {
  var $img = $( this );
  var src = $img.attr( "src" );
  $img.attr( "src", src.replace( "oldsite", "newsite" ) );
});

In vanilla JavaScript:


var images = document.querySelectorAll( "img[src^='http://oldsite.com']" );
for( var i = 0; i < images.length; ++i ) {
  var img = images[i];
  var src = img.getAttribute( "src" );
  img.setAttribute( "src", src.replace( "oldsite", "newsite" ) );
}

With the use of the DOM Selectors API we can get a result that is pretty similar to the original jQuery code. However, the DOM selectors API are not implemented in IE7. So if our project requirements need the support to IE7, we have to change our code as follows:


var images = document.getElementsByTagName( "img" );
for( var i = 0; i < images.length; ++i ) {
  var img = images[i];
  var src = img.src;
  if( src.indexOf( "http://oldsite.com" ) != -1 ) {
    img.src = src.replace( "oldsite", "newsite" );
  }
}

As you can see, we're also forced to adapt our original and modern code to the lowest common denominator, IE7.

How much time does it take to circumvent all these limitations? Too much time. If we're working on several projects, time is money and we can't simply afford to waste it.

Conclusions

Time is against vanilla JavaScript, though is a very stimulating approach and surely is the best approach from a pure web development's point of view.

In our daily work we don't have enough time, unless we start writing our own JavaScript framework by reusing our existing code. But there's jQuery for that.

Back to top