10 reasons why Dart is cooler than JavaScript

By Christian Grobmeier

Dart is a new programming language from Google and after coding JavaScript for over one year now, I immediately felt in love with it. Coming from the Java world I had a good bunch of things I had to learn before I could use JavaScript.

Some people say, you need to dig deep into JavaScript, otherwise you are not allowed to speak about the pros and cons of a language. I am not a JavaScript Ninja. But I strongly believe a programming language should be easy to learn, easy to understand and should be consistent in terms of language constructs. Even after all the long time I dealt with JavaScripts weakness, and even when I meanwhile think JavaScript has some pretty cool ideas, I must say that I need to be very, very, very carefully every day when I work with it. And that’s bad. A language must support his programmer and not vice versa.

Here are some of the JavaScript flaws which will make me switch to Dart, once it is ready for production. Please keep in mind that Dart is in the makings.

1. Dart uses only one falsify

Looking at this post, you will easily see the point. The values: false, null, undefined, “”, 0, NaN will evaluate to false. Means you can write things like this:

var a = null;
if(!a) {
   // do
}

In Dart there is only one thing which is false. It is false itself. Of course you need to rewrite to this:

var a = null;
if(a != null) {
   // do
}

Using 6 falsifying expressions is well, let’s say you need to learn about it.

2. Dart can work with types, if you want it

JavaScript devs often say types kill flexibility. OK, might be true. But too much flexibility will kill your software. Sometimes you want to work with types, and with Dart you can do it – if you want. Just enable the type checker and go ahead.

3. You need a framework to work proper with DOM

In JavaScript you can work with these old friend:

getElementsById()
getElementsByTagName()
getElementsByName()
getElementsByClassName()
querySelector()
querySelectorAll()
document.links
document.images
document.forms
document.scripts
formElement.elements
selectElement.options

Isn’t it nice? Thanks heaven we have got jQuery (and friends) to help us out of this. But… should it really be necessary to use a framework when simply selecting from the DOM? Not today.

Dart has looked at jQuery and has stripped it down to 2 methods:

elem.query('#foo');
elem.queryAll('.foo');

Much better.

4. Classes and Interfaces

When Java developers start with JavaScript they often try to write JavaScript like they write Java-Code. There are constructors and class like elements. Of course this is not the way JavaScript should be programmed. It is prototype based, everything is an object. This is somehow cool. But you can throw away many of your Gang of Four Design Patterns and instead read about JavaScript design patterns.

Honestly, some of the developers I have worked with have invested a long time to understand the “mainstream” patterns. Not everybody is a geek. Using a non-mainstream programmin language in a mainstream environment leads to the center of ultimate chaos.

5. Inheritance

Dr. Rauschmayer explained at his excellent blog post why JavaScript inheritance is easy. He is right. It is easy. But be warned: his recommendation is not the only way for JavaSCript inheritance. The Frameworks Prototype and jQuery have even created “extend” Methods. Instead of Dr. Rauschmayers use of __proto__ you can use the prototype keyword (and yes this guy even speaks of classes, even when there are no classes). Of course you can implement your own extension mechanism and simply copy every property yourself.

All the results popped up when searching Google for “javascript object extends”. It is a confusing mass of different approaches for achieving a simple goal: extensions.

Guess not everybody reads Dr. Rauschmayers blog. It would be so easy if.

Dart does know classes and therefore does now the “extends” keyword. Pretty damn simple.

6. Global namespace

In JavaScript you need to take care that you don’t put stuff in your global namespace. Honestly, this can be done so easy. If you miss a “this” or a “var” you have a variable on a global level. Every script has then access to it. This is terrible. Try to not mess up things. Thanks to Stoyan Stefanovs Book JavaScript Patterns I have learned a pattern to keep my namespace clean. I feel better now and have more control over what I do. But: I need a pattern for it. This is such a basic need and does not come out of the box.

In Dart you develop in “library” scope. Means, you have a keyword “library” and only what is public is visible outside of it. In addition, every Dart script executes as its own Isolate. Means, it has a fresh state, without the mess of other scripts around. With Dart you should still think about visibility and libraries, but its way easier and for sure you don’t need a book teaching it to you. Instead, just think about “Separation of concerns” and you are in the game.

7. Dart knows concurrency

With JavaScript things are not really concurrent. Even when you make an “asynchronous” request from jQuery, you are still working with one “thread” only. I think there is some chance to get more from V8, but I am not sure on it. You can solve it with HTML5 and webworkers.

Dart knows Isolates. These are little beasts similar like in Erlang. They can communicate to each other. If one fails, another Isolate can simply restart it again. Isn’t that cool? And of course this makes Dart very nice for server side programming too. Yes, I have heard of Node.js. But that is not my point. Dart can do that magic out of the box.

8. JavaScript doesn’t know foreach

Oh wait.

You can extend Object or the Array.prototype which is pretty nice.

Or you do the following for arrays:

for (var i = 0; i < elements.length; i++) {
  // do something
}

And you can even do that for objects:

for (key in elements) {
  alert(elements[key]);
}

But unfortunately Douglas Crockford (a very important guy in the JavaScript world) recommends not to use this statement. Reason: your results are not ordered and you might members from the prototype chain or function names.

Of course you can filter with hasOwnProperty.

Finally you should look into your frameworks docs if they offer something like forEach. jQuery does.

In Dart:

for (element in elements) {
  // do something
}

Life can be so easy. You iterate here over a list of elements.

9. Weirdness intializing arrays

This one is borrowed. Look at this:

var a1 = new Array(1,2,3,4,5);
var a2 = new Array(5);

a1 is an array with 5 elements: [1,2,3,4,5]
a2 is an array with 5 elements to: [undefined,undefined,undefined,undefined,undefined]

Dart is much more cleaner. An array is basically a List and therefore has this interface.

List a1 = [1,2,3,4,5];
List a2 = new List(5);

Again, a1 contains 5 different elements. a2 contains space for 5 elements.
In addition you get nice features like “removeRange” or support for sorting. Check out Seths blog.

10. undefined and null

There is much you need to learn when starting with JavaScript. Among them is the holy knowledge that there is not only null, there is undefined too. It is a type with only one value: undefined. It can be overridden. And you can get it by various scenarios, for example if you call return but don’t return any value. At the linked page you can even see how you can deal with a possible overwritten undefined value.

It seems null can be replaced by undefined in pretty much scenarios.

This is sick.

Dart does only know one null.

Conclusion

JavaScript has some good parts, of course. There are some nice patterns. But for the moment, I have seen nothing I can’t do with Dart. Dart is mostly more elegant and easier to read (to my taste). Some hardcore JavaScript devs will think different, but that’s ok. You need to love JavaScript if you want to work with it (or arrangte. Dart on the other hand is pretty mainstream. And thats good.

PS: I missed the event handlers in this list – another thing which is pretty much cooler than in JavaScript. Check them out.


Follow me on Twitter :-)

  • Steve

    [1, 2, 3, 4, 5] works just fine in JavaScript, as well. (as does JSON for initializing an object, but Dart probably does, as well.)

    Also, in newer versions of ECMAScript (i.e. in browsers/environments that actually support features, not outdated versions of IE), Array.prototype has filter, map, reduce, and forEach.

  • http://www.openswimsoftware.com Corbin Uselton

    I see a lot of reasons why dart would be nice. Though I have been using coffeescript for about 6 months now and although it may not do as much as Dart(not sure if that is true or not). I am going to stick with it for one reason, Dart needs to be Implemented by the browsers. Coffeescript compiles to regular javascript so you can not worry about JavaScript headaches and still write code that works in all browsers today. Just my 2 cents

  • http://rauschma.de Axel Rauschmayer

    It’s not entirely fair to compare a language in progress (Dart) with a language that has been in use for 1-2 years (ECMAScript 5). Most of JavaScript’s quirks will go away with ECMAScript 6 (which will be finished by 2013). I’ll sometimes point to ongoing JavaScript projects (which is not entirely fair to Dart, but it shows the momentum behind JavaScript).

    That being said, Dart undoubtably cleaned up many of JavaScript’s rough edges, you even missed a very bad one: JavaScript’s dynamic `this`. On the other hand, not all of your complaints are valid:

    5. Inheritance: A very real concern under ECMAScript 5. Thankfully, ECMAScript 6 will introduce a standard construct for instance factories.

    6. Global namespace: Once you know the pattern, I don’t find it that difficult to understand and use. You can already use Node.js modules or AMD modules [1] in browsers. Both make global scope a non-issue. ECMAScript 6 will standardize a module system.

    7. Concurrency. I would love to see a comparison between WebWorkers and Isolates, somewhere. Concurrent JavaScript is being worked on, one example is Intel’s RiverTrail [2].

    8. Foreach: ECMAScript 5 comes with a built-in forEach() array method.

    9. Weirdness initializing arrays. Not usually a problem: The rule is to never use the Array constructor in the manner you use it for a1. Then you have the following code and everything is fine:
    var a1 = [1, 2, 3, 4, 5];
    var a2 = new Array(5); // empty array of length 5

    10. Having both undefined and null. An ugly legacy “feature”, but rarely a problem in practice. You simply treat both values as the same. ECMAScript 6 will make that easier.

    Advantages of JavaScript over Dart:

    1. Momentum on both server and client. It is the standard for writing web applications. Node.js allows you to use the same language on the server and has a vibrant community. JavaScript is also becoming an important player in mobile applications and desktop applications (PhoneGap etc.). There are many projects underway for improving it and for using it for all kinds of tasks (Windows 8, Chrome OS, B2G, webOS, etc.).

    2. Openness. JavaScript is a very open programming language: It has a clearly written language specification (Dart’s seems unfinished and hard to read) and several implementations adhering to it, from competing vendors.

    3. Objects first. You can start with concrete objects and introduce abstractions later. That makes JavaScript quite agile.

    My advice is to check out both Dart and JavaScript (e.g. via [3]). JavaScript requires a more open mind than Dart, especially if you come from a class-based language such as Java. But it will also more easily land you a job and (currently) has broader applications.

    [1] http://www.2ality.com/2011/10/amd.html
    [2] http://blogs.intel.com/research/2011/09/15/pjs/
    [3] http://www.2ality.com/2011/10/javascript-overview.html

  • http://www.grobmeier.de Christian Grobmeier

    Actually you can compile Dart to JavaScript too, like you do with CoffeeScript. There are two compilers out there: DartC (which is deprecated more or less) has got some glory with compiling “Hello World” to a few MBs of JavaScript. But the new compiler “Frog” is pretty cool and creates great JS. If you are interested, then please read this post, where Seth Ladd wrote up his experiences when he ported a JavaScript game to Dart and compiled it for all Browsers using Frog: http://blog.sethladd.com/2011/12/10-lessons-from-porting-javascript-to.html

  • http://www.grobmeier.de Christian Grobmeier

    JavaScript is still good but not perfect. Of course it will develop with ECMAScript, as you said. But it will never be perfect, and well, what about all the projects when it comes to backward compatibility?

    Right, I missed “this”. This drove me nuts for a good while!

    To your comments (and thanks letting me know so much on ECMAScript 6 – which I will not wait for, actually).

    To 6) The problem is, I need to know the pattern. In my world I should be able to program clean and safe without knowing such kind of patterns.

    To 8) It seems I missed this or confused something. I was sure foreach on objects at least is not recommended by Douglas Crockford. I have this book no longer at hand so I cannot look at verify.

    To 9) Again, a rule. You are right, if you know all the rules, JavaScript is easy.

    To 10) Treat them as the same, as long as the undefined value is not overridden. Which is very unlikely, I admit.

    To your JavaScript > Dart arguments (I need to comment :-) ):

    1) Dart is available on the server without any pain. I have even started to work on some server side stuff here: https://github.com/grobmeier/hydart . This project will listen (someday, when I have time) to a port and respond to it. In a post from Dartwatch: http://www.dartwatch.com/index.php/2011/11/exploring-dart-client-server-written-in-dart/ Chris Buckett demonstrates how one can write both, server and client in Dart. Actually I expect Dart being on Google AppEngine pretty soon.

    2) Dart is unfinished, this is true. But it also has a clear Language Spec: http://www.dartlang.org/docs/spec/index.html In addition, I know from experience how open Google developers are to suggestions from other Dart lovers (see mailinglist). I cannot agree to “Dart is hard to read”. For me Dart reads ways easier than JavaScript (I come from a Java, PHP World). As you said, there are not many other vendors, but it is possible. Actually there is a guy already implementing Dart for the JVM: http://code.google.com/p/jdart/ I have no doubt there will be other vendors/projects doing similar stuff in near future.

    3) (including your “Open Mind” argument): Yes, thats what I am saying. Coming from the mainstream world (f. e. Java) you’ll easily find into Dart (pretty similar syntax). But you need a very open mind for JavaScript. I have learned it, but it took me a good while to refactor my thinking. Meanwhile I have done some pretty cool stuff in JS – but still I am afraid I miss some of the rules you simply need to learn when doing JavaScript.

    With my post I didn’t want to say JavaScript is going away. My point was: if you are coming from Java and need to do some browser work you are probably better learning Dart.

  • http://www.openswimsoftware.com Corbin Uselton

    Very interesting did not know there was a compiler for dart as well though this is obviously not the main way it is intended to be implemented.

    I found it interesting how you said you liked it coming from Java as I find coffeescript very python like(so polar opposite) will definaly try it out though :-)

    Am always interested in new ways to spend less effort programming

  • http://www.grobmeier.de Christian Grobmeier

    hehe actually in the time before Dart arrived I was looking to CoffeeScript too, but was not very happy because it is so Python like. Python is a language I have really absolutely no clue of. I surprised myself that I like Ruby, even when it looks pretty Pythonesque too. Anyway, with Dart I was sometimes missing some Pythonskills, because many of the Google Tools are written in Python. For example, testcases for the Dart core are executed by Python (or so). Probably this is the way into Dart for you?

  • http://rauschma.de Axel Rauschmayer

    @Christian Grobmeier: “I cannot agree to ‘Dart is hard to read’.” – I meant that the Dart spec is hard to read. Dart itself is fine, especially if you are familiar with Java.

  • http://www.openswimsoftware.com Corbin Uselton

    No not at all I’m actually a Software Eng. major so achitecture is actually more up my alley then hard core coding.

    That interesting that they would model dart after java and then do the testing in python.

    I would definaly recommend playing with python a little as I feel if one knows Java, C and Python they can pretty much pick up any language :-)

    Most of why I have been playing with it is for a CMS im building in PHP so liked that there is actually a coffeescript compiler written in PHP

  • Rodrigo Moraes

    I agree that the Dart spec is hard to read. Too technical and probably it must be like that for VM/compiler implementers.

    The lack of examples makes it a a bit hard to decipher when you just want to learn the language.

  • Rodrigo Moraes

    “Dart itself is fine, especially if you are familiar with Java.”

    Or AS3, or C#, or JavaScript, or…

    Thinking about these languages, one thing I’d add to this list is that Dart has quite sophisticated constructors:

    - Instead of constructor overloading as in C# or Java, it has factory constructors.

    - It supports constant constructors to define compile-time objects.

    - Constructors support automatic value assignment of class properties right in the parameters.

    - Constructors support initializers to setup all final fields before they are seen with a null value: you can’t refer to a final field of an object that isn’t initialized.

  • http://www.itoctopus.com itoctopus

    Dart looks more or less like a hybrid between C and LISP, which is a programmer’s idea of an ideal programming language.

    Quick question: Do all browsers understand Dart?

  • http://www.grobmeier.de Christian Grobmeier

    @itoctopus: at the moment you have only the chance to transcompile Dart into JavaScript. Then there is Dartium (Chrome based Browser) which can execute native Dart: https://groups.google.com/a/dartlang.org/group/misc/browse_thread/thread/6d8c441b2a1288f7

  • http://www.grobmeier.de Christian Grobmeier

    @Axel Rauschmayer: oh yes, I agree. The spec is pretty heavy stuff. If you ask me they have looked a bit too long at the Java Language Specification :-) http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html

  • http://www.grobmeier.de Christian Grobmeier

    @COrbin I am an idiot with C honestly. :-) I have compiled some python stuff before a couple of days and it felt like that. Anyway, you are right, I need to look into it and will do so – probably this year.

  • http://twitter.com/rwaldron Rick Waldron

    Aside from all of errors and incorrect information in this article, my favorite part is that Dart _requires_ JavaScript to exist.

  • http://www.grobmeier.de Christian Grobmeier

    Dart can be executed this way:

    • Dart generates JavaScript via DartC/Frog
    • Dart runs native in the browser (does not require JavaScript), as can be seen on Dartium
    • Dart runs on the server side (does not require JavaScript)

    In other terms, Dart does not necessary require JavaScript. But if you want to use it with todays standard browsers, you need to generate JavaScript of course.

    By the way it seems (I cannot confirm at the moment) the Dart code can work hand in hand with JavaScript code.

  • Pingback: 10 razones por las que Dart mola mas que Javascript | Dart Experience

  • Pingback: My Weekly digest of links and articles - Peter's blog

  • Luis Gonzalez

    Whatever language comes up as the winner, the future looks bright. The days were only a crappy and slow language (javascipt) was available for client side programming are gone. Today, JavaScript has gotten fast and efficient. All its wharts have been ironed out by Coffeescript, which is delightful pythonesque syntactic abstraction layer over JavaScript. Moreover, Coffeescript has shown us that anyone can create a transpiler targeting js, porting their own programming niceties to the browser (just like Dart is doing, in addition to it’s own vm).
    Today I’m all warm and fussy about Coffeescript, which is a pleasure to work with (specially when mixed with jQuery).
    However, Dart looks good and it’s coming to the rescue of the web.
    Its syntax may be boring and unexciting, granted, but it is conventional enough to be understood a quicklypicked up by mainstream programmers. And it aims to be an efficient platform for tomorrows web (and an excellent compilation target for Coffeescript-like alternatives).
    Think about it: if you were looking to bet the farm to create the next big Internet company, the next facebook, and you had to choose a language for your development team, a language that will create you growing code base on the server, on the client, everywhere… Would it be JavaScript???
    Facebook chose php and their are still crying…

  • https://www.youtube.com/user/jambrizgdl Jesus Ambriz Meza

    A tutorial in spanish for Dart:
    https://www.youtube.com/watch?v=NNVbEBN0Q0U

    A tutorial in spanish for JS:
    https://www.youtube.com/watch?v=S09crIEeDPA

    make your own conclusions!

  • http://cawoodm.wordpress.com/ Marc

    JavaScript has it’s weaknesses but they are not insurmountable. The 2 biggest ones can be overcome with a live linter (e.g. Scripted), a live tester (e.g. Testem) and “option strict”.

    Übrigens: “consequent” (auf Deutsch) heisst “consistent” (in Englisch) während “consequent” gar kein Wort ist. Es ist verwirrend weil “consequence” sowas wie Resultat oder Ergebniss bedeutet ;-)

  • grobmeier

    There are always workarounds. JavaScript has its benefits too: some patterns from the class-less worlds are really great. But it is (in my opinion) not developed fast enough from ECMA and has a lot of historic issues. Dart benefits of being a new language. When you start from scratch you can always learn from what is already there. And so Dart has become a language which I find really exciting.

    Vielen Dank für deine Korrektur! Ich hab’s schon verbessert und schreibs mir jetzt auch hinter die Ohren :-)

  • grobmeier

    And by the way, great links. Didn’t know Scripted and Testem

  • Pingback: Darting Pub | Darting pub

  • http://profiles.google.com/ross9885 Daniel Ross

    Javascript and it’s replacements (altjs anyone?) make me miss Python, and I especially miss the STL from C++. I am disappointed to see that in Dart, hash keys must be strings, and there is no Set object. When I try to implement a Set, I end up needing to extend, wrap or add a dangerously named id parameter to everything I put in the set, so that I can store it in an Object as a key: value pair. Very awkward. And no, I can’t / shouldn’t always just use strings as keys and use arrays and indexOf as sets. Rant aside, I am pretty stoked about dart, and I will try using it for a web game. Javascript works, but I’ve had better :)

  • grobmeier

    Have you tried to discuss this on Darts mailing list? Maybe you’ll get your suggestion done as Dart folks currently rework all the libraries. If I were you, I would give it a try and see what they say.

  • Andrew Smith

    http://api.dartlang.org/docs/releases/latest/dart_core/Set.html

    But maybe I am misunderstanding. If so, I apologise. I am very new to Dart.

  • garcia_IS_shill

    This article reeks of hype and ignorance if you’d dug into NodeJS not Javascript. Though to be fair Node’s core is implemented in C++ but its run time language does many of these things already making it a good contender to promote JavaScript rather than obsolete it.

  • grobmeier

    Node.js as framework doesn’t fix the problems of the language. This article focuses on the language alone. JS is still very useful, I use it a lot myself. Having something like Angular.js makes it much easier (and fun) to use. Still, the flaws of the language is there. And thats why I think Dart is cool. Please don’t make it a religious debate.

  • http://profiles.google.com/ross9885 Daniel Ross

    https://groups.google.com/a/dartlang.org/forum/?fromgroups=#!topic/misc/fuqZwjdXPg8
    http://code.google.com/p/dart/issues/detail?id=4207

    Now I am really confused. I suppose this will all become clear when I actually start using Dart, but for now I am sticking with JS so that I can easily share requirejs modules between a Node server and the client. Sorry for the delay, I missed the Disqus notification.

  • Orochi

    Javacript’ maintenance is a headache because of its weird structure.
    Dart is simpler because the code can be class based.

  • http://twitter.com/CamiloSanchez46 Camilo Sanchez

    I am so glad Google is doing this. it really does take a long time to master JS, and yes, the ones with PhD’s in the room will certainly defend it because many love javascript. But it is not me saying it, is Google saying that there is something wrong with Javascript, we don’t know exactly what it is that is wrong with it, but we feel it, we felt it our entire developing life, we can feel it when we try to debug, when we try to loop, when we deal with closures.

    It’s time for supersede it and I for one join the Google cause, may God bless Google and its subsidiaries.

  • http://xenomuta.com/ XenoMuta

    I used to complain a lot about Javascript, but the Good Parts (thanks mr. Douglas Crockford) made enough counterweight for me to stay with it.