Semantics Matter, 4 Examples in Dart

We recently re-launched the Dart Synonym app, which provides mappings between common Dart/JavaScript/C# patterns, idioms, and snippets. If you know how to build a loop or create a function in JavaScript, this is a great way to learn how to do the same thing in Dart.

A great comment on G+, in response to the re-launch, was "I think Microsoft may have a better idea with TypeScript, which adds a syntax for declaring variable types that should make JavasScript more robust, but it still runs on top of JavaScript, cross browser."

While the Dart team welcomes TypeScript to the neighborhood, in the end TypeScript is "just JavaScript". It's great that TypeScript fosters better tooling and bigger web apps, but the same warts of JavaScript are still there with TypeScript. One of the main distinctions between Dart and TypeScript is that Dart cleans up the semantics and not just the syntax.

Don't get me wrong, syntax is important, and Dart offers familiar and easy to use syntax. Here's an example of assigning a function to a variable.


// Dart. A one-line function assigned to a variable.
var loudify = (msg) => msg.toUpperCase();


While aesthetics and syntax matter, semantics arguably matter more. Here are four examples of how Dart offers easier to understand semantics.



Index out of bounds


Consider accessing an array index that is out of bounds:

// Dart or JavaScript
var foo = ['a', 'b'];
foo[3];


In Dart, you'll get a RangeError exception. No doubts what happened there. :)

Method does not exist

What happens when you call a method that doesn't exist on an object?

In Dart, noSuchMethod() is called on your object, which means you have a chance to handle the method call. That kind of dynamism is great for frameworks and scripts.

Is a variable a string?

How do you tell if a variable is a string? In Dart, you can simply do:

obj is String

Closures in a for loop

What happens to variables closed around inside a for loop? In Dart, a new i variable is created for each loop iteration. This leads to expected behavior:


// Dart
var callbacks = [];
for (var i = 0; i < 2; i++) {
  callbacks.add(() => print(i));
}

callbacks[0]() // == 0


Summary

Syntax matters, but what the language does matters more. Dart offers semantics that are more obvious, logical, and straight forward. Above all, all that really matters is that you're building awesome HTML5 apps for the modern web. Language doesn't matter, the web matters.

Popular posts from this blog

Lists and arrays in Dart

Converting Array to List in Scala

Null-aware operators in Dart