Simon Online

2013-05-03

Strictly JavaScript

ECMAScript or JavaScript as it is more commonly known has gone through a number of large iterations over the years. The version currently under development is known as ECMAScript 6 or Harmony, which is an awesome code name. However most JavaScript we see around is actually ECMAScript 3. ECMAScript 4 was a failedendeavour but ECMAScript 5 brings a great new feature which we, as developers, should be exploiting: Strict Mode.

Back in the day Visual Basic had a feature called Option Explicit which was recommended. It required that you actually declare all your variables. Adding a simple command to your JavaScript enables strict mode for the whole file

“use strict”;

What does this strict mode do? A bunch of great things. The first is that it does the same thing as Option Explicit in VB: it requires that all your variables be explicitly defined using var. Without strict code such as

monkey = “salmon”

will attach a monkey property to the global object, in most cases window. This is a dangerous behaviour as it allows information to leak from one function to another. Strict will catch that and throw an error. Instead you need to do

var monkey = “salmon”

This alone should be enough reason to use strict mode. But there is more! Way more.

Duplicate property assignment is detected and prevented so you will know right away if you do

var shoe = { size: 7, size: 9}

you’re also prevented from putting in duplicate parameters into a function declaration

function climbTree(treeName, height, treeName) { }

Finally strict mode restricts the use of the eval key-word. You can no longer use it as a parameter or as the name of a function or even as a variable. It also prevents variable assignment from inside an eval context so you can no longer do

eval(“importantOuterVariable = ‘delete everything’;”);

Although I found that variable assignment from eval was still permitted in chrome.

Adding strict to any JavaScript is likely to catch errors before they become bugs in the real world. I think it is highly advisable and so easy to do. So why don’t you get a little stricter with your JavaScript?

2013-05-02

What I learned from Azure Bootcamp

Over the weekend I helped run a day long Azure camp. We had about 40 people come out and learn a bunch of stuff about Azure. The day was set up as a code camp with us having presentations every hour or so and then working time during which we circulated and attempted to help people out. Based on the feedback and my own observations I wanted to jot down some suggestions for the next time we put on such an event.

  1. Name tags. It would be great to give people name tags so that when I’m walking around I don’t keep having to ask what their names are and they don’t have to keep asking about mine.

  2. Electronic method of asking questions during the presentation. We were in a big room and it would have been good for people to be able to tweet questions instead of raising hands and the such. Frequently people are worried aboutinterruptingthe flow of thepresentationso this side channel would be great.

  3. Less complete demo. We built a fully functional azure driven website and let people download it to play with it. Next time we should branch the website just before we give people the download link and remove key parts of the functionality. They would still be available in a branch should people get stuck but they wouldn’t be obvious. As it stood people went to implement things and found them already to be in place and nothing for them to do.

  4. Challenge problems. One of the most popular comments was that things were going too slow. At the same time there were some people who were struggling to keep up. I can totally understand that. The camp catered for people at all sorts of skill levels so there were bound to be differences in how long it took people to get a task done. We should have put instretch goals or challenge problems for the faster moving. It would also give people something to work on when they get home, should they wish.

  5. Status board. With 30+ people plugging away at stuff it is hard to say who is ready to move on and who is still working. We could have set up a site on which users could check off their progress so we could see if we were ready to move on. This would allow us to be more dynamic with when sessions start and finish.

  6. Microphones and better projectors. Our room was huge, too big as it turns out. People at the back had trouble hearing and seeing the projector. The obvious solution is to move forward but we should have been proactive at the same time and moved people or invested in some microphones.

  7. Something for people who don’t have the tools. As always people end up at the camp without the right tools installed. From time to time they can’t install the tools because they’re using their company’s laptop. All the tools for this camp were free so we could easily have set up some VMs on the cloud to let people do development with remote desktop. There would have been a cost but for 10 users for 8 hours on a large instance at Azure the cost would have been $26. I think we could have stretched to that, the only question is “would our bandwidth have stretched?”

I think the whole camp went really well and I’m excited about doing another one at some point in the future.

2013-05-01

Dart Part 4 - DOM Changes

It is tough when looking at Dart to remember that compiling Dart to JavaScript isn’t the end game of Dart. This is a much bigger project than CoffeeScript or TypeScript which just aim to make writing JavaScript less painful. Dart is on a quest tocompletelychange how web browser scripting is done. So when I compare dart:html to Sizzle it is a false analogy. Sizzle is written in JavaScript and talk to the browser through a set of APIs which have grown up over the last decade or so.

dart

The assertion of the Dart folks over at Google is that the API which has grown organically is inconsistent and unmaintainable. Based on some of their examples I can’t really disagree. Let’s take a look at a couple of them.

Say you want to query for some information out of the DOM. There is a rich JavaScript API for that. Why you just need to pick one of these methods

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

That’s pretty clear. In Dart your choices are

query() queryAll()

That’s it. All the power of selecting items is still there but it now hidden in the parameters passed to these two functions. The parameters are written in the same DSL as CSS so it is something that web developers already know. Vendor prefixes are another big issue in modern development. When browser vendors create newfunctionalitythey hide it behind a vendor prefix until it is ready for general consumption. It’s not a big deal if you’re on a rapidly updating browser like FireFox or Chrome but if you’re on IE with yearly release cycles the it is tedious to deal with.

If you want to get access to the camera from a browser in JavaScript you’re going to do

navigator.getMedia = ( navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);

Dart abstracts away all those silly vendor prefixes and give you

window.navigator.getUserMedia(audio:true, video: true)

Way nicer! You can still have all the nice syntactic sugar of jQuery but now jQuery itself can be much smaller and easier to maintain because it doesn’t have to smooth out the weirdbehaviorsbetween browsers.

We need this. I don’t know if Dart is the solution but we need a clean break from maintaining the garbage which is the interface between JavaScript and the browser DOM. I’m glad that somebody is at least making an effort.

2013-04-30

Dart Part 3 - Libraries

Unlike CoffeeScript and TypeScript Dart is not really meant to be compiled to JavaScript. You certainly can compile it to JavaScript but the long term goal of the language is to replace JavaScript. That’s a goal which is at least a decade out. Truth be told I don’t see Dart ever replacing JavaScript wholesale. Selling Dart to Microsoft and to Mozilla is going to be quite a thing when there is already such acceptance of JavaScript. JavaScript hangs around rank 9-11 in the language ranking while Dart is not even in the top 50. That’s not to say that Dart isn’t a fantastic language it is just new and facing a pretty entrenched competitor.

So being a full replacement for JavaScript Dart must also fulfill the role of many of the fantastic libraries which have become commonplace in the land of JavaScript. Dart includes a number of libraries for manipulating html, performing asynchronous actions, running mathematical operations and even fir file I/O. These library create a sort of base class library the same as what you get with Java and .net. Obviously they are too large to cover in a single post. I thought I might talk a bit about dart:html which is the library designed for manipulating and queryingHTML.

The first thing in the html library is a sizzle like selector engine which works on CSS3 selectors. It is easily usable via the query and queryAll functions. Query returns an Element and queryAll returns a list of elements. These elements can be manipulated just as you would in JavaScript. For instance this code will add a colour a couple of divs

On the trivial html test page I put together the result was

Coloured boxes thanks to dartColoured boxes thanks to dart

Exciting!

If you look back at part 1 of this series I mentioned that there was some concert over the amount of crud which was created by Dart during a normal compile. To make these boxes dart2js generated 1891 lines of code. Humm”¦ that seems excessive. But it isn’t really a fair comparison is it? I included dart:html which is likely huge as it contains a bunch of the functionality of jQuery. If you read the Dart documentation it suggests that Dart will actually trim out functions which are not used. There is also a ““minify flag which can be passed to the dart2js compiler. Using the minify option the library is shrunk way down and the results are in line with other selector libraries.

LibrarySize when Minified
Sizzle17KB
jQuery32KB
dart:html25KB
It is difficult to say if comparing dart:html to Sizzle or jQuery is more accurate. There is more that just a selector engine in there but there is also less that full blown jQuery. There is some interesting stuff built into dart:html and its companion libraries. With dart:uri and dart:async we pick up support for web sockets as well as Ajax. I don’t feel like the syntax is all there yet but it does have the advantage of being built into the language. Well built into the base libraries. Most times developers are more likely to use the built in libraries instead of finding third-party libraries so there is probably more consistency moving from one Dart project to another than moving from one JavaScript project to another. The libraries aren’t terrible but they aren’t fantastic either.

“Not terrible but not fantastic” pretty much sums up my feelings about Dart in general.

2013-04-29

Dart Part 2 - Classes

Classes are a common structure in many programming languages. They are used to arrange code into logically related groupings. In object oriented programming the idea is that each class represents a thing. This thing may be a real world object like a Book or a thing which operates on a book like a BookSorter. Much like the other languages at which we’ve looked Dart has support for classes and also for full inheritance.

Here you can see Book has a descendant class TextBook which adds the additional edition field. Just like CoffeeScript and TypeScript there is syntactic sugar to allow for setting of public properties from the constructor. In this case the “this” keyword us used to denote what should be set. Interestingly on line 18 we have access to the edition information even though the instance was created as a Book and not a TextBook. This would not be possible with a language like C# or Java.

Dart has an interesting feature which is a built in factory method. Factories can be used to construct objects in a non-initialized way. Basically it is a way of overriding construction. Honestly it is a useful pattern but it isn’t one which I use so frequently that I feel the need to have my language support it. But perhaps you’re different.

In this example I retrieve the book from HTML5 local storage instead of creating a new book.

2013-04-26

Dart Part 1 - Another New Hope

In preparation for my upcoming talk about next generation JavaScript I’ve been looking atalternativesto writing pure JavaScript. Largely my discussion is predicated on the idea that JavaScript isn’t great for building large applications. As others have suggested JavaScript is the assembly language of the web. So far I’ve looked at TypeScript and CoffeeScirpt, today bring Dart into the mix.

Wraith Darts - sorry, Google, these are still coolerWraith Darts ““ sorry, Google, these are still cooler

Dart is a product of Google and having been announced in October of 2011 it is fairly mature. When it first came out the compiler for it was terrible and produced the most verbose JavaScript imaginable. It was unfortunate because it was soundly mocked for being junk. I seem to remember that a hello world application compiled to over 1000 lines of JavaScript code. Things are greatly improved now and Google recently announced that the JavaScript emitted by the latest compiler, dart2js, runs faster than hand written JavaScript. That’s quite an achievement considering the crazy lengths to which browsers go to optimize JavaScript.

What’s interesting about Dart, which makes it different from the other two languages we’ve looked at, is that you can actually run dartnativelyon Chrome. There is no need to compile it to JavaScript first. Well no need assuming that everybody who uses your site runs a special build of Chromium. However, I hear that the new Blink rendering engine is going to include support for Dart so there may be a future for native Dart and that future could be very close.

This post’s goal is just to get started with the Dart development tools. Google provide a Dart editor which is based on Eclipse(ugh). So let’s ignore that for now and use the command line tools. Grabbing the install package fromhttp://www.dartlang.org/tools/gives us the editor and the SDK. Within the SDK are a number of tools but we’re interested in dart2js.

It can be run without any flags to produce both the compiled JavaScript and a map file. A real basic bit of Dart like this

prints

0 Hello 1 Hello 2 Hello 3 Hello

The code demonstrates some small part of Dart but nothing too exciting. We’ll get more into Dart in upcoming days.

2013-04-25

Slurp - Source Maps CoffeeScript Part 5

Today I would like to talk a bit about source maps. Back when the world was new and languages like TypeScript and CoffeeScript which transcompile to JavaScript were just poking their heads out of the primordial soup there was no way to trance an error in your JavaScript back to the line of code in the generating language. For simple programs this wasn’t a huge deal because you could squint a bit and figure it out. But as the languages became more powerful and programs more complicated the situation worsened.Fortunatelya hero arose in the form of source maps.

Source maps are about what you would expect: they are a way of translating from one representation of the source to another. In our case from JavaScript to the source language, CoffeeScript. These maps can be consumed by the browser and the output shown in the debugging consoles in Chrome and FireFox. As source maps are still a bit new you may need to enable them manually before you make use of them. In Chrome, my development browser, this can be done by hitting F12 the clicking on the little cog icon in the bottom right corner of the developer tools. Under sources there is a check box for Enable source maps

Enabling source mapsEnabling source maps

Next up is telling the CoffeeScript compiler to generate source maps too while it is compiling. That is just a question of including the -m flag

coffee -m -c test.coffee

You will now see that the compiler does two things. First it emits a .map file which is the mapping from JavaScript back to CoffeeScript. Next it adds the line

/ //@ sourceMappingURL=test.map /

To the bottom of the generated JavaScript file. That’s pretty much it now. I tested mine out with a little bit of mildly complicated CoffeeScript

This generates output which is pretty different from the input so source mapping is handy

In Chrome now I see not only the JavaScript but also the CoffeeScript when I jump into the source view. I’m able to set break points on the CoffeeScript and execution will actually stop there allowing me to debug CoffeeScript directly instead of guess at the source CoffeeScript line.

Breaking on CoffeeScriptBreaking on CoffeeScript

Pretty nifty! You can actually use source maps to map minified JavaScript too, you can even use multiple layers of maps to translate from minified JavaScript -> full JavaScript -> CoffeeScript. Not every minifier has support for this butUglifyJS certainly does.

2013-04-24

Slurp Deconstruction CoffeeScript Part 4

Welcome to part 4! This is the first part which is divisible by 2 but isn’t equal to 2. Of course that wouldn’t be true if I started my blog series at 0. Son of a gun ““ you just wait for the next series.

Deconstruction are one of my favorite features of CoffeeScript. Deconstructions allow for rapid assignment of variables or rapid remapping on complex objects. The simplest case is the old interview question of how to swap two variables.

This isn’t limited to only two items either, you can do anarbitrarynumber

Nifty but not all that useful, right? Not so fast my part 4 friend. Using this technique we can easily supportmultiplereturns from a function which is really the dream. Frequently you want to return complex data from a function but don’t want to waste time building a bunch of data transfer objects

Just. Like. That.

It can also be used to expand object like the options hash which is commonly passed in when building jQuery plugins.

See? That’s why part 4 is all about the fun of deconstructions.

2013-04-23

Slurp - Operators CoffeeScript Part 3

CoffeeScript brings a number of renamed and new operators to your JavaScript. The first one is our old friend ==. JavaScript has two equality operators == and ===. The difference is that == will not perform type conversion before performing the comparison. That has the result of allowing really strange things to be true

Fortunately CoffeeScript clears this weirdness up by masking JavaScript’s == and introducing its own == operator which compiles to ===.

Confused yet? It’s a lot of =s that’s to be sure. To maintain consistency with the conversational tone of CoffeeScript you can use English words in place of the standard operators. For instance that == can be written as is.

Taken from the CoffeeScript documentation

CoffeeScriptJavaScript
is===
isnt!==
not!
and&&
or||
true, yes, ontrue
false, no, offfalse
@, thisthis
ofin
inno JS equivalent
In addition to being able to use the operators as one would in JavaScript one can use nifty post statement branches.

The final goodie for today is the existential operator. It is represented using the ? symbol. It can be used to check to see if a value is null or undefined.

A more impressive use is in operator chaining

You can’t tell me that isn’t a far cleaner and easier to understand syntax.

2013-04-22

Slurp - Looping CoffeeScript Part 2

There are a couple of different approaches to looping in CoffeeScript. The designers of CoffeeScript felt that the majority of loops are really just iterating over a collection. Thus the majority your looping needs can be served using a for-each style loop. The syntax for doing so looks about how you would expect

Here we have a loop over the trees in theforest. Pretty easy. What if I really need to know the index of the element on which I was operating? Unlike for-each loops in many languages which assume that the index of and element in an enumeration in meaningless CoffeeScript offers a way out

By passing in a secondparameterto the for loop you can gain access to an element which contains the index. If you don’t have a collection but wish to execute some operation multiple times you can either use a for loop syntax on a range or use a while loop.

For loop with range:

While loop:

Perhaps the coolest feature of loops in CoffeeScript are that you can perform filtering on the elements as youiterateover them. If I only wanted to perform an action on my forest when the tree was birch then I can create an implicit if by doing

Now let’s say that the trees in the forest are a bit more complex that before and we wanted to filter on a property, that’s no problem:

Loops are much more powerful in CoffeeScript than in pure JavaScript. I think the syntax is also more readable.