Friday, August 24, 2007

Why do they call it Javascript ? It's not Java and it's way powerful for a scripting language!

A couple of days back, I was enjoying Steve Yeggey's keynote on Software Branding at the OSCON 2007. Talking about the negative aspects of branding, he mentioned about Javascript, a name which never helped the growth of the language. Glenn Vanderburg, another noted Ruby convert, says in his NFJS writings:
I still think that naming decision was a bad idea. It caused no end of confusion. Many nonprogrammers never figured out that Java and JavaScript were two different things.

In an earlier post, I had mentioned how the Rhino scripting engine and externalized business rules in Javascript saved us the day in one of our client engagements. That experience had me thinking about the virtues of polyglot programming, usefulness of embeddable scripting engine in Java 6 and the essence of the JVM as the next ubiquitous computing platform. However, it took me some more time and a couple of more blog readings to realize the power and elegance of Javascript as a language. Indeed all the capabilities of Javascript within the browser are add-ons to the simple virtues that the language imbibes.

In gensym.org, David mentions about the following Scheme implementation of a snippet that picks up the maximum salary of a programmer amongst a collection of employees having various roles:


(define (salary-of-highest-paid-programmer records)
  (accumulate
      max 0
        (map salary
          (filter programmer? records))))



He observed that the normal Java implementation will be much more verbose compared to the Scheme one. I tried out a Javascript implementation for the same problem ..


maxProgrammerSalary = function() {
    return {
        maxSalaryFun : function(emps) {
            return reduce(
                Math.max,
                0,
                map(pluck('salary'),
                    filter(
                        callMethod('isProgrammer'),
                        emps)))
        }
    };
}();



The code looks wonderfully similar to the Scheme implementation in structure using the functional paradigms. I really feel bad now that I have chosen to ignore this language so long. Like Glenn Vanderburg, this is my personal story of coming full circle with Javascript.

Of course the above implementation uses a couple of functions, which we have to define today or get it from libraries like prototype. With Javascript 1.6 Array extras and the new features in progress for Javascript 1.8, almost all of them will be part of the core language.

Javascript as a language

Being a prototypal language like Self, Javascript's tryst with OO principles are very much different from the classical strongly typed model of Java or C++. Prototype based inheritance was made hugely popular by frameworks like prototype and enthused many UI folks to the world of practicing OO programming.

A language does not necessarily have to preach OO in order to be beautiful - Javascript supports encapsulation and separation of concerns in its very own way, as has been amply demonstrated by the Module pattern all across YUI. I can have my properties declared at the appropriate level of abstraction without polluting the global namespace. In case of the above function for computing the salary of employees, if we were to fetch the employee collection from some data source and need to define some helpers for the computation, we can have a nicely defined module that encapsulates the whole computation model in a separate namespace:


maxProgrammerSalary = function() {

    // this is not exposed to the global namespace
    var getEmployees = function() {
        // get the employee list
    }

    return {
        maxSalaryFun : function() {
            return reduce(
                Math.max,
                0,
                map(pluck('salary'),
                    filter(
                        callMethod('isProgrammer'),
                        getEmployees())))
        }
    };
}();



A Growing language

One of the definite indications of the growing popularity of a language is the growth rate and increasing rate of adoption. While I do not have any concrete figures on the latter, there have definitely been lots of buzz in the blogosphere about the increasing importance of Javascript as a language. We have started seeing frameworks like jQuery, with its own programming patterns and DSL based approach. jQuery custom selectors, along with chaining gives you the programming power of using FluentInterfaces - here is an example from recently published Jesse Skinner's article ..


$('form#login')
    // hide all the labels inside the form with the 'optional' class
    .find('label.optional').hide().end()

    // add a red border to any password fields in the form
    .find('input:password').css('border', '1px solid red').end()

    // add a submit handler to the form
    .submit(function(){
        return confirm('Are you sure you want to submit?');
    });



This snippet is a succinct one-liner that selects the login form, finds some stuff, repeatedly going back to the form after each find, makes some changes to them and finally adds a submit event handler to the form. All the complexities of query optimization and DOM scripting are taken care of by the jQuery engine. When we see lots of programming idioms being discussed actively amongst the experts, it is the sign of a growing programming language. In my short stint towards loving Javascript, I discovered great idioms for lazy function definition, memoization, currying and other functional programming patterns being discussed vigorously in the community. In an earlier post, I had also discussed about the plethora of developments going on in this space.

Thoughtleaders of the programming language community think that Javascript 2 is one of the contenders for NBL. It has lots of features which will delight you as a programmer. It is succinct, it is functional with full support of closures, it is prototypal and it is dynamic. You can add methods to classes even after instantiation. It's a different paradigm altogether from the noun-land of Java. And it's also the most natural glue to the browser. Learn to love it now or ignore it at your own risk.

4 comments:

Peter Bona said...

Nice post. Can you point me to some books, tutorial where I could get into advanced Javascript? Thanks.

Unknown said...

javascript is great. A lot of people dont like it(mainly for the old bad browsers implementations) but now we've got rhino, which simply rocks.
I'm very happy, some quality libs (prototype, jquery, jmaki) are getting a lot of sucess. As javascript book i'd suggest professional javascript for web developer (wrox), which is very complete and explains a lot of advanced js features.

Unknown said...

Peter Bona, if you already know programming then Douglas Crockford's seminars are an excellent way to get started.

http://www.metafilter.com/61049/Douglas-Crockford-Teaches-JavaScript

http://developer.yahoo.com/yui/theater/

Anonymous said...

Java = cause the syntax is built the same
Script = Cause it's runtime and not compiled