Writing Compressible JavaScript

June 19, 2010 by Ed Spencer · 8 Comments 

Writing a library is a balancing act between the (sometimes competing) interests of API clarity, code clarity, performance and compressibility. In this article I’m going to detail three of the approaches we take to meet this balance and suggest them for your own usage.

1. Collecting var statements

Every time we declare variables we add 4 bytes to the compressed file size. Variables are declared sufficiently often that this can really add up, so instead of this:

var myFirstVar = 'something';
var myOtherVar = 'another thing';
var answer = 42;
var adama = true;

One should use this form:

var myFirstVar = 'something',
    myOtherVar = 'another thing',
    answer = 42,
    adama = true;

When this code is compressed, each variable name above is turned into a single-letter name, meaning that the wasted 4 bytes per useless additional ‘var ‘ in the first example would have contributed significantly to code size with no benefit.

2. Local variable pointers to object properties

The following code (pruned from a previous version of Ext JS) is not as compressible as it could be:

var cs = {};
for (var n in this.modified) {
    if (this.modified.hasOwnProperty(n)) {
        cs[n] = this.data[n];
    }
}
return cs;

We’re better off aliasing ‘this.modified’ to a local variable first. Aside from the performance benefits some JS engines derive from not having to perform object property lookups over and over again, we save precious bytes this way too:

var modified = this.modified,
    changes  = {},
    field; 

for (field in modified) {
    if (modified.hasOwnProperty(field)) {
        changes[field] = this.data[field];
    }
}

return changes;

Again, the minifier will compress those variable names down to a single character each, so for our ‘this.modified’ example we’re going to use 15 bytes to define the variable plus 1 byte each time we use it (totalling 15), vs the 26 bytes for that code previously. This approach scales especially well – were we to refer to this.modified a third time in the function, as our code will now minify to 16 bytes, vs 39 without the variable declaration.

Side note: in the first example here the variable ‘n’ was being used in the for…in loop. We can always safely exchange that for a meaningful variable name (in this case ‘field’) and leave the rest to the minifier.

3. Aliasing ‘this’ to ‘me’

In Ext.data.Record’s markDirty method we have the following code:

this.dirty = true;
if(!this.modified){
    this.modified = {};
}
this.fields.each(function(f) {
    this.modified[f.name] = this.data[f.name];
},this);

There are 7 references to ‘this’ in that method, taking 28 bytes and completely incompressible. We could rewrite it like this (note that the final ‘this’ can be removed in this format):

var me = this; 

me.dirty = true;
if (!me.modified) {
    me.modified = {};
}
me.fields.each(function(f) {
    me.modified[f.name] = me.data[f.name];
});

Again, our minifier will change the ‘me’ var to a single character, saving us 8 bytes in this instance. That might not sound like a lot but after minification it equates to a 7% reduction in code size for this function.

In each of the cases above we’re generally talking about single-digit percentage savings after minification. There is value in that small slice though, especially as more and more applications shift onto bandwidth-constrained mobile platforms.

The first two approaches are no-brainers and must always be done but the third is slightly more controversial. Personally I find it makes the code a little harder to read, largely because my syntax highlighter doesn’t recognise that ‘me’ is now the same as ‘this’. Its value also varies significantly by function – some functions can contain over a dozen references to ‘this’, in which case this approach makes a big difference.

Answering Nicholas Zakas’ JavaScript quiz

February 16, 2010 by Ed Spencer · Leave a Comment 

A current meme that’s floating around the JavaScript geek corner of the internet is setting quizzes on some of the more unusual aspects of JavaScript. This time round Nicholas Zakas is providing the entertainment, so I thought I’d provide some answers. Let’s get started:

Question 1

Question 1 looks like this:

var num1 = 5,
    num2 = 10,
    result = num1+++num2;

We’re asked what the values of result, num2 and num1 are. First, let’s deconstruct what that +++ is doing. There is no +++ operator in JavaScript – instead we have a num1++ followed by a + num2.

JavaScript has two ways of incrementing a number by 1 – we can either put the ++ before the variable or after it. The variable is incremented either way – the only difference is what is returned. ++10 returns 11, whereas 10++ returns 10:

var a = 10;

var b = a++; //a is set to 11 now, but b is set to 10
var c = ++a; //a is set to 12 now, c is also set to 12

So ‘result’ is the sum of num1++ (which is 5) and num2, which is 10, so result equals 15. num2 remains at 10 as it was not modified. num1 is now equal to 6 because we incremented it by 1, though the incrementation did not affect the sum passed to result.

Question 2

var x = 5,
    o = {
        x: 10,
        doIt: function doIt(){
            var x = 20;
            setTimeout(function(){
                alert(this.x);
            }, 10);
        }
    };
o.doIt();

We’re asked what is alerted. This is mostly smoke and mirrors – there’s some indirection with all the duplicate names but the important thing here is the setTimeout. The function we pass to setTimeout gets run in the global scope, meaning ‘this’ refers to the window object. Declaring x as a variable in the global scope (var x = 5) is the same as setting window.x = 5, so 5 is alerted.

Question 3

var num1 = "10",
    num2 = "9";

We’re asked:

  • What is the value of num1 < num2?
  • What is the value of +num1 < num2?
  • What is the value of num1 + num2?
  • What is the value of +num1 + num2?

This question is all about type casting.

  • num1 < num2 is true - if both operands are strings JavaScript will compare them alphabetically, and "10" is lower alphabetically than "9"
  • +num1 < num2 is false - placing a "+" operator before a string casts it into a number, so we're actually testing 10 < "9". When testing a mixture of numbers and strings like this, everything is cast into a number, so we're testing 10 < 9, which is false
  • num1 + num2 === “109″ – the plus sign can mean both addition and concatenation, depending on the operand types. Here we have 2 strings so we’re concatenating them together
  • +num1 + num2 === “109″ also – again we’re casting num1 into a number, but the + operator means concatenation if at least one operand is a string

The confusion around this comes largely from the fact that the plus sign is used for both addition and concatenation in JavaScript. This causes the engine to have to test the typeof each operand and cast accordingly. All of the other math operators (e.g. /, *, % etc) cast both operands to numbers.

Question 4

var message = "Hello world!";

We’re asked:

  • What is the value of message.substring(1, 4)?
  • What is the value of message.substr(1,4)?
    • substring and substr do similar things. The first argument to each is the character index to start from, but whereas substring’s second argument is the character index to end at, substr’s second argument is the number of characters to return. Therefore message.substr(1, 4) will return a string of length 4, whereas message.substring(1, 4) will return a string of length 3 (4 – 1):

      • message.substring(1, 4); //”ell”
      • message.substr(1, 4); //”ello”

      Question 5

      var o = {
              x: 8,
      
              valueOf: function(){
                  return this.x + 2;
              },
              toString: function(){
                  return this.x.toString();
              }
          },
          result = o < "9";
      alert(o);
      

      We’re asked the value of ‘result’, and what gets alerted. This requires an understanding of the special valueOf and toString functions available on every object. These functions are used internally by the JavaScript engine to pull out the best representation of an object’s value based on the situation.

      When alerting a value, we want a string representation so toString is called. When comparing the value to another object, valueOf is called instead. So alert(o) alerts “8″, and result is set equal to the result of 10 < "9". The JavaScript engine will decide when to use which option, or we can specify it ourselves:

      var num1 = 8, num2 = 9;
      
      num1 + num2; //17
      num1.toString() + num2.toString(); //"89"
      num1.valueOf() + num2.valueOf(); //17
      

      The 'result' assignment needs a little explanation. First, the engine calls valueOf on the object, which returns 10. Second, because one of the operands to the < operator is a number, the other is also cast into a number, so we are testing 10 < 9, which returns false. We could instead force it to use toString: o.toString() < "9" returns true.

      Quizzes like this are great for getting your teeth into some of the guts of JavaScript, but don't mistake them for a good way to write code. The point is to demonstrate how quirky JS code can be unless you write it in a sensible way.

Ext JS is looking for a QA rockstar

January 19, 2010 by Ed Spencer · Leave a Comment 

This has been cross-posted from our Open Discussion Forum.

As part of our ambition of creating the world’s best JavaScript framework, we’re looking to hire a special somebody to help maintain the high quality of our components.

While we have one eye on implementing new features and improving Ext JS’s performance, the other is on making sure what we already have still works well.

This is a difficult job and we need someone smart, focused and well versed in Ext JS. Somebody who will:

* Use our existing systems to test components as new builds of the library are landed
* Maintain a strong presence in the forums and be the first to know of any reported issues
* Respond to bug tickets such as rendering issues and broken functionality
* Totally own the Quality Assurance of Ext JS – we want your ideas and your initiative as well as your expertise with Ext
* Liaise with the core team on a daily basis

This is a full-time position, though allowances can be made for the right person. If you think you would enjoy working with Ext JS, and have what it takes to help us keep Ext at the forefront of our field, drop me a private message with the following information:

* Your name
* Email address
* Location (city, country, timezone)
* All experience with Ext JS
* Bonus points for links to open source software

JavaScript FizzBuzz in a tweet

September 17, 2009 by Ed Spencer · 17 Comments 

The FizzBuzz challenge has been around a while but I stumbled across it again after reading another unique Giles Bowkett post.

If you’re not familiar with FizzBuzz, it’s a little ‘challenge’ designed to test a candidate programmer’s ability to perform a simple task. In this case, you just have to print out the numbers from 1 to 100, unless the number is a multiple of 3, when you should instead print “Fizz”, 5 in which case you print “Buzz”, or both 3 and 5 in which case you print “FizzBuzz”.

Here’s a trivial JavaScript implementation:

for (var i=1; i <= 100; i++) {
  if (i % 3 == 0) {
    if (i % 5 == 0) {
      console.log('FizzBuzz');
    } else {
     console.log('Fizz');
   }
  } else if (i % 5 == 0) {
    console.log('Buzz');
  } else {
    console.log(i);
  }
};

Pretty simple stuff, but a bit verbose. I wanted something that would fit into a tweet. It turns out that’s pretty simple – this is 133 characters including whitespace, 7 within tolerance for a twitter message:

for (var i = 1; i <= 100; i++) {
  var f = i % 3 == 0, b = i % 5 == 0;
  console.log(f ? b ? "FizzBuzz" : "Fizz" : b ? "Buzz" : i);
}

Which of course begs the question – just how short can a JavaScript FizzBuzz implementation be? Here’s my baseline, which is a tortured and contorted version of the above:

for(i=1;i<101;i++){console.log(i%3?i%5?i:"Buzz":i%5?"Fizz":"FizzBuzz")}

The above is 71 characters – I expect you to do better. The rules are that the only dependency is Firebug’s console.log being available, and you can’t replace ‘console.log’ for anything else.

Of course, if we did swap ‘console.log’ for ‘alert’, the whole thing would fit in a tweet twice, but that would be damn annoying.

Hint: you can take at least three more characters off the above – can you see how?

Using the ExtJS Row Editor

September 16, 2009 by Ed Spencer · 14 Comments 

The RowEditor plugin was recently added to the ExtJS examples page. It works a lot like a normal Grid Editor, except you can edit several fields on a given row at once before saving.

This neatly solves the problem of adding a new row to an editor grid, entering data into the first field and finding it save itself straight away, which is rarely desired. In this fashion we can provide full CRUD for simple models in a single page.

Installation

You’ll need to get a copy of the javascript, css and images from the server. This is a bit of a pain. If you still have the ExtJS SDK around you can find these in the examples folder, if not you can get each file as follows:

Grab the plugin JS file below and put it where you usually put your .js files:
http://www.extjs.com/deploy/dev/examples/ux/RowEditor.js

This needs to go with your other stylesheets, usually in a directory called ‘css’:
http://www.extjs.com/deploy/dev/examples/ux/css/RowEditor.css

Download these two images and put them into your existing ‘images’ folder (the same place the other ExtJS images live):
http://www.extjs.com/deploy/dev/examples/ux/images/row-editor-bg.gif
http://www.extjs.com/deploy/dev/examples/ux/images/row-editor-btns.gif

Include the .js and .css files on your page and you should be ready to go.

Usage

RowEditor is a normal grid plugin, so you’ll need to instantiate it and add to your grid’s ‘plugins’ property. You also need to define what type of Editor is available (if any) on each column:

var editor = new Ext.ux.grid.RowEditor();

var grid = new Ext.grid.GridPanel({
  plugins: [editor],
  columns: [
    {
      header   : 'User Name',
      dataIndex: 'name',
      editor   : new Ext.form.TextField()
    },
    {
      header   : 'Email',
      dataIndex: 'email',
      editor   : new Ext.form.TextField()
    }
  ]
  ... the rest of your grid config here
});

RowEditor defines a few events, the most useful one being ‘afteredit’. Its signature looks like this:

/**
 * @event afteredit
 * Fired after a row is edited and passes validation.  This event is fired
 * after the store's update event is fired with this edit.
 * @param {Ext.ux.grid.RowEditor} roweditor This object
 * @param {Object} changes Object with changes made to the record.
 * @param {Ext.data.Record} r The Record that was edited.
 * @param {Number} rowIndex The rowIndex of the row just edited
 */
'afteredit'

All you need to do is listen to that event on your RowEditor and save your model object appropriately. First though, we’ll define the Ext.data.Record that we’re using in this grid’s store:

var User = Ext.data.Record.create([
  {name: 'user_id', type: 'int'},
  {name: 'name',    type: 'string'},
  {name: 'email',   type: 'string'}
]);

And now the afteredit listener itself

editor.on({
  scope: this,
  afteredit: function(roweditor, changes, record, rowIndex) {
    //your save logic here - might look something like this:
    Ext.Ajax.request({
      url   : record.phantom ? '/users' : '/users/' + record.get('user_id'),
      method: record.phantom ? 'POST'   : 'PUT',
      params: changes,
      success: function() {
        //post-processing here - this might include reloading the grid if there are calculated fields
      }
    });
  }
});

The code above simply takes the changes object (which is just key: value object with all the changed fields) and issues a request to your server backend. ‘record.phantom’ returns true if this record does not yet exist on the server – we use this information above to specify whether we’re POSTing to /users or PUTing to /users/123, in line with normal RESTful practices.

Adding a new record

The example above allows for editing an existing record, but how do we add a new one? Like this:

var grid = new Ext.grid.GridPanel({
  //... the same config from above goes here,
  tbar: [
    {
      text   : "Add User",
      handler: function() {
        //make a new empty User and stop any current editing
        var newUser = new User({});
        rowEditor.stopEditing();

        //add our new record as the first row, select it
        grid.store.insert(0, newUser);
        grid.getView().refresh();
        grid.getSelectionModel().selectRow(0);

        //start editing our new User
        rowEditor.startEditing(0);
      }
    }
  ]
});

Pretty simple stuff – we’ve just added a toolbar with a button which, when clicked, creates a new User record, inserts it at the top of the grid and focusses the RowEditor on it.

Configuration Options

Although not documented, the plugin has a few configuration options:

var editor = new Ext.ux.grid.RowEditor({
  saveText  : "My Save Button Text",
  cancelText: "My Cancel Button Text",
  clicksToEdit: 1, //this changes from the default double-click activation to single click activation
  errorSummary: false //disables display of validation messages if the row is invalid
});

If you want to customise other elements of the RowEditor you probably can, but you’ll need to take a look at the source (it’s not scary).

Final Thought

RowEditor is a really nice component which can provide an intuitive interface and save you writing a lot of CRUD code. It is best employed on grids with only a few columns – for models with lots of data fields you’re better off with a full FormPanel.

I’d be pretty happy to see this included in the default ExtJS distribution, as I find myself returning to it frequently.

Next Page »