ECMAScript: The history of JavaScript

JavaScript is a very interesting language that has caught my eye in the last year. Previously I blogged about the power of the Module Pattern in JavaScript; why it’s powerful and how to make sure your site complies to this great pattern. The language has come a long way and is growing up fast to be the defacto language of choice for all front-end UI/behavioral functionality. Flash, the old heavy dog, is on its way out. JavaScript, part of the HTML5 stack, is looking the most promising.

This post isn’t about how great JavaScript is, it’s about its history. Before one delves into anything one should always understand the basics. So let’s begin with some basics and then its history. The history is rather interesting.

What is JavaScript anyway?

JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions.

For the business guy

  • JavaScript is client-side language. Meaning anyone with a browser can view it in its entirely. Nothing is hidden. This is how we have access to any site’s code. Right click on any webpage and select “View Source” – Bingo!
  • JavaScript is downloaded via your browser and then executed within the browser. This is where performance bottlenecks are experience and browser compatibility issues.
  • JavaScript’s real name is actually ECMAScript.

For the tech guy

  • JavaScript is a “prototype-based scripting language” meaning it is object-oriented where classes are not present, and inheritance is performed via a process of cloning existing objects that serve as prototypes.
  • JavaScript is “dynamic”; meaning that it executes at runtime.
  • JavaScript is “weakly typed”; meaning you can cast memory to any type and
  • JavaScript has “first-class functions”t meaning it supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures.

History of JavaScript

There are many stories online but I think this one below (source) explains it nicely.

Here is something else you should know about Javascript that seems like it was almost designed to be confusing as possible:

  • There is a programming language called Javascript.
  • There is a programming language called Java.
  • There is an interpreter (‘thing that makes it go’) for the programming language Javascript built into most web browsers
  • There is an interpreter for the programming language Java that is sort of built in to most web browsers, or was.
  • THESE TWO PROGRAMMING LANGUAGES HAVE ALMOST NOTHING TO DO WITH EACH OTHER

Back in the olden days, there was a company called Sun that had invented a programming language they decided to call Java. It was very trendy and exciting. There was a company called Netscape that made the trendiest and excitingest web browser. Sun wanted Netscape to include the magical crap that would make Java work with their browser, because everyone was gonna get Netscape, so everyone would also automatically have the stuff that makes Java programs work. On the other hand, Netscape was saying, “but lets also make our own tiny programming language that runs right in the browser so instead of having to make up new html tags like ‘blink’, web authors can make annoying shit we haven’t even thought of yet!” So they said, “Sun, we’ll ship your ‘Java’, but we want to be allowed to call our other programming language, which has absolutely no relationship to yours and is intended to do completely different things, JavaSCRIPT.” And Sun said, “OK, swell. go nuts. That won’t matter to us. ONCE JAVA TAKES OVER THE WORLD!”

So Netscape said to a guy named Brendan, who worked at Netscape, “Please make us a programming language. Also, you have to call it Javascript. Also, if you can make some of it kind-of sort-of look a bit like Java, that would be even better. Also, you have only 10 days to do this so get cracking!”

Fortunately, it turned out that Brendan was a cool genius and he secretly designed a cool programming language and dressed it up in some vaguely Java-looking disguises, kind of like how children will sometimes wear a huge cloak and stand on top of one another in order to get into R-rated films.

But Brendan’s disguise worked too well! People were like “wtf is with this crap version of Java? IT SUCKS!” Also, even a cool genius like Brendan has some some limits, so he did make a few mistakes when he was making his programming language in only 10 days. Also, because Netscape had basically thrown down the gauntlet and said, “You think the blink tag is annoying? Marquee makes you want to rip your eyeballs out? YOU HAVEN’T SEEN NOTHING!” people did manage to find insanely annoying things to do with Javascript. All the cool people installed special software on their web browser JUST TO MAKE JAVASCRIPT NOT WORK. So it took many years before people started to figure out that Brendan’s language was wrapped in an elaborate disguise and that it was actually cool.

Weirdly, some of the main people who did this were people at Microsoft, who had tried to confuse this whole mess out of existence by coming out with programming languages named stuff like J++ and JScript. Netscape, at the time, was threatening to rip Microsoft apart, like a crab rips up a cuttlefish with his claws. So Microsoft, adopting the strategy of the cuttlefish, made a million confusing “J” programming languages, hoping to escape intact. A prophet by the name of Douglas started saying, “guess what nerds, it turns out Javascript is actually sort of awesome.” He managed to attract a fair number of acolytes, who fiddled with Brendan’s invention and realized that it was rather elegant and could certainly be made to do all sorts of useful, non-annoying things on webpages, if only people would stop blocking it.

And so the era now known as Web 2.0 began. There are a lot of things people associate with Web 2.0, but for people who make the internet, one of the biggest things was seeing sites like Flickr or Oddpost do cool stuff with Javascript and other technologies that had been previously considered lame.

And then, in a sort of poetic irony that makes this story almost seem like it was pre-scripted to Teach us a Lesson, JAVASCRIPT succeeded in doing what JAVA had intended to do. Microsoft, Java, Sun, Netscape, all were brought low by their hubris. But humble Javascript, the throwaway, ‘you get 10 days to make this’, blink-tag-replacing runt of a language was able to sneak onto every computer in the world thanks to its clever disguise. Servers are written in Javascript. Databases are built to talk Javascript. The people who build browsers and operating systems move heaven and earth to make Javascript just a tiny bit faster. Java’s still out there, of course. In various forms. It probably makes sure your account is updated when you pay your water bill. It’s making the underpinnings of your android phone work. It’s figured out a way to play host to a zillion new trendier programming languages. But Javascript won the original prize.

Anyway, I’m just pointing this out because I remember the time when I didn’t know the difference between Java and Javascript and I’d find a tutorial for one or an article about the other and I was like “wtf, how do these go together.” The answer is, “they don’t. Marketing people just tried to name them as confusingly as possible.”

JavaScript today is..

  • Used in every website you visit online.. like 99.9999% of them.
  • At the core of famous server-side Node.js, an evented I/O framework.
  • If you heard of beautiful frameworks like jQuery, YUI, and more recently SproutCore and Cappuccino (Objective-J).. all JavaScript.
  • HTML5? replacement for Flash and other slick interface functionality, yap you guessed it.. JavaScript.
  • It is the most important language today!

What next

Plenty more informative & juicy articles on this front are being lined up. Not to mention I am starting a fun project with few smart software engineers in the valley which aims to give back to the community around this most important language today, JavaScript. Stay tuned to find out more on what’s next!

~ Ernest

JavaScript: made better using the Module Pattern

I’ve just finished reading JavaScript Patterns by Stoyan Stefanov and boy has it opened up my mind and inspired me to write better, faster, cleaner and more modular JavaScript code using the Module Pattern.

Stoyan’s book covers many patterns and anti-patterns (the common old approach to JavaScript coding).

Stoyan provides detailed explanations why and where to use each pattern inc. module pattern. Since there is so much content in this book I decided to write about what I believe will add immediate value to any developer working with JavaScript, how to make JavaScript better using the module pattern.

No hacks around poor JavaScript

JavaScript is unlike back-end server-side code where if the code becomes a bottleneck you just throw more boxes (hardware) at it to speed thinks up. JavaScript downloads & runs within the user’s browser. So if you got lazy or just didn’t know better to follow Convention over Configuration (CoC) or the rapid development principle of Don’t Repeat Yourself (DRY) and you hacked something together.. the user will get poor experience and even limited to a single browser. This is where JavaScript Patterns play an important role and understanding them is the 1st step in becoming a JS Ninja.

JavaScript – what you need to know

Let’s shake some old grounds and cover the what you need to know about JavaScript in 2011.

  • There are no classes in JavaScript. You create a blank object when you need one and then start adding members to it.
  • Sometimes when people say “Singleton” in a JavaScript context, they mean the Module Pattern – covered below and discussed in detail in Stefanov’s Chapter 5. Every time you create an object using the object literal, you’re actually creating a Singleton. And there’s no special syntax involved.
  • When you think about objects in JavaScript, simply think about hash tables of key – value pairs. Similar to what are called associative arrays in other languages.
  • Use literal notation patterns instead of object definitions. Literal is more concise, expressive and less error-prone. See Appendix 1.1 at the end of this post for examples.

Module Pattern – organize your code

Let’s start with what’s most common out there on the internet. You may have seen (or even do) this.

Code sample – anti pattern

Declaring:

var array_string = "[object Array]";
var ops = Object.prototype.toString;
var MAX_NUM = 123;

function inArray (haystack, needle) {
    for (var i = 0, max = haystack.length; i < max; i += 1) {
        if (haystack[i] === needle)
            return i;
    }
    isEnabled = false;
    return −1;
}

function isArray (a) {
    return ops.call(a) === array_string;
};

var pageTitle = "New title";

Calling:

isArray(arr_user);

The problems here are:

  • All these are global (variable and functions) are shared among all the code in your application living in the global namespace. High chance of naming collisions between your and other developer’s code (think maintenance).
  • isEnabled above has no var declaration so automatically becomes chained to the global namespace outside the function.
  • When something in your code is chained to the top of the prototype it takes longer time to be found then if it’s within a module. I will discuss the JavaScript Prototype in another post and show examples with performance differences.
  • Some best practices are broken – see below what these best practices should be.

Module Pattern – the solution, organize your code

There are many great patterns described in JavaScript Patterns by Stoyan Stefanov but my preference today is to use the Module Pattern. The Module Pattern is widely used because it provides structure and helps organize your code into self-contained de-coupled pieces of code. If you look at the source of jQuery you will find a similar pattern being used.

The Module Pattern is a combination of several patterns described in Stoyan’s book.
They include:

  • Namespaces (Stefanov’s pg.87)
  • Immediate functions (Stefanov’s pg.73)
  • Private and privileged members (Stefanov’s pg.92) and
  • Declaring dependencies (Stefanov’s pg.90)

And here’s how the same sample of code above would look when the Module Pattern was followed.

Module Pattern code sample – the pattern

Declaring:

var MYCOMPANY = MYCOMPANY || {};

// note the use of namespacing - similar to jQuery.
MYCOMPANY.Page = (function () {
    'use strict';

    // [ private properties ]
    // note the chaining of var declarations vs a var on each line
    var pageTitle    = "blank",
        isEnabled    = false,
        array_string = "[object Array]",
        ops          = Object.prototype.toString,
        MAX_NUM      = 123; // constants always are in capital case
    // end var

    // [ private methods ]
    // note the use of literal patterns vs constructor functions
    function inArray(haystack, needle) {
        var i   = 0,
            max = 0;
        for (max = haystack.length; i < max; i += 1) {
            if (haystack[i] === needle) {
                return i;
            }
        }
        return -1;
    }
    function isArray(a) {
        return ops.call(a) === array_string; // end var
    }

    // [ public methods ]
    return {
        init: function (title, enabled) {
            pageTitle = title;
            isEnabled = enabled;
        },
        isArray: isArray,
        indexOf: inArray
    };
}());

Calling:

MYCOMPANY.Page.init('Page title', true);
MYCOMPANY.Page.isArray(arr_user);

Code is now modularized and less prone to collisions.

JSLint: The JavaScript Code Quality Tool

Once you have written your new modularized code it’s a best practice to run it past JSLint. JSLint is a free JavaScript program that looks for problems & violations of some of the patterns in your JavaScript code. It is a code quality tool. Check it out here: http://www.jslint.com/

JavaScript best practices

  • Curly brackets should always be used even if there is 1 expression. Code is then more readable and maintainable.
  • Use 4 space indentation – also JSLint default. This way no matter what editor engineers use it is always displayed in the same manner.
  • Like curly brackets, always use semicolons, even when they are implied by the JavaScript parser. Why slow down the compiler to clean up the mess during runtime.
  • Naming convention for constructors is typically UpperCamelCase, functions lowerCamelCase, variables lowercase_separated_by_underscore and constants UPPER_CASE.
  • Use whitespace as much as possible by separating all operators and their operands with spaces.
  • Use Google’s Closure Compiler to minify your code before production AFTER you have passed it via JSLint (above).

Appendix

1.1 Constructors and their corresponding and preferred literal patterns.

Built-in constructors (avoid) Literals and primitives (prefer)
var o = new Object(); var o = {};
var a = new Array(); var a = [];
var re = new RegExp( “[a-z]”,”g”); var re = /[a-z]/g;
var s = new String(); var s = “”;
var n = new Number(); var n = 0;
var b = new Boolean(); var b = false;
throw new Error(“uh-oh”); throw { name: “Error”, message: “uh-oh” };… or throw Error(“uh-oh”);

And that is it for now. Have I missed something or gotten something wrong above? If so please let me know and I will correct it. How is your JavaScript looking? Need help to get it fixed? Post below or contact me.

~ Ernest