Why JavaScript is the future of software

I have been using JavaScript for a long time but the full extent of its potential didn’t really occur to me until recently and now I am convinced that JavaScript, of all languages, is the one which will carry us into the next epoch of software development.

Not so long ago, like many other software developers, the web projects which I worked on were mostly written in PHP (often using a PHP framework like Zend, CodeIgniter or a custom one) – JavaScript was just an add-on, optional feature meant to ‘enrich’ the user experience. Today it’s been over a year since I’ve been coding almost exclusively in JavaScript (both for my personal projects and at work) and I am hooked. I have a pretty broad software background (C/C++, Java, Python, ActionScript3, C#, AVR assembly and maybe a few others) so I hope that the following analysis of JavaScript is fair and accurate.

There are several aspects of JavaScript which make it a really great language to work with – One of the most important aspects for me is its conciseness and its versatility – Of all the languages that I’ve used, JavaScript is the best when it comes to turning thoughts into code – Everything is either an Object, a Function (which is also an Object, technically-speaking) or a primitive and once you understand the relationship between these three basic types (which can take a little bit of time), JavaScript becomes really easy and fun to write. Another cool aspect is that JavaScript is ideal for dealing with asynchronous logic; JavaScript allows you to define functions wherever you want – This lets you execute code asynchronously without losing the scope of the current function (this can be done using an inline callback) – This is a HUGE advantage and can save you hours (dealing with multiple parallel processes is ridiculously simple in Node.js – Especially when compared to C++).

The other, and possibly the most awesome thing about JavaScript today (which I alluded to in the previous paragraph) is the fact that you can run it on either the client side (in just about any browser) or on the server side using engines such as Node.js – And I think that this feature is what makes JavaScript the language of the future – No other language has managed to be standardized so formally by so many different companies, browsers and platforms as JavaScript. As an example of this, for the past couple of months, I’ve been doing some contract work building a framework for a major set top box company (who make those devices people plug into their TVs) and guess what the framework is written in!
It’s not actually Node.js (it’s using a custom engine based on WebKit) but yes, JavaScript! A couple of years ago, JavaScript was only for the browser on a PC, then it moved to mobile phones, then it got traction as a server-side language and now it’s moving to embedded systems!

Several decades ago, Mark Weiser ( https://en.wikipedia.org/wiki/Mark_Weiser ) who is often referred to as the father of ubiquitous computing theorized that computers would become the fabric of our everyday life – And today this sounds more like reality. We’ve had the internet, iPods, smart phones, tablet computers, internet TV, and now we are about to get smart watches and Google Glasses! Let’s face it, all of these devices will run on completely different firmware/operating systems and will be produced by different companies.
Here is the selling point of this article: JavaScript is currently the only language which is in a position to bring all of these devices together to allow them to interoperate.

Advertisements

JavaScript Inheritance Done Right

One of the worst (and possibly also one of the best) things about JavaScript is that it offers you many ways to do anything. Some tricks are simple and neat while others can be complex and confusing.

If you have done some research, you will likely have come across many ways of implementing inheritance in JavaScript. I have personally used a lot of variations over time in various projects but it’s not until recently that I have settled on a particular technique.

I have chosen this particular technique because I feel that it most closely resembles how most OO programming languages implement inheritance. To get it to work properly, you should use the prototype-based method of class definition. Here is an example of the technique in action:

function BaseClass(name) {
    this.name = name;
}

BaseClass.prototype.foo = function (arg) {
    return ‘This is the foo method with argument: ‘ + arg;
};

function SubClass(name) {
    // Call the base class’ constructor.
    BaseClass.call(this, name);
}

// SubClass’ prototype is based on BaseClass’ prototype
SubClass.prototype = Object.create(BaseClass.prototype);

SubClass.prototype.sub = function () {
    return ‘This is the sub method.’
}

SubClass.prototype.foo = function (arg) {
    // Call the base class foo method on the current instance
    return BaseClass.prototype.foo.call(this, arg) + ‘ SUB’;
}

Ok, so what stands out the most in this code is this line:

SubClass.prototype = Object.create(BaseClass.prototype);

When you define a function in JavaScript, initially, its prototype will be an empty object. What we’re doing here is setting the SubClass’ prototype to be a new instance which shares the BaseClass’ prototype. Effectively, this allows us to freely modify the SubClass’ extended prototype without messing with the BaseClass’ prototype – The advantage of this technique over simply cloning the prototype is that changes in the BaseClass prototype will still be reflected in the SubClass (but not the other way around). The best way to think about the Object.create() method is that it instantiates a class based on a prototype without actually going through its constructor. The Object.create() function may not be supported by older browsers, but thankfully there is a simple polyfill which you can get from this page:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

The second weird thing about the code above is this line:

BaseClass.call(this, name);

Now if you don’t know what call or apply do, you should check this:
http://stackoverflow.com/questions/1986896/what-is-the-difference-between-call-and-apply

OO languages usually offer a way to explicitly call a super class’ constructor or method, JavaScript is no exception. With JavaScript, you just call the constructor/method using either call() or apply() and pass a reference to the current instance as the first argument. This is a neat feature of JavaScript which allows you to effectively borrow methods from any other class to use on the current instance.

If you’re used to languages like Java, C# and Python, you might find the class definitions above unusual – In these languages you have an explicit ‘class’ keyword and you define the methods INSIDE the class block. If however, you have written C++ before, this might seem a little less confusing because C++ allows you to define methods of a class outside of the class definition block. While JavaScript does let you define methods inside the constructor’s function block, this makes inheritance more difficult to achieve and I would strongly recommend that you follow the technique above (I swear you won’t regret it).

JavaScript Prototype Instantiation

In JavaScript, functions can be used in two ways; they can be simply called or they can be instantiated. When you call a function, it will simply run the code inside it and possibly return some value – When you instantiate a function, the JavaScript engine will first create a new object (a clone of that function’s prototype) and then will call that function using the newly created object as the context for the ‘this’ keyword.

Function prototypes are essentially empty objects by default – You can add properties to the prototype object using the Function.prototype property. Here is an example of how to add properties to a function’s prototype:

var Fun = function() {
    this.prop = 'This is a property of a Fun instance';
}

// Adding a 'foo' property to the 'Fun' function’s prototype
Fun.prototype.foo = function() {
    return 'foo';
}

var fun = new Fun(); // fun is an object with a 'foo' property which is a function

When ‘new Fun()’ is called, the JavaScript engine first creates a clone of the function’s prototype object which essentially looks like this: {foo: function() {return ‘foo’;}}; then it executes the Fun function using the cloned object as the ‘this’ reference – Because of that, properties added to ‘this’ within the function body can overwrite those defined in the prototype.

Writing Selfish JavaScript – Dealing with the this keyword

In class-based programming languages, the ‘this’ keyword is used to refer to the class instance within which the current method is defined. While JavaScript does provide an essential ‘this’ keyword which aims to serve a similar purpose, its functionality differs a bit and this can cause a lot of confusion.

A key difference between JavaScript and most other OO languages is that, in JavaScript there are no such things as classes and methods. All you have in JavaScript are objects and functions – While JavaScript does let you create objects which hold member functions (which look and behave very much like methods); they are not really methods. The main difference between a function and a method is that a method is bound to the instance of the class in which it is defined – A function is stand-alone and is bound to nothing…

If JavaScript does not support classes or methods, what does the ‘this’ keyword point to? The ‘this’ keyword in JavaScript actually points to the object within which the function is EXECUTED (as opposed to the object within which the function is DEFINED). This might seem like a small difference but the implications are huge. Because JavaScript lets you pass functions around as callbacks and assign them to other object’s properties, the object which contains a given function may change throughout your program execution and that is why the ‘this’ reference may also change depending on when your function is executed.

For example, take this code:

    var TypeOne = function () {
        this.foo = 'TypeOne foo';
        this.doFoo = function () {
            return this.foo;
        }
    }

    var TypeTwo = function () {
        this.foo = 'TypeTwo foo';
    }

    var t1 = new TypeOne();
    var t2 = new TypeTwo();
    t2.doFoo = t1.doFoo; // Copy the doFoo function from TypeOne object into TypeTwo object

    console.log(t1.doFoo()); // Outputs 'TypeOne foo'
    console.log(t2.doFoo());    // Outputs 'TypeTwo foo'

As you can see, the ‘this’ reference within the doFoo() function changes depending on the context within which the function is executed. In some cases, this feature may actually be desirable, but in many cases, this can be very problematic. Passing functions around in JavaScript is EXTREMELY common; in fact, that’s the entire premise of asynchronous programming – If we want to have some class-like behaviors in our code, there needs to be some way to bind a function to the object within which it is defined! Newer versions of JavaScript offer a useful ‘bind()’ function which lets you do just that, but unfortunately, this is a new feature and most browsers do not currently support it.

Ok, so what’s the solution then? Well, actually there are a number of solutions but I would like to discuss just one of them which I find to work consistently well, it’s easier to explain if I show some code first:

    var TypeOne = function () {
        var self = this;
        self.foo = 'TypeOne foo';
        self.doFoo = function () {
            return self.foo;
        }
    }

    var TypeTwo = function () {
        var self = this;
        self.foo = 'TypeTwo foo';
    }

    var t1 = new TypeOne();
    var t2 = new TypeTwo();
    t2.doFoo = t1.doFoo; // Copy the doFoo function from TypeOne object into TypeTwo object

    console.log(t1.doFoo()); // Outputs 'TypeOne foo'
    console.log(t2.doFoo());  // Outputs 'TypeOne foo'

Ok, so that works, but why? This trick is sometimes called ‘fixing the this’ because we are effectively capturing the ‘this’ reference at a convenient time and using it later when the actual ‘this’ keyword may have changed. This relates back to the fact that JavaScript determines the reference of ‘this’ upon function execution and not upon function definition – Here the variable ‘self’ is being assigned to ‘this’ when the constructor function is executed; at that point, ‘this’ is pointing to the newly created object (whose reference we will need to use within its member functions). What all this means is that when the doFoo() function is passed on to a TypeTwo object, it will still be using the ‘self’ reference from TypeOne. Using ‘self’ instead of ‘this’ in this way gives you certainty about the context within which the member functions will be executed.