Home > Programming > Why JavaScript is AWESOME

Why JavaScript is AWESOME

JavaScript is an awesome language. Now, a few years ago, you’d be marked out as a weirdo for saying something like that. I think there’d probably be some kind of witch-burning ceremony or something, because JavaScript was this stupid language which had stupid syntax and stupid scope and was used to do stupid things by stupid people and just led to awful spaghetti code and killed kittens.

These days people are more understanding, and more and more are coming out of the JavaScript closet. It’s starting to become cool. And I don’t mean cool as in “look at this cool bouncing text” (only works in Internet Explorer 4+ and Netscape 3+); I mean cool as in “hey, check out that cool guy over there writing JavaScript, look how cool he is!”. These days John Resig is a ninja and Douglas Crockford is Chuck Norris.

Douglas Crockford with guns

If Crockford builds JSON without quotes around the labels, it's still valid JSON. - TheReincarnator

Seriously though, what’s so great about JavaScript?

Functions or lambdas

A rose by any other name would smell as sweet, and JavaScript’s functions are sweet like chocolate. I tried to explain to a friend recently just what was so great about JavaScript. What I decided was that it was the functions. JavaScript’s functions can act like lambdas, functions and methods. They can be used to create modules, namespaces, classes and objects. A language like Ruby is a toolbox with some really neat little tools that do their job really nicely. JavaScript is a leather sheath with a really really sharp knife inside. That knife can cut anything, and with it you can do anything. You can kill a bear. You can catch fish. You can whittle a piece of wood into a pony. It’s even a toothpick.

So what makes JavaScript functions so great? It’s two things I think: first-class citizenship and closures.

Functions as first-class citizens

Functions are people too you know? Well, no they’re not actually, but they are objects. They can be passed around like any other object. They can be assigned to variables, passed as arguments, and even returned. And because you can write function literals in JavaScript, you can return a function without even naming it:

function outer() {
    return function () {
        alert("I'm in ur function, accessin' ur local variablez");
    };
}

This kind of thing is really powerful. I’m not going to try to give any clever examples because it’s the kind of thing you only truly get once you’ve done it yourself and suddenly the whole universe opens up in your mind.

Closures

A closure is a funny thing to get your head around. If you’re used to a static language, then it just won’t make sense. Really it’s another one of those things that you have to do until you transcend, but I’m going to have a go explaining it.

Closures are intimately related to first-class functions. One of the things you can do with a function in JavaScript is define it within another function. You can nest functions as deep as you like. Here’s an example of a nested function:

function outer() {
    var name = 'Bob';
    function inner() {
        alert(name);
    }
    inner();
}

So, in this example, when outer is called, it defines name and inner as a local variable and function, respectively (i.e. they are not visible outside of outer). Then inner is called, which alerts name (‘Bob’). That’s not very exciting though – all it shows is that a function can access variables defined in an enclosing scope. But look what happens here:

function outer() {
    var name = 'Dave';
    function inner() {
        alert(name);
    }
    return inner;
}
var something = outer();
something();

Now outer is called, and it defines name and inner like in the previous example. This time, however, inner is returned (alternatively, I could’ve just returned it as a function literal like earlier). When outer is called, its return value is assigned to something. something is now the same function as inner. But what happens when we call something? outer has returned, so when something tries to access it it’ll probably segfault or something. Well, no, it won’t. That’s where the magic happens. When inner was returned, it somehow magically “closed over” its containing scope, essentially keeping it all available even after outer returned. You can do this with arguments as well:

function outer(arg) {
    return function () {
        alert(arg);
    }
}
outer(5)();

This time the returned function has access to the argument of the outer function. That last crazy line there with all the parentheses isn’t Lisp, it’s JavaScript, believe it or not (Lisp parentheses are nested, in case you ever need to tell the difference). outer is getting called with an argument of 5, and then the return value of that call is called itself.

These two things, first-class functions and closures, are what make JavaScript functions so powerful and flexible. Again, this power needs to be felt to be believed, and the only way to feel it is to write it.

Douglas Crockford

Another thing that’s great about JavaScript is Douglas Crockford. He not only wrote the best book on JavaScript – he’s also given the best talks on the language.

Dynamic typing

I’m a big fan of dynamic typing. It adds so much flexibility, agility and speed to programming. It also makes programming much more fun. I’ve written a few posts on the subject so no need to go into more detail here.

Conceptual purity

If I went back ten years and told anyone (myself included) that one of the great things about JavaScript was its conceptual purity, I’d be laughed out of my time machine. But it’s true, there’s something really pure about the language. What can be achieved with such simple language constructs is amazing. There are just objects and arrays (and arrays are just specialised objects). There are literals for objects and arrays. There are functions, and loops. And that’s pretty much it. No classes, no modules, no iterators, no generators, no templates or generics, no macros. None of these things because they just aren’t necessary when functions are allowed to be free as nature intended. You’d think that it would feel limiting not having these features, but it’s actually liberating. It feels clean, and pure. But powerful. Like a polar bear.

Why JavaScript isn’t awesome

There are a few small things that I don’t like about JavaScript (and are generally considered a Bad ThingTM).

Implied globals

If you don’t declare a variable as local with var, you’re making it global. I don’t need to go into why global variables are a bad thing, because everyone else has.

Semicolon insertion

There was a programme on TV once and they showed all these x-rays with weird things in like toy cars and bottles and stuff, and … oh yeah, semicolon insertion. That’s where the JavaScript interpreter makes it easier for non-programmers to write JavaScript that works and makes it harder for programmers to write JavaScript that’s correct. Silly. Here’s what happens:

return {
    javascript : "fantastic"
}; //This will return an object with a single property

//the interpreter sees this as an empty return statement so inserts a semicolon:
return //this line is interpreted as "return;" - with a semicolon
{
    javascript : "fantastic"
}; //this is just an empty block now.

But I love it really

It’s easy to mitigate those two things with decent coding practices. Basically, always use var, always use semicolons where necessary, and always put the opening brace at the end of the previous line, not at the beginning of the next. Finally, put anything you write through JSLint. It’s like a compiler, without the necessity.

Further reading

JavaScript: The Good Parts: This is Douglas Crockford’s book on JavaScript, and it’s brilliant. It’s only 176 pages, but manages to pack a lot into those pages. By the end you’ll know how to write a recursive descent parser for parsing JSON in JavaScript (some really beautiful code).

Move over Java, I have fallen in love with JavaScript: Miško Hevery usually writes great things about testing – here he talks about JavaScript, from the perspective of a Java programmer.

Best resources to learn JavaScript: This is a useful list of resources for learning JavaScript (as suggested by its title).

Structure and Interpretation of Computer Programs: If you still don’t understand what all the fuss is with functional programming, read this book. I’m only half-way through, but it’s already taught me more about programming than any other book. It’s also probably the reason I love JavaScript so much, because deep down, JavaScript is just Scheme in C’s clothing.

Categories: Programming Tags: ,
  1. 2fuf
    September 4th, 2010 at 13:54 | #1

    When you write:

    var something = outer();
    something();
    

    It reminds me of Actionscript 3 (also an ECMA-262 languague) where you can do something similar. Only in AS it would be:

    var something = outer;
    something();
    

    So you would assign the function reference to variable something, and then call it by adding the parentheses.

  2. September 4th, 2010 at 14:08 | #2

    ActionScript has the same syntax as JavaScript (they’re essentially the same language). You can do your example in JavaScript – the difference is that in my example I wasn’t assigning outer to something, I was assigning the return value of outer to something – the return value being another function.

  3. greggT
    September 4th, 2010 at 14:51 | #3

    i don’t see the semicolon being inserted. could you, say, draw it in red or bold perhaps?

  4. September 4th, 2010 at 20:57 | #4

    There you go, does that help? I’m only showing the code that is sent to the interpreter – the comments explain how it’s interpreted.

  5. Dave
    September 6th, 2010 at 00:24 | #5

    “If you’re used to a static language [...]“

    Closures aren’t limited to dynamic languages.

  6. vinhoverde
    September 6th, 2010 at 00:34 | #6

    Any decent lanugage has first-class functions / closures. Doesn’t make it automatically an awesome language. JavaScript has too many quirks for my taste.

  7. Jakob
    September 6th, 2010 at 11:10 | #7

    Glad you found a good tool…

    That knife can cut anything, and with it you can do anything

    But beware the "Hammer Syndrome"”

  8. September 6th, 2010 at 11:17 | #8

    Absolutely, but within JavaScript it’s almost always the best tool for the job, because it’s the only tool :)

    That doesn’t mean to say that JavaScript’s always the best tool for the job – that would be crazy talk!

  9. September 6th, 2010 at 11:28 | #9

    this is a great post !)

  10. jake
    September 6th, 2010 at 21:25 | #10

    sorry. js still sucks ;)

  11. jeo
    September 9th, 2010 at 02:07 | #11

    @Dave Yep even C# has them.

  12. September 10th, 2010 at 19:55 | #12

    Definitely agree with you, JavaScript is an awesome language! Functions as closures and first-class citizen are great things, but I’d also say that the way prototypical OO works, and that every object is a hashmap, is what makes JS awesome. That prototypes simply are regular functions and objects, with an extra way to call them. That array indexing is actually property indexing, and is a dynamic membership operator.

    Everything is so.. generalized. :)

  13. December 3rd, 2010 at 06:50 | #13

    JavaScript is fairly nice for writing short scripts that add basic interactivity to a page (which is what it was originally intended for). However, when it comes to maintaining with projects with thousands of lines distributed across hundreds of files the language is completely ill equipped.

    I believe the main reason for this is the language’s lack of functional programming features available in Haskell. For example, JavaScript has no constants, pure functions, type annotations, or any of that other stuff present in Haskell.

    The declarative purity of Haskell makes it absolutely perfect for being distributed over a network, as things like dependencies, concurrency, and parallelism can be handled automatically. Where as the process of distributing JavaScript over a network is a complete mess.

    The other things that make the language undesirable like the fact that + is used for both concatenation and addition, and there is with, eval, etc, however JSLINT can at least help you avoid some of the cruft.

    no classes, no modules, no iterators, no generators, no templates or generics

    JavaScript doesn’t have classes in the traditional OOP sense, however, they are often implemented with prototypes.

    The CommonJS group is working to implement modules, however, because of the fact that the language sucks their module system is a complete mess.

    JavaScript 1.7 provides us with iterators and generators.

    Indeed there is no templates or generics, and there certainly is many other features that arise from the lack of a type system. Which I will argue is a bad thing as people tend to put type data in their documentation rather then in their code, which means that compilers are not able to utilize that data which is being written down anyways…

    no macros.

    If you don’t miss the lack of macros either you haven’t witnessed the true power of macros in the Lisp sense, or you just haven’t written that much JavaScript.

  14. December 3rd, 2010 at 09:30 | #14

    @jhuni JavaScript isn’t Haskell, and it isn’t Lisp. It’s a very clean and simple language. Yes, there are certain things you can’t do with it, but that doesn’t mean it should be discounted as a great language. I wasn’t saying that it was the language to beat all languages, just that there’s a beauty in there that a lot of people don’t see.

  15. December 5th, 2010 at 22:51 | #15

    It’s a very clean and simple language.

    The JSLINT-valid subset of JavaScript, which is free of semi-colon insertion, bad blocks, ++, –, bitwise operators, with, eval, and several other features represents a relatively clean subset of JavaScript.

    You can probably take almost any programming language and construct a clean subset of it, that says nothing of the language itself.

    Similarily, the JavaScript language taken as a whole, with all the bad features included, can hardly be considered to be clean or simple.

    there’s a beauty in there that a lot of people don’t see.

    I don’t see it. What I see a lot of verbosity, redundancy, duplication and bloat.

    The language is verbose in the sense that to be clean and efficient you need to do so much extra work like: wrapping your for in statements with a call to Object.prototype.hasOwnProperty, caching objects to reduce property access, adding the extra = sign every time you want to check for equality, etc.

    On the other hand, the duplication and bloat arise from the inability of prototypal programming to constitute reuse. In the very core of the language a lot of functionality is duplicated across the Array and String prototypes.

    that doesn’t mean it should be discounted as a great language

    What discounts it as a great language IMO is the lack of the following features

    • namespaces
    • static typing
    • constants

    The lack of these three features forces developers to program in a completely dynamically typed global namespace. This alone is enough for me to use a JavaScript code generator such as GWT for anything other then very small scripts.

  16. eggstew
    December 11th, 2010 at 11:27 | #16

    @juhni: Nice trolling, two long comments filled with your highly personal and narrowly specified preference in programming languages.

    Clearly, JavaScript was not developed with you in mind, which begs the question: why are you replying to this post? Nobody is walking over to lisp-country to piss on your great language. Because I DO hope you realize that most of what you are describing as “missing functionality” are language features?

    If not, you must at least comprehend that different languages cater to different taste, or you just haven’t written that much of anything.

  17. eggstew
    December 11th, 2010 at 11:27 | #17

    Oh, and great article!

  18. December 11th, 2010 at 11:31 | #18

    @eggstew Cheers! :)

  19. December 12th, 2010 at 07:10 | #19

    @eggstew

    Nobody is walking over to lisp-country to piss on your great language.

    Recall that garbage collection, dynamic typing, lambdas, recursion, eval, and the if-then-else construct were all pioneered by us. So rather then walking over to our country to “piss on us” perhaps some people have been coming here to learn.

    two long comments filled with your highly personal

    I have pointed out specific technical problems. You on the other hand are the one who is the one being subjective and resorting to personal attacks by calling me a “troll.”

    Because I DO hope you realize that most of what you are describing as “missing functionality” are language features?

    Those are not missing features??

  20. May 4th, 2011 at 17:29 | #20

    @jhuni. I appreciate your objective assessment of Javascript. You were not trolling at all.

  21. Danny
    June 8th, 2013 at 04:47 | #21

    If you’re from a static language just won’t make sense

    Wat… Haskell/OCaml/F# all make heavy use of closures….. type systems really aren’t prevalent here. “If you’re coming from a C family language” would be better.

  22. Lars
    June 24th, 2013 at 11:19 | #22

    Just to offer some perspective, i would like to compare javascript to python:

    First: python has closures, function as objects and an elegant underlying model, Then: python does not have weird equality operators, automatic “fixing” of code, global variables problems Also: - python has a lot of easy to use libraries for all kinds of purposes - python has list comprehensions: e.g. [n for n in [1,3,6,7,9] if n%3 == 0] == [3,6,9] - python uses indentation instead of {}, which is much easier to read and much harder to make errors with - python has a straightforward class system, which is (at least) much easier to read then prototypes - python has straightforward namespaces in modules, classes, methods/functions, loops, etc. - straightforward ways to adapt attribute access to object attributes/properties (e.g add logging to all attribute access of a class in 3 lines of code) - has descriptors to e.g. Add static property typing to classes - has decorators to e.g. Add logging to functions in a couple of lines - has metaclasses to fundamentally adapt class behaviour - can call c libraries without too much fuss (though i havent done that) - its relatively easy to debug, for a dynamically typed language

    The only real advantage of javascript i see at this point is that it is understood by all major browers out of the box.

    Part of my point is that you cannot really declare something great without comparing it to something similar.

    (My other point is, if you haven’t, give python a try, its easy to get into and has a lot of depth, its elegance makes your code elegant, which in turn enables you to handle much more complexity in your program).

    Cheers, Lars

  23. October 17th, 2013 at 20:54 | #23

    If you want to obtain much from this paragraph then you have to apply such strategies to your won weblog.

  24. October 17th, 2013 at 23:30 | #24

    Let’s discuss some of the reasons which influence you to adopt male enhancement pills over other methods for sexual problem. Unfortunately for this reason, people never consider that an effective treatment should first have its source in nature. Some of these firms promise the moon and the stars, but turn out to be frauds.

  25. April 15th, 2014 at 10:42 | #25

    Hello There. I found your weblog the usage of msn.

    That is an extremely neatly written article. I’ll be sure to bookmark it and come back to read extra of your useful info. Thank you for the post. I will definitely comeback.

  26. July 3rd, 2014 at 22:10 | #26

    You have made some really good points there. I checked on the net for more information about the issue and found most people will go along with your views on this site.

  27. Jonatan Machado
    July 4th, 2014 at 16:27 | #27

    Great explanation!! Thank you share!

  28. July 15th, 2014 at 14:30 | #28

    Hiya! I know this is kinda off topic however , I’d figured I’d ask. Would you be interested in trading links or maybe guest authoring a blog post or vice-versa? My site covers a lot of the same subjects as yours and I believe we could greatly benefit from each other.

    If you happen to be interested feel free to shoot me an e-mail. I look forward to hearing from you! Wonderful blog by the way!

  29. July 20th, 2014 at 06:52 | #29

    This is really interesting, You are a very skilled blogger. I’ve joined your rss feed and look forward to seeking more of your magnificent post. Also, I have shared your website in my social networks!

  30. July 20th, 2014 at 10:44 | #30

    Very nice post. I simply stumbled upon your blog and wished to say that I have truly enjoyed surfing around your weblog posts. After all I’ll be subscribing to your feed and I’m hoping you write again soon!

  31. August 14th, 2014 at 08:23 | #31

    hello!,I really like your writing so so much! share we keep in touch more about your post on AOL? I require a specialist on this space to solve my problem. May be that’s you! Taking a look ahead to look you.

  1. September 6th, 2010 at 12:02 | #1
  2. October 11th, 2010 at 11:55 | #2
  3. November 9th, 2010 at 11:16 | #3
  4. April 26th, 2011 at 21:14 | #4
  5. July 22nd, 2014 at 12:27 | #5

Comments parsed as Markdown.