Which JavaScript Recipe Is Right For You?

Advertisement

JavaScript has been called everything from great to awful to the assembly language1 of the Web, but we all use it. Love JavaScript or hate it: everyone admits there are serious flaws and not many other choices.

Let’s start with some fundamental negatives. JavaScript has no good answer for some really basic features of modern programming languages: private variables and functions, packages and modules, standard localization mechanisms, code completion in editors.

While JavaScript is missing a lot of features, it’s the very dynamic nature of the language that scares so many static programming believers. This is all valid JavaScript:

obj1 = {
    func1: function() {
        return "I'm function 1";
    }
};

obj1['func2'] = function() {
    return "I'm function 2";
};

obj1['fu' + 'nc' + 3] = function() {
    return "I'm function 3";
}

var f = 'func4';

obj1[f] = function() {
    return "I'm function 4";
}

alert(obj1.func2());
alert(obj1.func3());
alert(obj1.func4());

Most languages support dynamic code loading2, but JavaScript encourages it. JavaScript has a lot of dark corners. Did you know that adding two arrays in JavaScript results in an empty string, or that [] + {} results in the string [object Object] but {} + [] is 0? Wat3?!?

JavaScript makes it so easy to write unreadable code that it’s impossible to write large projects in JavaScript4… except for Twitter, Facebook, Google, every big website you’ve ever heard of and hundreds of others.

These shortcomings cause me problems every day, but I still love JavaScript. It’s fun to code and it’s far from the assembly language of the Web. Assembly is nearly impossible to write by hand and even harder to read:

C005 B7 80 04        STA A  ACIA
C008 86 11           LDA A
C00A B7 80 04        STA A  ACIA

JavaScript is easy to write. If I have a button and want to know when someone clicks it, I could import a library like jQuery75 and write a click function:

$('#myButton').click(function() {
    alert('I was clicked');
});

Your grandmother can guess what this code does. That’s why JavaScript is a good first programming language6 and a great prototyping language. JavaScript programs go from a blank page to a working app ridiculously fast. They’re quick to write, don’t require a compiler and allow you to do anything you need.

These two views of JavaScript are difficult to reconcile. Is JavaScript an ill-defined loose language designed to cause premature gray hair, or a fun place to work? The answer is both.

We face this choice with every new Web project. Should we write JavaScript, or another language that generates it? This article shows you how to choose.

JavaScript Is Constantly Improving

JavaScript is the most popular client-side programming language in the world. It’s tough to find a website that doesn’t run it. It’s also come a long way with the introduction of excellent libraries like jQuery75, Backbone8 and countless others. JavaScript wins easily for small projects, but it falters when the projects and teams get larger.

Every large JavaScript project adopts conventions to compensate for the lack of language features. They’re simple patterns like using an underscore to mark some functions as private, or adding comments before arguments to indicate the expected type.

function formatDate(/* Date */ d) {
    var day = d.getDate();
    var month = d.getMonth() + 1;
    var year = d.getFullYear();
    return date + "-" + month + "-" + year;
}

These comments help, but there’s nothing to stop you from passing a string, number or anything else to the formatDate function. You can’t enforce a coding convention and you’ll never know it’s broken until the code actually runs in your production environment and fails. Extra type checking like instanceOf makes the program fail with a better error message, but it still fails at runtime instead of getting caught by the compiler.

Tools like JSLint9 or JSHint10 find common syntax problems like using == when you should have used ===, but they don’t address the larger issues. Libraries like RequireJS11 provide some support for modules in JavaScript, but that’s still just a convention. With nothing to enforce these patterns, you’ll spend endless hours tracking down annoying bugs. It’s never fun to debug someone else’s JavaScript.

Programmers love coming up with new solutions to existing problems, but there aren’t many good alternatives to JavaScript.

Google Web Toolkit (GWT)

Google made the first major effort to replace JavaScript with GWT12. The idea was to write Java code and compile it into JavaScript. Java provides many of the language features JavaScript is missing, and the compiler makes it possible to do a lot of checking before your code runs. With a nice debugger and a UI library added in, GWT looked like it would take over the world.

It didn’t.

GWT hasn’t failed (yet), but it hasn’t succeeded either. Java is a difficult language to write. It has a lot of complexity and requires a deep understanding of object-oriented programming.

Most of Java’s complexity comes from the hard problems it solves. That’s nice if you were going to have those problems, but overkill if you weren’t.

GWT added the complexity of the Web on top of Java. It was also positioned as a way to write code for the Web without needing to worry about browsers or HTML. It produced interfaces that looked clunky and ran slowly. It also led to some bad anti-patterns13.

It’s possible to write good applications in GWT14, but it takes a lot of work.

Even more distressing are the clear indications that GWT isn’t the future. Google’s still maintaining it, but the community is dwindling and its dreams of world domination are long gone. Even Google never really used GWT. All of their major products (Search, Gmail, Maps, Calendar, Docs, Google+) are written in JavaScript. Well… sort of JavaScript, but we’ll get to that a little later.

I still use GWT professionally, but I question it with every new project. GWT tried to drastically change the JavaScript ecosystem and it’s tough to turn an aircraft carrier on a dime.

CoffeeScript

The CoffeeScript15 team didn’t redefine JavaScript, they just gave it a face-lift. CoffeeScript added new syntax to improve some of the day-to-day difficulties of JavaScript programming without drastically changing the language.

Instead of this:

$(document).ready(function() {
    alert('Hello World!');
});

CoffeeScript lets you write this:

$(document).ready ->
    alert 'Hello World!';

The general philosophy is that writing less code means you have fewer bugs. CoffeeScript simplifies the JavaScript syntax by removing the need to declare var and using white-space indenting instead of curly braces.

CoffeeScript is growing fast, loved by Ruby programmers16 and hated by anyone with a secret crush on curly brackets. CoffeeScript compiles into JavaScript either when the page is run, or ahead of time during a build step.

CoffeeScript makes many syntactic improvements over JavaScript, but it has two main flaws. The first is that you can’t debug directly in CoffeeScript. Browsers don’t run CoffeeScript natively so you get all errors in compiled JavaScript and have to translate them back to your source code. That means you can’t write a CoffeeScript application without a pretty deep understanding of the JavaScript it will produce.

The second major flaw of CoffeeScript is that it’s basically just JavaScript with a different syntax. CoffeeScript means writing less code, but it doesn’t fix the real problems of JavaScript as a language. It’s still the case that I love my CoffeeScript and hate everyone else’s.

Google Closure Tools

Around the same time that CoffeeScript came out, Google made another effort to improve JavaScript with the Google Closure Tools17. Google tried to make GWT the next dominant Web technology, but it let Closure slip quietly out the door.

Closure includes a templating mechanism and a widget library, but the most interesting parts are the Closure Compiler18 and the Closure Linter19.

The Closure compiler (like the YUI Compressor20) takes your JavaScript and squishes it down so it takes less time to download and runs faster in production. The general idea is that you develop in standard JavaScript and compile it for release.

The Closure compiler turns this:

function sayHello() {
   alert('Hello World!');
}

$(document).ready(function() {
   sayHello();
});

into this:

$(document).ea(function(){alert("Hello World!")});

The result’s tough to read, but it runs a lot faster.

The Closure compiler supports two major modes: simple and advanced. Simple mode takes any JavaScript and compresses it by removing comments and white space, substituting variable names and making other safe changes. Simple mode has a very low chance of breaking your JavaScript, and it can find some issues when it compiles.

Advanced mode21 provides much better compression, but there’s a pretty good chance it will break your code unless you plan ahead. Advanced requires extra information to tell the compiler what not to remove. The very dynamic nature of JavaScript makes it tough for the compiler to follow every path in your code tree without some help.

The Closure tools also introduce JSDoc22 tags, which tell the compiler more about how your code works. In regular JavaScript you might define an object with three states for your application:

myProject.threeStates = {
    TRUE: 1,
    FALSE: -1,
    MAYBE: 0
};

You know that this is an enumerated type23 which constrains a value to one of these three options, but the compiler doesn’t know. Neither does that other developer on your team who added a fourth value dynamically. JSDoc lets you specify how this code works:

/**
 * Enum for my three states.
 * @enum {number}
 */
myProject.threeStates = {
    TRUE: 1,
    FALSE: -1,
    MAYBE: 0
};

By adding this comment you’re making it clear that this is an enumeration, that it only contains numbers and that you’re defining it as a strong type24 which you can use elsewhere. Combine this feature with the Closure linter that forces you to write comments like this and you’re basically redefining JavaScript. It still looks like JavaScript, but turned into a strongly-typed language.

That’s easy to see with the @type annotation:

/**
 * The name of the user
 * @type {string}
 */
var name = 'Zack';

JSDoc supports other annotations that control everything from what a function returns to who can call it. Add a module loader25, and the Closure library addresses a lot of the shortcomings of JavaScript, by turning it into Java.

Closure code looks like Java with clunkier syntax. It’s strongly typed, uses a similar packaging mechanism and has a powerful compiler. That’s a good and bad thing in all the ways that Java is good and bad.

Google isn’t putting much marketing behind the Closure tools, but they’re putting a lot of engineering there. All of the major Google products use Closure. Google+ was built on Closure26 from the ground up.

The Closure community is growing, but there still aren’t many people outside of Google who know it well. Closure also suffers from the need to maintain backward compatibility with JavaScript. The syntax looks clunky and only more advanced JavaScript and object-oriented programmers can write it.

Some people thought the Web needed a brand-new language. So Google continued its frenemy relationship with JavaScript by creating Dart.

Dart

Dart27 totally replaces JavaScript with a language that’s strongly-typed, uses interfaces and looks a lot like a simplified Java.

library hi;

import 'dart:html';

main() {
  query('#status').text = 'Hi, Dart';
}

This simple “Hello World!” example shows packages, imports and methods similar to Java syntax.

Dart can compile into JavaScript, but running it natively in the browser gets you better performance and debugging. Google controls the Chrome browser and may add native support for Dart there. They already have a special version running on Windows28. But it isn’t all up to Google.

Chrome depends on WebKit29, which also powers Safari from Apple. Webkit is an open source project made up of about one third Google people, one third Apple people and one third other people. The Chrome team would like to change Webkit to support Dart; that would make their lives easier, and also make Safari support Dart. If that happened they could claim two major browsers support it, and pressure the others to start. The Safari team doesn’t want the Web to run on a new language owned by Google, so they’re adamant about not including Dart.

It looks like none of the other browsers will support Dart30 either. That leaves you compiling Dart into JavaScript and losing some of the nicer features like integrated debuggers.

Dart has many technical merits; it’s eclipsed by larger political problems.

Some very smart Googlers work on Dart and it has some nice features, but it’s still an invention of Google and isn’t standard. It wasn’t developed by a community and there are good reasons for other vendors to distrust it.

The only thing certain about Dart is that its future is unknown. A preview (version 0.1) was recently released but isn’t really usable outside of Google. Dart is a language to keep an eye on, but not a real option yet.

Opa

Opa31 is the new kid on the block with a 1.0 release last August. It’s a strongly-typed language with a growing community. You write Opa and compile into other languages like JavaScript, but it isn’t just client-side. Opa mixes client-side and server-side programming into a single file.

Opa supports client, server and database development with a single language. Using the same code base, it compiles into JavaScript, native executables and SQL code. They recently added support for non-relational databases like MongoDB32 as well.

Unlike Dart, Opa draws heavily on functional programming languages like Erlang33. That makes it appeal to nerds, but the entry bar is pretty high. Opa lacks the simple syntax of CoffeeScript, and you can’t really teach yourself Opa without a strong background in other programming languages.

Though the bar is high, Opa rewards your learning investment by giving you a single environment where you don’t have to switch languages between client and server. It hasn’t grown much beyond samples and small websites, but it’s gaining ground.

What Should I Do?

The JavaScript problem is everyone’s problem; there are no good answers. It’s possible to write good JavaScript that scales to large projects, but that takes constant attention and the right culture.

There are a few other options for generating JavaScript (for example, Clojure34 compiles into JavaScript), but they’re still small projects without much real-world use.

Google writes most of their client-side code with the Closure tools and they’re starting to adopt more Dart. Other large websites like Twitter use JavaScript combined with other technologies like Ruby On Rails. Big open source projects like WordPress mostly stick with straight JavaScript and jQuery. Facebook uses a combination of all of them. Microsoft combines jQuery with .Net and some other server-side technologies which interact with JavaScript. They’ve also released a new static-typed JavaScript variant called TypeScript35.

That just scratches the surface. The CoffeeScript project maintains a comprehensive list of languages that compile into JavaScript36.

If your project is small, then just write JavaScript. jQuery is very well done; so are many other JavaScript libraries. Keep your project small and the problems stay small.

But the line between small and large is blurry. Small projects get bigger with time, and you can get into big trouble writing large JavaScript applications without a lot of process to keep you out of the bad parts37. The other options are either has-beens or aren’t-yets.

A big part of this problem is the difficulty of finding a single language that keeps everyone happy. Small websites want something simple that makes it easy to get started and produce an app quickly. Large projects want the structure to keep the code base maintainable for years. The two goals are at odds and no language has ever satisfied both parties. That’s why Visual Basic38 and C++39 are both so popular.

There’s also no reason to choose just one. GWT combines well with regular JavaScript, and you can use the Closure Compiler simple optimizations with any JavaScript project.

JavaScript will never be the best language for all applications, but browsers won’t support another one anytime soon. The key to using JavaScript well is to understand its limitations and know when not to use it. JavaScript is easy for small projects; you need planning, care and help from other libraries to work on larger ones.

Image on front page created by Ruiwen Chua40.

(cp)

Footnotes

  1. 1 http://en.wikipedia.org/wiki/Assembly_language
  2. 2 http://en.wikipedia.org/wiki/Reflection_(computer_programming)
  3. 3 https://www.destroyallsoftware.com/talks/wat
  4. 4 http://blogs.adobe.com/bparadie/2012/05/07/the-pew-pew-manifesto/
  5. 5 http://jquery.com/
  6. 6 http://www.stanford.edu/class/cs101/
  7. 7 http://jquery.com/
  8. 8 http://backbonejs.org/
  9. 9 http://www.jslint.com/
  10. 10 http://www.jshint.com/
  11. 11 http://requirejs.org/
  12. 12 https://developers.google.com/web-toolkit/
  13. 13 http://www.zackgrossbart.com/hackito/antiptrn-gwt/
  14. 14 http://www.spiffyui.org
  15. 15 http://coffeescript.org/
  16. 16 http://www.rubyinside.com/rails-3-1-adopts-coffeescript-jquery-sass-and-controversy-4669.html
  17. 17 https://developers.google.com/closure/
  18. 18 https://developers.google.com/closure/compiler/
  19. 19 https://developers.google.com/closure/utilities/
  20. 20 http://developer.yahoo.com/yui/compressor/
  21. 21 https://developers.google.com/closure/compiler/docs/api-tutorial3
  22. 22 https://developers.google.com/closure/compiler/docs/js-for-compiler
  23. 23 http://en.wikipedia.org/wiki/Enumerated_type
  24. 24 http://en.wikipedia.org/wiki/Strong_typing
  25. 25 http://closure-library.googlecode.com/svn/docs/class_goog_module_ModuleLoader.html
  26. 26 http://highscalability.com/blog/2011/7/12/google-is-built-using-tools-you-can-use-too-closure-java-ser.html
  27. 27 http://www.dartlang.org/
  28. 28 http://www.dartlang.org/dartium/
  29. 29 http://en.wikipedia.org/wiki/WebKit
  30. 30 https://news.ycombinator.com/item?id=2982949
  31. 31 http://opalang.org/
  32. 32 http://www.mongodb.org/
  33. 33 http://en.wikipedia.org/wiki/Erlang_(programming_language)
  34. 34 http://clojure.org/
  35. 35 http://www.typescriptlang.org/
  36. 36 https://github.com/jashkenas/coffee-script/wiki/List-of-languages-that-compile-to-JS
  37. 37 http://shop.oreilly.com/product/9780596517748.do
  38. 38 http://en.wikipedia.org/wiki/Visual_Basic
  39. 39 http://en.wikipedia.org/wiki/C%2B%2B
  40. 40 http://www.flickr.com/photos/7162499@N02/3260095534/

↑ Back to topShare on Twitter

Zack Grossbart is an engineer, designer, and author. He's a founding member of the Spiffy UI project, the architect of the WordPress Editorial Calendar, and a Consulting Engineer with NetIQ. Zack began loading DOS from a floppy disk when he was five years old. He first worked professionally with computers when he was 15 and started his first software company when he was 16. Zack lives in Cambridge, Massachusetts with his wife and daughter.

Advertising
  1. 1

    Thanks for the awesome overview. I realize the rise of mvc frameworks stem from trying to help you write better JavaScript. It’s exactly why I choose Backbone. It has helped me understand the language better and I see no reason why you cannot write large-scale applications with it. Without a framework as such, I have to agree, and say that writing a large application would be near impossible without some sort of framework. Using another language altogether, in my opinion, is just wrong.

    0
  2. 2

    Regarding Dart:

    While development has been done by Google to date and not “the community”, Google has been very open and receptive to feedback (maybe even too much). The positive side is they have been able to cut through a lot of the B.S.

    The political obstacles you mentioned should be eliminated when Google turns Dart over to the community as planned. I don’t think it will be a mess like the JCP with Oracle. The DNA of Google is too different.

    Dart is bringing real and substantial solutions to JavaScript’s dark corners. In the meantime I’ll be happy to cross-compile into JavaScript until the other browsers adopt the Dart VM.

    0
    • 3

      Dart has two main issues: the reality and the perception. In reality they’ve been very good about opening up their process and taking feedback. I think they will release it well and make it open.

      The perception is that it will always be owned by Google and they have some real work ahead of them to convince Apple and Microsoft to accept it.

      0
  3. 4

    The second major flaw of CoffeeScript is that it’s basically just JavaScript with a different syntax

    This is one of the things that make CoffeeScript great, not a flaw.

    0
  4. 6

    Closure isn’t Google’s effort to make javascript better. Closure has been used for years internally before it was released, and the reason it doesn’t get the fanfare is because Google isn’t trying to push it on to other people. Closure is what they have used internally in the past and they don’t want lots of people externally using it (as then they’d have to spend the time to improve and maintain it). They decided that a small release would bring on a small community that could help, whereas other products like GWT and Dart are a concerted effort to influence the ECMAscript committee and browser vendors, rather than a tool that is used by every part of their business.
    And the best thing? It’s real javascript.

    0
  5. 7

    Great article but you really need to revise it once you’ve had a chance to evaluate TypeScript, it’s not exclusive to the Microsoft stack.

    http://stackoverflow.com/questions/12678716/transforming-typescript-into-javascript

    0
    • 8

      I second that. It is a great article but its brief mention of TypeScript is a gaping hole. Now when I forward it to others I have to add a qualification.

      I also disagree that JavaScript is a good language for learning programming. That is hard to support after showing how many problems it has. Yes, many of its problems apply to its use in large projects but their are plenty of quirks that apply to small ones too.

      0
    • 9

      TypeScript is a really interesting option. I’ve been keeping an eye on, but it’s a little too early to know how successful it will be. Do you know of any big projects using TypeScript. I haven’t seen much outside of the TypeScript site and Microsoft.

      0
    • 11

      I love TypeScript. Compile time debugging is an obvious win, as it is with the other compile to JS languages. But its sticking point will be on runtime debugging. As the code map feature matures it will be up to the IDE makers to drive TS’s adoption rate. The true difference with TS is that while waiting for code map debugging support, it sits closer syntactically to the output JS than the others (particularly when migrating an existing JS project).

      0
  6. 12

    Jørn E. Angeltveit

    December 14, 2012 5:09 pm

    You also have tools like Smart Mobile Studio, which converts Object Pascal code into JavaScript.

    All the powerful OOP features you’d expect from a modern programming language, the language-safety you need for serious development, and all the benefits you have when you’re using an easy and readable language.

    0
    • 13

      Thanks for letting us know about Smart Mobile Studio. The number of languages that compile into JavaScript is huge.

      0
  7. 14

    Seriously JavaScript debugging is amazing compared to Cache Object Script, which I am currently writing, wish I could be JS debugging right now!

    When you have to work in a language which the error messages are non-existent, nonsensical or simply generated intermittently by the compiler and not a coding error then JS looks like the best language ever.

    Solving a JS issue normally only requires a minimal googling to find out a browser does not support a method or property rather than fighting the poor documentation of less popular languages. JS’s “popularity” and community makes it a better language than most. Semantic arguments about scope, public/private etc come so far behind these aspects that it feels barely worthwhile even debating how good the language is.

    0
  8. 15

    Java was never intended to replace C++. Also I would argue that JavaScript is very difficult to get you head around especially if you have come from Java, C# or Visual Basic .NET, especially when you think about things like variable scoping and how the “this” keyword behaves.

    Opa I wouldn’t recommend, the page weight for every page is simply massive compared to using jQuery, a Grid System and some Semantic HTML.

    0
  9. 16

    You can’t enforce a coding convention and you’ll never know it’s broken until the code actually runs in your production environment and fails.

    I definitely have to disagree with that. There is literally no excuse for not unit testing. With tools like Jasmine and the various plug-ins you can test almost anything.

    0
    • 17

      Signed up just to reply to this comment. Yes. A million times. Reading this line made me embarrassed for the author.

      0
      • 18

        I’m a big believer in unit tests. I even wrote an article about unit tests for Smashing. There are many good unit testing frameworks for JavaScript, but I’m wary of how easy it is to skip a unit test you should have written.

        Do you have any suggestions for making sure all the right unit tests get written? Do you know of any good test coverage tools for JavaScript?

        0
        • 19

          In Ruby land I use something like Capybara and drive a headless browser to do integration testing whenever there is craziness going on and I want to make sure the page has the content I expect it to have. You can get a long way with Jasmine’s “spies” and Sinon.js gives you the idea of fake servers. While testing JS can be tricky, it certainly is not a “you’ll never know it’s broken until the code actually runs in your production environment and fails.” scenario.

          0
        • 20

          My former colleague has created this tool http://timurstrekalov.github.io/saga/ for JavaScript code coverage. I have only used it on a small research project but it looks quite promising.

          0
  10. 21

    Not to be a dick, but some of your javascript is actually jQuery…

    0
  11. 24

    We should separate flaws that come from the comparison with each of our own preferred languages and the real ones of JavaScript. In fact, there are only few real flaws in JavaScript (and highly more debattable ones):
    * It’s dynamically typed, making “compile time” checking impossible. Whether you are pro or against statically typed languages, it’s a serious advantage we can denied them,
    * It’s not really built for modularity and “import style” programmation. Require.js and other AMD libraries tend to fill this flaw, but’s it’s not in the core of the language.

    What we can expect is not a replacement language or another layer compiling to JavaScript, it’s simply an evolution of ECMAScript in its next versions which will effectively tackle with those issues more than enrich, in some “useful but not so” manner, the core API.

    0
  12. 25

    Great article! I’d just want to add that’s it not really true that you won’t find an editor that has code completion. Both eclipse and netbeans have some code completion. And if your’e willing to pay for your IDE you can choose any of jetBrains products, they have a truly impressive understanding of the javascript code.

    0
    • 26

      Visual Studio has intellisense for JavaScript.

      0
      • 27

        Some editors have a little code completion for JavaScript, but they can’t provide the same level of completion that you can for other more static languages.

        I haven’t had a chance to try JavaScript in JetBrains or Visual studio. Do they do a good job?

        0
        • 28

          I can’t tell when it comes to Visual studio but if you haven’t tried any of jetBrains IDE´s I think you will be amazed. Download a free trial of WebStorm and try it out. (and the answer is “No, I do not work for jetbrains :)”)

          0
        • 29

          VS2012 has definitely improved a great deal over earlier versions, out of the box you get code collapsing and ‘go to definition’ (albeit not perfectly) which is massively handy.

          It’s intellisense for pure JS is pretty strong and by using the ‘/// references’ you can pull in most libraries to a reasonable level.

          One thing I also found out the other day is that VS’s intellisense actually get better when the app is running, so if you’re in debug (as it can determine more about the app) the intellisense is quite impressive.

          It does still struggle when functions extend or utilise multiple files, but it’s a lot better than it used to be!

          0
        • 31

          You are right about Javascript lacking basic features needed to keep large projects maintainable.

          If find annotating my code with the annotations of the Closure Compiler incredibly powerful. It gets even better when you use an IDE like WebStorm, which supports the Closure annotations and has advanced code inspection for type annotation, inheritance, access control, etc. etc. Using annotations makes your code much easier to control in large projects. And as a side effect, it encourages you to document your code.

          Like Vic points out, WebStorm does an amazing job when it comes to code inspection and autocompletion. This IDE finally allows me to create Java-scale projects with Javascript. I doubt if your statement that “… some editors have a little code completion for JavaScript…” still holds these days :). Give it a try.

          (and the answer is “No, I do not work for jetbrains :)”)

          0
  13. 32

    I’m trying out AngularJS and Backbone at the moment. Both allow you to organise large amounts of JS code into an MVC (kinda) structure and I can see no reason not to build large apps in pure JS.

    Personally, I hate Coffeescript. To somebody that is used to reading javascript it looks messy, not to mention the use of whitespace for structure (eugh!) and the fact that you have to learn a new language just to replicate what you can already do in the old language. I just don’t see the sense in it.

    0
  14. 33

    Peter-Paul van Gemerden

    December 17, 2012 12:59 pm

    “Let’s start with some fundamental negatives. JavaScript has no good answer for some really basic features of modern programming languages: private variables and functions […]”

    Private properties are entirely possible and quite practical. It’s a simple matter of defining the private variables and functions, as well as the public functions that need access to them, inside the constructor. Douglas Crockford wrote about this pattern, more clearly than I ever could, back in 2001 (“Private Members in JavaScript”, http://javascript.crockford.com/private.html).

    The downside of this, is that neither the private properties nor the “privileged” methods are part of the prototype, so they are created again for each instance. IMHO this is a pretty small price to pay when you really need private properties.

    The thing that JavaScript really doesn’t have, is protected members. I doubt that anyone misses them, but I suppose you could find a use for them in really large applications.

    0
    • 34

      Thanks for the comment.

      Douglas Crockford’s method makes it possible to write a sort of private function, but you have to jump through a lot of hoops to do it. There are also many coding conventions for creating private variables and function in JavaScript like starting them with an underscore.

      My issue with these patterns is that you can’t enforce them. They are nice conventions, but there’s no way to make sure people follow them without a lot of code review.

      0
      • 35

        Richard Wagenknecht

        December 17, 2012 5:45 pm

        You honestly don’t understand the concept of a closure if you think JavaScript requires you to jump through hoops to create private variables and functions.

        0
      • 36

        I don’t see any cumbersomeness in the way to use closures to control the scope of variables. It’s not as explicit as the way it’s made in other languages with keywords like private, public, protected, but it’s clearly managed by JavaScript.

        One again, it’s just that JS disturbs some of our usual practices in our everyday languages.

        0
  15. 37

    “JavaScript has no good answer for some really basic features of modern programming languages: private variables and functions, packages and modules, standard localization mechanisms, code completion in editors.”

    I can’t agree with the part about JavaScript not providing “good answer” for private variables and functions (methods). How about closures (leaving alone the fact that comparing prototype based inheritance to the class based one is a bit like comparing apples and oranges ;})?

    IMHO the biggest problem of JavaScript is that it “looks” similar to Java while not “quacking” like it. Because of that most people try to use “Java” methodologies and fail horribly. Well, “think Scheme” instead :}.

    As for the rest, I think it’s rather “outside of the language” problem.

    0
    • 38

      Richard Wagenknecht

      December 17, 2012 5:51 pm

      Well said. The author doesn’t understand some very key concepts about JavaScript. I see many Java, C#, C++ developers make the same mistake the author is making. They confuse it with other languages because the syntax is similar. The author would be well served by reading Crockford’s book.

      0
  16. 39

    In my experience using javascript to structure large projects isn’t more (or less) difficult than say Java or C#, as long as you’ve got proper (OO)-guidelines in place.

    Perhaps it’s the ability of javascript to cut lots of corners very efficiently (multiple inheritance, mixins and closures come to mind), that diffuses the need to architect your project properly.

    0
  17. 40

    Thanks for the cool article, glad someone else agrees with me on JavaScripts issues!

    Maybe this is for a separate article but another tool that upgrades GWT and makes it (far) better is Vaadin (https://vaadin.com/home). I have used it before and find the code it creates so much nicer than GWT. But again, maybe this topic warrants a follow up article called “GWT and its (better) children?”

    0
  18. 41

    typo?
    “Most languages support dynamic code loading, but JavaScript encourages it.”..

    0
  19. 43

    How about we all start using the ‘strict mode’ introduced in ECMA/JavaScript 5. Most browsers support it.
    It should help improve code quality side mentioned in the article.

    0
  20. 44

    “Most languages support dynamic code loading, but JavaScript encourages it.”
    What exactly is your definition of “dynamic code loading”? Since you’re linking a Wikipedia article about Reflection there… And Reflection has nothing to do with code loading.

    “Assembly is nearly impossible to write by hand […]”
    I mean, seriously?! First of all, you only posted some weird hex digits there, and no mnemonic or opcodes… Second, why did you only post some hex digits there?

    I think you should have focused this article around the topic “Should we write JavaScript, or another language that generates it?” Because, this is what most of it is about.

    The first section tries to be self-critical about JS, but contains mostly dangerous half-truths. Including some fragments of the WAT talk doesn’t help here etiher.

    0
  21. 45

    Not a totally bad article, but your second paragraph just pushed my buttons – though I think what I’m about to do it rude, I just have to correct you because some things are just so wrong:

    “Let’s start with some fundamental negatives. JavaScript has no good answer for some really basic features of modern programming languages:”
    Great.

    “private variables and functions,”
    Javascript has both of these things:
    var global_variable = true;
    var a_function = function() {
    var private_variable = true;
    return global_variable === private_variable;
    };

    If you’re talking about private variables in the sense of classes, then you’re making the language (Javascript) something it’s not. Though Javascript is object-oriented, it is not class based, but prototypal. Both are great in their own way:
    http://en.wikipedia.org/wiki/Class-based_programming
    http://en.wikipedia.org/wiki/Prototype-based_programming

    “packages and modules”
    This is your only point I can agree with – there is no native way of doing this, but there are tools like RequireJS (http://requirejs.org/) that help with this problem.

    “standard localization mechanisms”
    As far as I am aware, most programming languages don’t natively support this. Most have third party libraries to handle this – Javascript has them too:
    http://eligrey.com/blog/post/passive-localization-in-javascript
    http://dev.foyt.fi/node/7

    “code completion in editors.”
    This is up to the text editor or IDE you’re using. Very few programming languages come with a standard text editor or IDE you’re to use – including Javascript. You really cannot blame the language for this.

    0
  22. 46

    You talk about CoffeeScript not having first-class debugging, but that is not exactly the case. For example Chrome supports source maps that allows debugging for languages compiled into JavaScript to take place. CoffeeScript will hopefully support this in the future, in the meantime you can check out projects like CoffeeScriptRedux.

    http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/
    http://ryanflorence.com/2012/coffeescript-source-maps/

    0
  23. 48

    Regarding GWT:
    The article about the anti-pattern is from 2009. GWT evolved quite a bit since then and most of the anti-pattern are actually not really an issue anymore or at least GWT provides some solutions for that.

    Also development on GWT changed.
    A steering community consisting of Google, Red Hat, Vaadin, Sencha, Acrbees, etc and also many important contributors (i.e. Thomas Broyer) is now responsible for the future of GWT.

    0
  24. 49

    I mostly coded in JavaScript for the last 8+ years career.
    And comfortable with it…

    Worries when I see CofeeScript,TypeScript , Dart etc which just trying to make JS something else.
    And a bunch of MV* frameworks….

    I consider it as abusing JavaScript to behave like Java/C.
    JavaScript is JavaScript and stop beating it to behave like Java.

    jQuery is there to solve most of cross browser issues.
    An agreed design pattern can handle larger apps…

    Framework Less MVC (lessMVC)

    http://johnchacko.net/?p=5

    0
  25. 50

    and which javascript recipe if I want to build it on IE6 ? This is my real experience.

    0
  26. 51

    Interesting article, but if the point is to present alternatives to javascript (or ways to improve it), it’s worth mentioning Haxe as well: http://haxe.org

    0
  27. 52

    In 2005, I would have agreed about most of your gripes about Javascript. Then I discovered that it’s not a class-based language, and stopped fighting it. Then I fell in love with it and find it very expressive.

    Now, I have to disagree with just about everything in your article. First, you don’t even do what you said you would (Should we write JavaScript, or another language that generates it? This article shows you how to choose.) It does not, unless the choice is as follows:

    I am a Java programmer that can’t be bothered learning Javascript = GWT
    I am a Ruby programmer that can’t be bothered learning Javascript = Coffeescript
    I work for Google = Closure
    I am a C++ programmer that can’t be bothered learning Javascript = Dart
    I am doing some esoteric masters thesis that has no real-world application = Opa
    I am a C# programmer that can’t be bothered learning Javascript = Typescript

    What you probably don’t realize is that ECMA tried to ‘solve’ your ‘bad parts’ with ECMAScript 4 (strongly typed, imports) and it went nowhere. As far as I know only 2 vendors took the time to implement the spec (Firefox & Adobe) and it was a mess. It turned out that trying to shove JS into a Java-shaped box ended with a language that was the worst of all worlds. And while I have only had a cursory glance at Typescript, it looks like they just re-implemented this failed spec.

    The only problem with not being strongly typed is that it’s only a problem if you abuse it. Yes, on a large project you can have cowboys writing all kinds of crap that makes it hard to maintain & debug. But you can make any language unmaintainable if you don’t enforce coding standards.

    The problem with imports is that JS was a language for the web. If you say ‘import ‘library_a’ what is the path? Where does the browser look? There is no build path, because it’s not being pre-compiled. No matter what language you could imagine, you’re going to have this problem unless you’re pushing down pre-compiled binaries. If that’s your thing, see Adobe Flash. It would be very difficult to solve this in a way that everyone agrees with. So that leaves creating a way to do dependency management and module loading, which any good (non-JQuery) library will give you.

    The biggest problem with people who voice this type of complaint is that they’re basing their ‘enterprise’ Javascript experience on JQuery. Then yes, the following are true:
    1. It makes small projects easy and fast to develop
    2. There is no way of controlling dependencies between modules
    3. It quickly turns into an undecipherable jumble after the project gets over a certain size
    4. It becomes unmaintainable quickly

    But those are faults in JQuery, not Javascript.

    JQuery !== Javascript

    0
    • 53

      I would recommend having another glance at Typescript because it doesn’t force JavaScript into a “box”, it just adds a few extra features which you can avoid if you wish (they are all optional). Also, almost all JavaScript is valid Typescript (the only problem you may encounter is trying to use reserved words).

      And if you don’t feel like learning another language, or you’re still hesitant, wait for Typescript to get to 1.0 before you give it a try :P. Most of the bugs and unwieldiness (lack of features) that’s left should be ironed out by then.

      In my opinion, the most important thing it provides is the ability to tell what variable type another programmer was expecting for their files without having to dig through their code.

      0
  28. 54

    I’m gonna keep this short because I’m a bit late to the party.

    Some of your complaints with JavaScript should go away with ES6 (modules, real private variables via symbols, etc). Unfortunately, it’s a lot harder for JS to make advancements than other languages, but change is coming.

    Besides that, a lot of your arguments really have nothing to do with JS and more to do with dynamic vs static typing. End of story. Believe it or not, some people actually prefer dynamic typing. It’s understandable to not, but that is not a flaw with JS really, it’s just not your cup of Java :)

    0

Leave a Comment

Yay! You've decided to leave a comment. That's fantastic! Please keep in mind that comments are moderated and rel="nofollow" is in use. So, please do not use a spammy keyword or a domain as your name, or else it will be deleted. Let's have a personal and meaningful conversation instead. Thanks for dropping by!

↑ Back to top