﻿<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom"><title type="text">Nerdworks Blogorama - Nerdspeak</title><subtitle type="text">The nerd shall inherit the earth.</subtitle><updated>2011-11-24T04:09:03Z</updated><author><name>Ranju. V</name><uri>http://blogorama.nerdworks.in/</uri><email>avranju@gmail.com</email></author><icon>http://blogorama.nerdworks.in/images/nw_logo.png</icon><id>http://blogorama.nerdworks.in/</id><link href="http://blogorama.nerdworks.in/" rel="alternate" type="text/html" /><link href="http://blogorama.nerdworks.in/atom.ashx" rel="self" type="application/atom+xml" /><entry><title>IE9 web cast / Chennai Web Camps / OSI Days 2011</title><link href="http://blogorama.nerdworks.in/entry-IE9webcastChennaiWebCampsOSIDa.aspx" rel="alternate" type="text/html" /><id>http://blogorama.nerdworks.in/comment.aspx?entryID=68</id><updated>2011-11-24T04:09:03Z</updated><published>2011-11-24T04:06:30Z</published><content type="html">&lt;p&gt;It has been a somewhat hectic two weeks shuttling between Chennai and Bangalore for a bunch of stuff. As usual, I’ve been happily handing out promises about posting resources for my talks on my blog. Like candy. Turns out you’ve got to come good on them eventually. So here goes:&lt;/p&gt;  &lt;h3&gt;IE9 Web Cast on ECMAScript 5&lt;/h3&gt;  &lt;ol&gt;   &lt;li&gt;&lt;a href="https://2vqcza.bay.livefilestore.com/y1p5eeTX9Yctq964iB4Y6MjQ4VC1Bb1oC5mKQi6CsVMQWQAG8_DT4AUalzu876ge_2zQuERLsQRHDl0EP6H80k92Q/IE9%20and%20ECMAScript%205.pptx?download&amp;amp;psid=1" target="_blank"&gt;Get the deck&lt;/a&gt; (there isn’t much in the deck but there it is for what its worth).&lt;/li&gt;    &lt;li&gt;Get the &lt;a href="http://blogorama.nerdworks.in/entry-JavaScriptevalconsole.aspx" target="_blank"&gt;JavaScript eval console&lt;/a&gt; I was showing off in the session.&lt;/li&gt; &lt;/ol&gt;  &lt;h3&gt;Chennai Web Camps&lt;/h3&gt;  &lt;blockquote&gt;   &lt;p&gt;All the resources for the web camps sessions are available &lt;a href="http://blogorama.nerdworks.in/entry-WebCampsVirtualTechDaysandjsFo.aspx" target="_blank"&gt;here&lt;/a&gt;.&lt;/p&gt; &lt;/blockquote&gt;  &lt;h3&gt;OSI Days 2011&lt;/h3&gt;  &lt;ol&gt;   &lt;li&gt;Session on &lt;a href="http://2011.osidays.com/proposal/webmatrix-building-complete-website-within-hour" target="_blank"&gt;WebMatrix: Building a complete website within an hour&lt;/a&gt;       &lt;ul&gt;       &lt;li&gt;Get the &lt;a href="https://2vqcza.bay.livefilestore.com/y1pXD21izvPLpVu9mm36kmbffp3rah3GAVMExZUpGaIGs14jMTX1rlG3v0wZIyxZgbPc59nMMgi1NhxsDoMSiJfeA/wm.pptx?download&amp;amp;psid=1" target="_blank"&gt;deck&lt;/a&gt;&lt;/li&gt;        &lt;li&gt;Get &lt;a href="http://bit.ly/vK5gsM" target="_blank"&gt;WebMatrix&lt;/a&gt;&lt;/li&gt;     &lt;/ul&gt;   &lt;/li&gt;    &lt;li&gt;Session on &lt;a href="http://2011.osidays.com/proposal/building-cross-browser-html5-web-apps" target="_blank"&gt;building cross browser HTML5 web apps&lt;/a&gt;       &lt;ul&gt;       &lt;li&gt;Get the &lt;a href="https://2vqcza.bay.livefilestore.com/y1ppMwwTdk-qkxwBmRTNqJjMdjc2pGNvOvOAKxDNHPx1VO72wE5qFADpoi_hPLA2nvghN9VjjkMbnir5C2HYdnfIQ/cross-browser.pptx?download&amp;amp;psid=1" target="_blank"&gt;deck&lt;/a&gt;&lt;/li&gt;        &lt;li&gt;Get the &lt;a href="https://2vqcza.bay.livefilestore.com/y1pInxhWZtREX5IF49DVSJYrWnIhVtKeVyyr6KLxa52d3I8fEkQCaG65nkgKBNGOIZobUUH4FQGZW97cJfvHQa6Mw/cross-browser-demos.zip?download&amp;amp;psid=1" target="_blank"&gt;demos&lt;/a&gt;&lt;/li&gt;     &lt;/ul&gt;   &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;That’s all folks. Hope the sessions were useful. If you’ve got feedback on any of these, please feel free to leave a comment. If you want to be nasty and use dirty words, please &lt;a href="http://blogorama.nerdworks.in/contact.aspx" target="_blank"&gt;email&lt;/a&gt; them to me.&lt;/p&gt;  </content></entry><entry><title>Partial function application in JavaScript</title><link href="http://blogorama.nerdworks.in/entry-PartialfunctionapplicationinJa.aspx" rel="alternate" type="text/html" /><id>http://blogorama.nerdworks.in/comment.aspx?entryID=67</id><updated>2011-11-07T09:32:22Z</updated><published>2011-11-07T09:32:22Z</published><content type="html">&lt;p&gt;Partial function application is a functional programming technique that allows you to transform functions that take N parameters into functions that take a subset of N parameters. For example, say you have this fairly useless function:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="prettyprint"&gt;function add(a, b) {
    return a + b;
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let’s say that for some reason we need a version of &amp;quot;&lt;code&gt;add&lt;/code&gt;&amp;quot; that will always have the value 5 for the parameter &amp;quot;&lt;code&gt;a&lt;/code&gt;&amp;quot;. One way we might do it is like so:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;function add5(b) {
    return add(5, b);
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;No black magic there. I was wondering if there might be some way that we can automate the process of generating functions with part of their arguments pre-bound. Here’s what I came up with:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;function partialBind(f, context) {
    // arguments length MUST be greater than 2
    if(arguments.length &amp;lt;= 2) {
        // coz. what're you &amp;quot;partial binding&amp;quot; otherwise?!
        return null;
    }

    // convert args to array excluding param &amp;quot;f&amp;quot; and &amp;quot;context&amp;quot;
    var arrayProto = Array.prototype;
    var params = arrayProto.slice.call(arguments, 2, arguments.length);
    return function () {
        // append params passed to this function to &amp;quot;params&amp;quot;
        var args = params.slice(0, params.length);
        if (arguments.length &amp;gt; 0) {
            arrayProto.forEach.call(arguments, function (p) {
                args.push(p);
            });
        }

        // call the original function
        return f.apply(context, args);
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This function allows me to transform pretty much any function that takes at least 1 argument into a new function that takes a subset of the arguments. Transforming our &amp;quot;&lt;code&gt;add&lt;/code&gt;&amp;quot; function into a single parameter version with &amp;quot;&lt;code&gt;a&lt;/code&gt;&amp;quot; bound to 5 for instance, would now look like this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;var add5 = partialBind(add, null, 5);
var val = add5(10);
assert(val === 15);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Interestingly, &amp;quot;&lt;code&gt;partialBind&lt;/code&gt;&amp;quot; allows us to compose argument binding to multiple levels. If we wanted to take our &amp;quot;&lt;code&gt;add5&lt;/code&gt;&amp;quot; function and create another version that binds the second parameter to, say 20, then we can do this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;var add5_20 = partialBind(add5, null, 20);
var val = add5_20();
assert(val === 25);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Note that we are doing a partial bind of a function that is already a partial bind of another function. Turns out we can take this to as many levels as we want. The example given above is of course somewhat concocted because we could have achieved the same result with a single partial bind instead of doing it in two levels:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;var add5_20 = partialBind(add, null, 5, 20);
var val = add5_20();
assert(val === 25);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;All of this works because JavaScript supports &lt;a href="http://blogorama.nerdworks.in/entry-JavaScriptclosuresactlikeimpli.aspx" target="_blank"&gt;closures&lt;/a&gt;. Pretty nifty don’t you think?&lt;/p&gt;  </content></entry><entry><title>Web Camps, Virtual Tech Days and jsFoo</title><link href="http://blogorama.nerdworks.in/entry-WebCampsVirtualTechDaysandjsFo.aspx" rel="alternate" type="text/html" /><id>http://blogorama.nerdworks.in/comment.aspx?entryID=66</id><updated>2011-10-17T05:28:01Z</updated><published>2011-10-17T05:07:14Z</published><content type="html">&lt;p&gt;So I’ve had a busy few weeks recently doing a bunch of sessions at &lt;a href="http://bit.ly/r56sCs" target="_blank"&gt;Web Camps&lt;/a&gt; (in Delhi and Hyderabad), &lt;a href="http://bit.ly/qgtuFu" target="_blank"&gt;Virtual Tech Days&lt;/a&gt; and &lt;a href="http://jsfoo.hasgeek.com/" target="_blank"&gt;jsFoo&lt;/a&gt;. At each of those events I promised attendees that I’d put up the demos and the decks on my blog “soon”. Well, truth be told I’ve not been exactly conscientious about doing this quickly and I apologize for that. At any rate here’s the material for folks who came by for these sessions:&lt;/p&gt;  &lt;h4&gt;Web Camps&lt;/h4&gt;  &lt;ol&gt;   &lt;li&gt;&lt;strong&gt;Bold and Beautiful with CSS3&lt;/strong&gt; – &lt;a href="http://bit.ly/q9tEsP" target="_blank"&gt;deck&lt;/a&gt; / &lt;a href="https://skydrive.live.com/?cid=2c5064cb54b16f50&amp;amp;sc=documents#cid=2C5064CB54B16F50&amp;amp;id=2C5064CB54B16F50%21516&amp;amp;sc=documents" target="_blank"&gt;demo&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;Spice it up - Advanced HTML5 – &lt;/strong&gt;&lt;a href="http://bit.ly/pmHizA" target="_blank"&gt;deck&lt;/a&gt; / &lt;a href="https://skydrive.live.com/?cid=2c5064cb54b16f50&amp;amp;sc=documents#cid=2C5064CB54B16F50&amp;amp;id=2C5064CB54B16F50%21516&amp;amp;sc=documents" target="_blank"&gt;demo&lt;/a&gt; &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Folks who attended the Hyderabad event might remember that I used a HTML5/CSS3 version of the decks during the session. If you’d like a copy of that code then hang tight because I hope to put up a post here on how I built it and intend to share the source with that post.&lt;/p&gt;  &lt;h4&gt;Virtual Tech Days&lt;/h4&gt;  &lt;ol&gt;   &lt;li&gt;&lt;strong&gt;Socket programming on the web&lt;/strong&gt; – &lt;a href="http://bit.ly/pAMvjI" target="_blank"&gt;deck&lt;/a&gt; / &lt;a href="https://skydrive.live.com/?cid=2c5064cb54b16f50&amp;amp;sc=documents#cid=2C5064CB54B16F50&amp;amp;id=2C5064CB54B16F50%21523&amp;amp;sc=documents" target="_blank"&gt;demo&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;strong&gt;Threading and async programming on the web&lt;/strong&gt; – &lt;a href="http://bit.ly/o7MQbF" target="_blank"&gt;deck&lt;/a&gt; / &lt;a href="https://skydrive.live.com/?cid=2c5064cb54b16f50&amp;amp;sc=documents#cid=2C5064CB54B16F50&amp;amp;id=2C5064CB54B16F50%21526&amp;amp;sc=documents" target="_blank"&gt;demo&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;strong&gt;Baking some HTML5 goodness into your ASP.NET apps&lt;/strong&gt; – &lt;a href="http://bit.ly/q5F2fD" target="_blank"&gt;deck&lt;/a&gt; / &lt;a href="https://skydrive.live.com/?cid=2c5064cb54b16f50&amp;amp;sc=documents#cid=2C5064CB54B16F50&amp;amp;id=2C5064CB54B16F50%21529&amp;amp;sc=documents" target="_blank"&gt;demo&lt;/a&gt;&lt;/li&gt; &lt;/ol&gt;  &lt;h4&gt;jsFoo&lt;/h4&gt;  &lt;ol&gt;   &lt;li&gt;&lt;strong&gt;A primer on ECMAScript 5&lt;/strong&gt; – &lt;a href="http://bit.ly/pJbCU5" target="_blank"&gt;deck&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;Advanced JavaScript Techniques&lt;/strong&gt; – &lt;a href="http://bit.ly/o9tEfl" target="_blank"&gt;deck&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;     &lt;div align="left"&gt;&lt;strong&gt;Best practices for building async apps with JavaScript&lt;/strong&gt; – &lt;a href="http://bit.ly/nHCJPh" target="_blank"&gt;deck&lt;/a&gt; / &lt;a href="https://skydrive.live.com/?cid=2c5064cb54b16f50&amp;amp;sc=documents#cid=2C5064CB54B16F50&amp;amp;id=2C5064CB54B16F50%21539&amp;amp;sc=documents" target="_blank"&gt;demo&lt;/a&gt;&lt;/div&gt;   &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;A number of jsFoo attendees requested that I share the “eval” console that I used to geek out on many of the advanced JS and ES5 samples during the session. I already have a post on that here:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a title="http://bit.ly/js-eval" href="http://bit.ly/js-eval"&gt;http://bit.ly/js-eval&lt;/a&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;You should be able to download a copy for your own use from that post or use the &lt;a href="http://blogorama.nerdworks.in/arbit/webstuff/eval/" target="_blank"&gt;online version&lt;/a&gt; if you prefer that.&lt;/p&gt;  </content></entry><entry><title>On the HTML5 Indexed DB API - Part 4 of n</title><link href="http://blogorama.nerdworks.in/entry-OntheHTML5IndexedDBAPIPart4ofn.aspx" rel="alternate" type="text/html" /><id>http://blogorama.nerdworks.in/comment.aspx?entryID=64</id><updated>2011-09-08T03:51:02Z</updated><published>2011-09-08T03:51:02Z</published><content type="html">&lt;p&gt;So far we have looked at creating databases and adding data to them. Let's next take a look at retrieving records from the database. Surprisingly, this turns out to be a bit complex. The indexed DB way of enumerating records from an object store is to use a “cursor” object. A cursor can iterate over records from an underlying object store or an index. A cursor has the following key properties:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;A &lt;em&gt;&lt;strong&gt;range&lt;/strong&gt;&lt;/em&gt; of records in either an index or an object store. &lt;/li&gt;    &lt;li&gt;A &lt;em&gt;&lt;strong&gt;source&lt;/strong&gt;&lt;/em&gt; that references the index or object store that the cursor is iterating over. &lt;/li&gt;    &lt;li&gt;A &lt;em&gt;&lt;strong&gt;position&lt;/strong&gt;&lt;/em&gt; indicating the current position of the cursor in the given range of records. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;While the concept of a cursor is fairly straightforward, writing the code to actually iterate over an object store turns out to be somewhat tricky given the asynchronous nature of all the API calls. Let’s implement the &lt;code&gt;listNotes&lt;/code&gt; method of our &lt;code&gt;NotesStore&lt;/code&gt; object and see what the code looks like.&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="prettyprint"&gt;...
listNotes: function (callback) {
    var self = this,
        txn = self.db.transaction(null, TransactionMode.ReadOnly),
        notes = [],
        store = txn.objectStore(self.store_name);

    Utils.request(store.openCursor(), function (e) {
        var cursor = e.result,
            iterate = function () {
                Utils.request(cursor.move(), function (e2) {
                    // if &amp;quot;result&amp;quot; is true then we have data else
                    // we have reached end of line
                    if (e2.result) {
                        notes.push(cursor.value);

                        // recursively get next record
                        iterate();
                    }
                    else {
                        // we are done retrieving rows; invoke callback
                        txn.commit();
                        callback(notes);
                    }
                });
            };

        // set the ball rolling by calling iterate for the first row
        iterate();
    });
},
...&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let’s break this implementation down:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;First we acquire a transaction object by calling the database object’s &lt;code&gt;transaction&lt;/code&gt; method. Note that this time we are indicating that we require a “read-only” transaction. &lt;/li&gt;

  &lt;li&gt;Next we retrieve a reference to the object store via the &lt;code&gt;objectStore&lt;/code&gt; method of the transaction object. &lt;/li&gt;

  &lt;li&gt;Then we issue an async call to the &lt;code&gt;openCursor&lt;/code&gt; API on the object store. The tricky part here is that every single iteration over a record in the cursor is itself an async operation! To prevent the code from drowning in a sea of callbacks we define a local function called &lt;code&gt;iterate&lt;/code&gt; to encapsulate the logic of iterating over every record in the cursor. &lt;/li&gt;

  &lt;li&gt;This &lt;code&gt;iterate&lt;/code&gt; function makes an async call to the cursor object’s &lt;code&gt;move&lt;/code&gt; method and recursively invokes itself again in the callback if it detects that there are more rows to be retrieved. Once all the rows in the cursor have been retrieved we finally invoke the callback method passed by the caller handing in the retrieved data as a parameter.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;That’s it for today’s post. I’ll let you mull over this for a bit till the next post when we’ll cover some more scenarios.&lt;/p&gt;  </content></entry><entry><title>On the HTML5 Indexed DB API - Part 3 of n</title><link href="http://blogorama.nerdworks.in/entry-OntheHTML5IndexedDBAPIPart3ofn.aspx" rel="alternate" type="text/html" /><id>http://blogorama.nerdworks.in/comment.aspx?entryID=63</id><updated>2011-09-06T00:43:56Z</updated><published>2011-09-06T00:43:56Z</published><content type="html">&lt;p&gt;In the &lt;a href="http://blogorama.nerdworks.in/entry-OntheHTML5IndexedDBAPIPart2ofn.aspx" target="_blank"&gt;previous post&lt;/a&gt; we covered some more background on working with the Indexed DB API and briefly reviewed the mechanics of creating a new database. In this post we take a look at some important Indexed DB constructs that one must be familiar with while working with the core APIs.&lt;/p&gt;  &lt;h3&gt;Object stores&lt;/h3&gt;  &lt;p&gt;Object stores are the indexed DB equivalent of &amp;quot;tables&amp;quot; from the relational database world. All data is stored inside object stores and serves as the primary unit of storage. A database can contain multiple object stores and each store is a collection of records. Each record is a simple key/value pair. Keys must uniquely identify a particular record and can be auto-generated. The records in an object store are automatically sorted in ascending order by keys. And finally, object stores can be created and deleted only under the context of &amp;quot;version change&amp;quot; transactions. We’ll see what a &amp;quot;version change&amp;quot; transaction is when we review transactions later on in this post.&lt;/p&gt;  &lt;h3&gt;Keys and Values&lt;/h3&gt;  &lt;p&gt;Each record in the object store is uniquely identified by a &amp;quot;key&amp;quot;. Keys can be arrays, strings, dates or numbers. For the purpose of comparison, arrays are considered to be greater than strings which are greater than dates which in turn are considered to be greater than numbers. Keys can be &amp;quot;in-line&amp;quot; keys or not. By &amp;quot;in-line&amp;quot; we indicate to indexed DB that the key for a particular record is actually a part of the value object itself. In our notes store sample for instance, each note object has an id property which contains the unique identifier for a particular note. This is an example of an &amp;quot;in-line&amp;quot; key, i.e., the key is a part of the value object.&lt;/p&gt;  &lt;p&gt;Whenever keys are &amp;quot;in-line&amp;quot;, we must also specify a &amp;quot;key path&amp;quot;, i.e. a string that signifies how the key value can be extracted from the value object. The key path for &amp;quot;note&amp;quot; objects for instance is the string &amp;quot;id&amp;quot; since the key can be extracted from note instances by accessing the &amp;quot;id&amp;quot; property. But this scheme allows for the key value to be stored at an arbitrary depth in the value object’s member hierarchy. Consider the following sample value object:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="prettyprint"&gt;var product = {
  info: {
    name: &amp;quot;Towel&amp;quot;,
    type: &amp;quot;Indispensable hitchhiker item&amp;quot;,
  },
  identity: {
    server: {
      value: &amp;quot;T01&amp;quot;
    },
    client: {
      value: &amp;quot;TC01&amp;quot;
    },
  },
  price: &amp;quot;Priceless&amp;quot;
};&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here, the following key path might be used:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;identity.client.value&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;h3&gt;Database versioning&lt;/h3&gt;

&lt;p&gt;Indexed DB databases have a version string associated with them. This can be used by web applications to determine whether the database on a particular client has the latest structure or not. This is useful when you make changes to your database’s data model and want to propagate those changes to existing clients who are on the previous version of your data model. You can simply change the version number for the new structure and check for it the next time the user runs your app and do the needful to upgrade the structure and migrate the data.&lt;/p&gt;

&lt;p&gt;Version number changes must be performed under the context of a &amp;quot;version change&amp;quot; transaction. Before we talk about that though let’s quickly review what &amp;quot;transactions&amp;quot; are.&lt;/p&gt;

&lt;h3&gt;Transactions&lt;/h3&gt;

&lt;p&gt;Like relational databases, indexed DB also performs all of its I/O operations under the context of transactions. Transactions are created through connection objects and enable atomic, durable data access and mutation. There are two key attributes for transaction objects:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;h4&gt;Scope&lt;/h4&gt;

    &lt;p&gt;The scope determines which parts of the database can be affected through the transaction. This basically helps the indexed DB implementation determine what kind of isolation level to apply to objects during the lifetime of the transaction. You can think of the scope as simply being a list of object stores that will form a part of the transaction.&lt;/p&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;h4&gt;Mode&lt;/h4&gt;

    &lt;p&gt;The transaction mode determines what kind of I/O operation is permitted in the transaction. The mode can be:&lt;/p&gt;

    &lt;ol style="list-style-type: lower-latin"&gt;
      &lt;li&gt;
        &lt;h5&gt;Read only&lt;/h5&gt;

        &lt;p&gt;Allows only &amp;quot;read&amp;quot; operations on the objects that are a part of the transaction’s scope.&lt;/p&gt;
      &lt;/li&gt;

      &lt;li&gt;
        &lt;h5&gt;Read/write&lt;/h5&gt;

        &lt;p&gt;Allows &amp;quot;read&amp;quot; and &amp;quot;write&amp;quot; operations on the objects that are a part of the transaction’s scope.&lt;/p&gt;
      &lt;/li&gt;

      &lt;li&gt;
        &lt;h5&gt;Version change&lt;/h5&gt;

        &lt;p&gt;The &amp;quot;version change&amp;quot; mode allows &amp;quot;read&amp;quot; and &amp;quot;write&amp;quot; operations and also allows the creation and deletion of object stores and indexes, i.e., the structure of the database can be modified only under the context of a &amp;quot;version change&amp;quot; transaction.&lt;/p&gt;
      &lt;/li&gt;
    &lt;/ol&gt;

    &lt;p&gt;Transaction objects auto-commit themselves unless they have been explicitly aborted. Transaction objects expose events to notify clients of:&lt;/p&gt;

    &lt;ul&gt;
      &lt;li&gt;when they complete &lt;/li&gt;

      &lt;li&gt;when they abort and &lt;/li&gt;

      &lt;li&gt;when they timeout &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;Creating the object store&lt;/h3&gt;

&lt;p&gt;Our notes store database will contain only a single object store to record the list of notes. As discussed earlier, object stores must be created under the context of a &amp;quot;version change&amp;quot; transaction. Let’s go ahead and extend the &lt;code&gt;init&lt;/code&gt; method of the &lt;code&gt;NotesStore&lt;/code&gt; object to include the creation of the object store. I’ve highlighted the changed bits in bold.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;var NotesStore = {
    name: &amp;quot;notes-db&amp;quot;,
&lt;strong&gt;    store_name: &amp;quot;notes-store&amp;quot;,
    store_key_path: &amp;quot;id&amp;quot;,&lt;/strong&gt;
    db: null,
    ver: &amp;quot;1.0&amp;quot;,
    init: function (callback) {
        var self = this;
        callback = callback || function () { };
        Utils.request(window.indexedDB.open(&amp;quot;open&amp;quot;, this.name), function (e) {
            self.db = e.result;

&lt;strong&gt;            // if the version of this db is not equal to
            // self.version then change the version
            if (self.db.version !== self.version) {
                Utils.request(self.db.setVersion(self.ver), function (e2) {
                    var txn = e2.result;

                    // create object store
                    self.db.createObjectStore(self.store_name,
                                              self.store_key_path,
                                              true);
                    txn.commit();
                    callback();
                });
            } else {
                callback();
            }&lt;/strong&gt;
        });
    },
    …&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Object stores are created by calling the &lt;code&gt;createObjectStore&lt;/code&gt; method on the database object. The first parameter is the name of the object store. This is followed by the string identifying the key path and finally a Boolean flag indicating whether the key value should be auto-generated by the database when new records are added.&lt;/p&gt;

&lt;h3&gt;Adding data to object stores&lt;/h3&gt;

&lt;p&gt;New records can be added to an object store by calling the &lt;code&gt;put&lt;/code&gt; method on the object store object. A reference to the object store instance can be retrieved through the transaction object. Let’s implement the &lt;code&gt;addNote&lt;/code&gt; method of our &lt;code&gt;NotesStore&lt;/code&gt; object and see how we can go about adding a new record:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;    …
    addNote: function (text, tags, callback) {
        var self = this;
        callback = callback || function () { };
        var txn = self.db.transaction(null, TransactionMode.ReadWrite);
        var store = txn.objectStore(self.store_name);
        Utils.request(store.put({
            text: text,
            tags: tags
        }), function (e) {
            txn.commit();
            callback();
        });
    },

    …&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This method can be broken down into the following steps:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;Invoke the &lt;code&gt;transaction&lt;/code&gt; method on the database object to start off a new transaction. The first parameter is the list of names of the object stores which are going to be a part of the transaction. Passing &lt;code&gt;null&lt;/code&gt; causes all the object stores in the database to be a part of the scope. The second parameter indicates the transaction mode. This is basically a numeric constant which we have declared like so:&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;pre class="prettyprint"&gt;// IndexedDB transaction mode constants
var TransactionMode = {
    ReadWrite: 0,
    ReadOnly: 1,
    VersionChange: 2
};&lt;/pre&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;p&gt;Once the transaction has been created we acquire a reference to the object store in question through the transaction object’s &lt;code&gt;objectStore&lt;/code&gt; method.&lt;/p&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;p&gt;Once we have the object store handy, adding a new record is just a matter of issuing an asynchronous API call to the object store’s &lt;code&gt;put&lt;/code&gt; method passing in the new object to be added to the store. Note that we do not pass a value for the &lt;code&gt;id&lt;/code&gt; field of the new note object. Since we passed &lt;code&gt;true&lt;/code&gt; for the auto-generate parameter while creating the object store, the indexed DB implementation should take care of automatically assigning a unique identifier for the new record.&lt;/p&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;p&gt;Once the asynchronous &lt;code&gt;put&lt;/code&gt; call completes successfully, we commit the transaction.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;Coming up&lt;/h3&gt;

&lt;p&gt;In the next post, we’ll take a look at retrieving records from an indexed DB. Surprisingly, this turns out to be slightly trickier than what one might expect.&lt;/p&gt;  </content></entry><entry><title>On the HTML5 Indexed DB API - Part 2 of n</title><link href="http://blogorama.nerdworks.in/entry-OntheHTML5IndexedDBAPIPart2ofn.aspx" rel="alternate" type="text/html" /><id>http://blogorama.nerdworks.in/comment.aspx?entryID=62</id><updated>2011-09-04T23:48:03Z</updated><published>2011-09-04T23:48:03Z</published><content type="html">&lt;p&gt;In the &lt;a href="http://blogorama.nerdworks.in/entry-OntheHTML5IndexedDBAPIPart1ofn.aspx" target="_blank"&gt;previous post&lt;/a&gt; in this series we covered the fundamentals of the Indexed DB specification. We continue the journey in this post and take a look at the API itself.&lt;/p&gt;  &lt;h3&gt;Building an offline note taking app&lt;/h3&gt;  &lt;p&gt;For the rest of this series of posts, we’ll try and build the client side data layer for a fictitious note taking web app. From a data model point of view it’s about as simple as it can get. The app allows users to write text notes and tag them with specific key words. Each note will have a unique identifier which will serve as its key and apart from the note text, it will be associated with a collection of tag strings. Here’s a sample note object represented in JavaScript object literal notation:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="prettyprint"&gt;var note = {
      id: 1,
      text: &amp;quot;Note text.&amp;quot;,
      tags: [&amp;quot;sample&amp;quot;, &amp;quot;test&amp;quot;]
    };&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;We’ll build a &lt;code&gt;NotesStore&lt;/code&gt; object that has the following interface:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;var NotesStore = {
        init: function(callback) {
        },

        addNote: function(text, tags, callback) {
        },
    
        listNotes: function(callback) {
        }
    };&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;It should be fairly self-evident as to what each method does. All method calls execute asynchronously and where a result is to be returned to the caller, the interface accepts a reference to a callback that is to be invoked with the result. Let’s see what it takes to efficiently implement this object using an indexed database.&lt;/p&gt;

&lt;h3&gt;Testing for Indexed DB&lt;/h3&gt;

&lt;p&gt;The root object that you deal with when talking to the indexed DB API is called &lt;code&gt;indexedDB&lt;/code&gt;. In fact you can check for the presence of this object to see whether the current browser supports indexed DB or not. Like so:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;if(window[“indexedDB”] === undefined) {
      // nope, no indexed DB!
    } else {
      // yep, we’re good to go!
    }&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Alternatively, you can use the &lt;a href="http://www.modernizr.com/" target="_blank"&gt;Modernizr&lt;/a&gt; JavaScript library to test for support for indexed DB like so:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;if(Modernizr.indexeddb) {
        // yep, go indexeddb!
    } else {
        // bleh! No joy!
    }&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;h3&gt;Asynchronous requests&lt;/h3&gt;

&lt;p&gt;The asynchronous API calls work through what are known as “request” objects. When an asynchronous API call is made, it would return a reference to a “request” object which exposes two events – &lt;code&gt;onsuccess&lt;/code&gt; and &lt;code&gt;onerror&lt;/code&gt;. The former is raised when the API executes successfully and the latter is raised when it errors out. Here’s what a typical call looks like:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;var req = someAsyncCall();
    req.onsuccess = function() {
        // handle success case
    };
    req.onerror = function() {
        // handle error
    };&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;As you work with the indexedDB API you eventually get to a point where it becomes somewhat hard to keep track of all the callbacks. In a future post I’ll explore some ideas I am currently playing with on how we can simplify this further. For now though, to make our exploration of the API somewhat simpler I’ll define and use a small utility routine that abstracts the “request” pattern away:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;var Utils = {
        errorHandler: function(cb) {
            return function(e) {
                if(cb) {
                    cb(e);
                } else {
                    throw e;
                }
            };
        },
    
        request: function (req, callback, err_callback) {
            if (callback) {
                req.onsuccess = function (e) {
                    callback(e);
                };
            }
            req.onerror = errorHandler(err_callback);
        }
    };&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now, I can write my async calls like so:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;Utils.request(someAsyncCall(), function(e) {
        // handle completion of call
    });&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;h3&gt;Creating and opening the database&lt;/h3&gt;

&lt;p&gt;Creating/opening a database is done by calling the &lt;code&gt;open&lt;/code&gt; method of the &lt;code&gt;indexedDB&lt;/code&gt; object. Here’s an implementation of the &lt;code&gt;NotesStore&lt;/code&gt; object’s &lt;code&gt;init&lt;/code&gt; method:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;var NotesStore = {
    name: “notes-db”,
    db: null,
    ver: “1.0”,
    init: function(callback) {
        var self = this;
        callback = callback || function () { };
        Utils.request(window.indexedDB.open(“open”, this.name), function(e) {
            self.db = e.result;
            callback();
        });
    },

    …&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The &lt;code&gt;open&lt;/code&gt; method opens the database if it already exists or creates a new one if not. The success callback of the request object returned by &lt;code&gt;open&lt;/code&gt; receives an event object as a parameter whose &lt;code&gt;result&lt;/code&gt; property is a reference to the newly opened database. You can think of this as the object that represents the connection to the database. When this object is destroyed (or if you called its &lt;code&gt;close&lt;/code&gt; method) the connection to the database is terminated.&lt;/p&gt;

&lt;h3&gt;Coming up&lt;/h3&gt;

&lt;p&gt;Now that we have the database created, in the next post, we’ll go ahead and create the rest of the database objects.&lt;/p&gt;  </content></entry><entry><title>On the HTML5 Indexed DB API – Part 1 of n</title><link href="http://blogorama.nerdworks.in/entry-OntheHTML5IndexedDBAPIPart1ofn.aspx" rel="alternate" type="text/html" /><id>http://blogorama.nerdworks.in/comment.aspx?entryID=61</id><updated>2011-09-03T21:40:34Z</updated><published>2011-09-03T21:40:34Z</published><content type="html">&lt;p&gt;Over the years the web has increasingly transformed from being just a repository of content to a marketplace of full-fledged functional applications. The suite of technologies that are bandied about these days under the “HTML5” banner have as a fundamental goal, the enablement of the building of this new breed of software. In this post (and over the next post or two) we review a technology that solves an important piece of the application puzzle – that of managing storage and retrieval of user specific data on the client side, called “Indexed DB”. For almost as long as the web has been around, there has been a need for web sites to track visitor specific information in one form or another. Using HTTP cookies has so far been pretty much the only standards based option available to web developers. While plug-in based alternatives in the form of Silverlight and Flash do exist, the typical challenges imposed on end users who either do not have the plug-in in question installed or are using the wrong version serves to complicate matters significantly. Let’s first briefly review what the available alternatives are for a web developer seeking to solve the problem of managing client side storage today:&lt;/p&gt;  &lt;blockquote&gt;   &lt;h4&gt;HTTP Cookies&lt;/h4&gt;    &lt;p&gt;HTTP cookies allow web applications to store small amounts of textual data on the client side using specially crafted HTTP headers. Access to this data is provided via the browser DOM. JavaScript code must be used to parse and make sense of the data. While this works, there are significant challenges in working with cookies:&lt;/p&gt;    &lt;ul&gt;     &lt;li&gt;       &lt;p&gt;Cookies are not allowed to be greater than 4 KB in size.&lt;/p&gt;     &lt;/li&gt;      &lt;li&gt;       &lt;p&gt;Cookies are transmitted with every request that the browser makes – even when it is requesting for things like images, script files or style sheets.&lt;/p&gt;     &lt;/li&gt;      &lt;li&gt;       &lt;p&gt;The programming model is not straightforward in that it is basically just text and you need to write code to parse and crack data stored in cookies.&lt;/p&gt;     &lt;/li&gt;      &lt;li&gt;       &lt;p&gt;Only textual data can be stored and retrieved.&lt;/p&gt;     &lt;/li&gt;   &lt;/ul&gt;    &lt;h4&gt;Plug-ins&lt;/h4&gt;    &lt;p&gt;Plug-ins have historically been the natural (if not the only) choice for web developers who have needs that are not catered to sufficiently by cookies. Technologies such as Silverlight, Flash and Google Gears come with their own brand of local storage options. While they are a better option as compared to cookies they do however present some unique challenges of their own:&lt;/p&gt;    &lt;ul&gt;     &lt;li&gt;       &lt;p&gt;As stated earlier, the primary issue is that user experience is less than stellar when you encounter cases where the user either does not have the plug-in in question installed or has the wrong version installed and must therefore upgrade. Often users are logged in to their computers with user accounts that do not have the required permission to install new software and hence are simply locked out of the web application or functionality completely.&lt;/p&gt;     &lt;/li&gt;      &lt;li&gt;       &lt;p&gt;Web developers must familiarize themselves with the specific tool stack associated with the plug-in.&lt;/p&gt;     &lt;/li&gt;   &lt;/ul&gt;    &lt;h4&gt;DOM Storage&lt;/h4&gt;    &lt;p&gt;DOM storage is a part of the HTML5 suite of specifications and is meant to be a replacement for HTTP cookies. This is actually a viable client side storage option. The idea is to basically provide a key/value based storage API that allows web applications to store user specific data in a persistent manner. The API is simple to use and it just works! However, there are some limitations to how it can be put to use which are to a large extent deliberate and by design:&lt;/p&gt;    &lt;ul&gt;     &lt;li&gt;       &lt;p&gt;You can only store strings in DOM storage, i.e., both key and value must be JavaScript strings. You can however use JSON serialization to manage the storage and retrieval of objects.&lt;/p&gt;     &lt;/li&gt;      &lt;li&gt;       &lt;p&gt;Data stored in DOM storage is scoped by the domain, i.e., it will not be possible for code running in one domain to access DOM storage data stored under the context of a different domain. While this is a good thing, the limitation however is that it is not possible to scope this with a greater level of granularity – say by specific URLs within a domain.&lt;/p&gt;     &lt;/li&gt;      &lt;li&gt;       &lt;p&gt;There is no mechanism to iterate through all the data stored in DOM storage. You can only request the value for a specific key that you already know.&lt;/p&gt;     &lt;/li&gt;   &lt;/ul&gt;    &lt;p&gt;With that brief overview of the alternatives let us move on to the topic of this post – the Indexed Database API.&lt;/p&gt; &lt;/blockquote&gt;  &lt;h3&gt;What is Indexed DB?&lt;/h3&gt;  &lt;p&gt;An Indexed DB is basically a persistent data store in the browser – a database on the client side. It defines an API that allows the storage and retrieval of key/value data. Like regular relational databases, it maintains indexes over the records it stores and developers use the Indexed DB JavaScript API to locate records by key or by looking up an index. Each database is scoped by “origin”, i.e. the domain of the site that creates the database. The database is transactional and provides a means for traversing the data in a deterministic order.&lt;/p&gt;  &lt;p&gt;The Indexed DB API includes a synchronous and an asynchronous version of pretty much all the interfaces. The asynchronous API is meant to be used from web apps when you are interacting with the database directly from the UI thread where having an API call block on an I/O operation is not acceptable. All blocking calls work asynchronously and results are reported via callbacks. The synchronous API counterparts are identical to the asynchronous versions except for the fact that there are no callbacks and results are returned directly.&lt;/p&gt;  &lt;h3&gt;A word on the status of the spec&lt;/h3&gt;  &lt;p&gt;The Indexed DB specification is currently (i.e., when this post was written) in draft status and should not be considered as being production ready. The specification itself is under active development and developers are encouraged to review it only with the objective of familiarizing themselves with an up and coming standard. Do not use it in production sites yet!&lt;/p&gt;  &lt;h3&gt;Setting your development environment up&lt;/h3&gt;  &lt;p&gt;Before we proceed with the API itself, you might want to spend some time setting up your development environment up. For Internet Explorer (IE), an experimental implementation of the specification is available for download from Microsoft’s &lt;a href="http://html5labs.interoperabilitybridges.com/prototypes/indexeddb/indexeddb/info" target="_blank"&gt;HTML5 Labs&lt;/a&gt; site. “HTML5 Labs” is an initiative from Microsoft for publishing prototype implementations of various key HTML5 specifications so that developers are able to experiment with them and provide feedback. The prototype implementation for Indexed DB works on Internet Explorer versions 8 and up and installing it is fairly straightforward.&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;     &lt;p&gt;Download the prototype by clicking on the link “Download the Protoype now!” from &lt;a href="http://html5labs.interoperabilitybridges.com/prototypes/indexeddb/indexeddb/info" target="_blank"&gt;here&lt;/a&gt;.&lt;/p&gt;   &lt;/li&gt;    &lt;li&gt;     &lt;p&gt;Unzip the downloaded file.&lt;/p&gt;   &lt;/li&gt;    &lt;li&gt;     &lt;p&gt;If you are running a 32-bit version of Windows then run &lt;em&gt;vcredist_x86.exe&lt;/em&gt;.&lt;/p&gt;   &lt;/li&gt;    &lt;li&gt;     &lt;p&gt;Register “sqlcejse40.dll” by running the following command from an elevated command prompt:&lt;/p&gt;      &lt;blockquote&gt;       &lt;p&gt;&lt;strong&gt;regsvr32 sqlcejse40.dll&lt;/strong&gt;&lt;/p&gt;     &lt;/blockquote&gt;      &lt;p&gt;If everything goes well, then you should see a screen such as the following:&lt;/p&gt;      &lt;blockquote&gt;&amp;#160;&lt;a href="http://blogorama.nerdworks.in/images/_img10.png"&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="reg" border="0" alt="reg" src="http://blogorama.nerdworks.in/images/_img11.png" width="366" height="131" /&gt;&lt;/a&gt;&lt;/blockquote&gt;   &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Alternatively, get a recent version of &lt;em&gt;Google Chrome&lt;/em&gt; or &lt;em&gt;Firefox&lt;/em&gt; and you should be all set.&lt;/p&gt;  &lt;h3&gt;Coming up…&lt;/h3&gt;  &lt;p&gt;Now that we have the fundamentals covered, we’ll go ahead and get started with the API itself from the next post. Stay tuned!&lt;/p&gt;  </content></entry><entry><title>On JavaScript code blocks, variable scope and variable hoisting</title><link href="http://blogorama.nerdworks.in/entry-OnJavaScriptcodeblocksvariable.aspx" rel="alternate" type="text/html" /><id>http://blogorama.nerdworks.in/comment.aspx?entryID=60</id><updated>2011-09-02T22:50:07Z</updated><published>2011-09-02T22:50:07Z</published><content type="html">&lt;p&gt;I am currently reading the book &lt;a href="http://oreilly.com/catalog/9780596806767" target="_blank"&gt;JavaScript Patterns, by Stoyan Stefanov&lt;/a&gt; and I came across this interesting tidbit of information regarding variable scopes in JavaScript.&amp;#160; Consider the following C++ code:&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="prettyprint"&gt;#include &amp;lt;iostream&amp;gt;

int main() {
  if(true) {
    int foo = 10;
  }

  std::cout&amp;lt;&amp;lt;foo;
  return 0;
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Compiling this produces the following error:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;scope.cpp(8) : error C2065: 'foo' : undeclared identifier&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is only to be expected. In C++, code blocks automatically define a variable scope, i.e., variables defined inside the code block are not visible outside of it. The same behavior can be observed in many of the other popular programming languages in use today such as C# and Java with one notable exception – JavaScript! &lt;img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://blogorama.nerdworks.in/images/_img9.png" /&gt; Consider the following JavaScript snippet:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;function scope() {
    if(true) {
        var foo = 10;
    }
    print(foo);
}

scope();&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Interestingly, this prints the value “10”! What’s going on here? The first thing one needs to understand about JavaScript is the notion of “variable hoisting”. Regardless of where you have declared a variable, the runtime treats it as though it has been declared at the start of the scope. Here’s an example:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;function hoist() {
    try {
        print(undeclaredVariable === undefined);
        print(&amp;quot;Yep, was able to refer to 'undeclaredVariable'.&amp;quot;);
    }
    catch(e) {
        print(&amp;quot;Could not use 'undeclaredVariable'.&amp;quot;);
    }
    
    try {
        print(declaredLater === undefined);
        print(&amp;quot;Yep, was able to refer to 'declaredLater'.&amp;quot;);
    }
    catch(e) {
        print(&amp;quot;Could not use 'declaredLater'.&amp;quot;);
    }
    
    var declaredLater = 10;
}

hoist();&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Running this snippet produces the following output:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;Could not use 'undeclaredVariable'.
true
Yep, was able to refer to 'declaredLater'.&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;In the function “hoist” we have declared a variable named “declaredLater” right at the end of the function body.&amp;#160; Interestingly, while we were unable to refer to an undeclared variable (evidenced by the fact that the “print” statement inside the first “catch” block got executed) we seem to have no problems referring to “declaredLater” even before it is actually declared. This is so because the JavaScript runtime “hoists” all the local variables declared in the function to the top of the function.&amp;#160; It is as though the function had been defined like so:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;function hoist() {
    var declaredLater;

    // stuff here
    
    declaredLater = 10;
}

hoist();&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Note that though the variable itself gets declared at the top of the function, the initialization still happens only on the line where it occurred in the original function - which explains why the statement &lt;code&gt;print(undeclaredVariable === undefined)&lt;/code&gt; ends up printing &lt;code&gt;true&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now, why did our “scope” function work the way it did? Turns out that in JavaScript curly braces &lt;u&gt;do not&lt;/u&gt; introduce a variable scope. Only functions do. This means that variables declared inside of “if”, “for”, “while” etc. behave as though they have been declared at the top of the function. The aforementioned book therefore recommends moving all variable declarations to the top of the function. So, instead of doing the following:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;function foo() {
    var a = [1, 2, 3, 4];
    if(someCondition() === true) {
        var b, c, d;
        // do something with b, c, d
    }
    for(var i = 0; i &amp;lt; a.length ; ++i) {
        // do something with &amp;quot;a&amp;quot;
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;Do something like the following:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;function foo() {
    var a = [1, 2, 3, 4], b, c, d, i, len = a.length;

    if(someCondition() === true) {
        // do something with b, c, d
    }
    for(i = 0; i &amp;lt; len ; ++i) {
        // do something with &amp;quot;a&amp;quot;
    }
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;This makes it clear that the scope of the variables in question is the function “foo”.&lt;/p&gt;

&lt;p&gt;The key takeaways therefore are the following:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Code blocks &lt;u&gt;do not&lt;/u&gt; determine variable scope in JavaScript. Functions are the only construct that can be used to limit scope of variables. &lt;/li&gt;

  &lt;li&gt;Regardless of where variables are declared, the runtime always treats them as though they have been declared at the beginning of the function in question. &lt;/li&gt;

  &lt;li&gt;
    &lt;p&gt;If you need some global code to be executed, then use an immediate function (also known as a “self-executing” function) to limit the scope of the local variables you use in that code. So instead of doing the following:&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;pre class="prettyprint"&gt;&amp;lt;script&amp;gt;
  var v1, v2;
  // some code here that uses v1 and v2
&amp;lt;/script&amp;gt;&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p&gt;Use code like this:&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;pre class="prettyprint"&gt;&amp;lt;script&amp;gt;
  (function() {
      var v1, v2;
      // some code here that uses v1 and v2
  })();
&amp;lt;/script&amp;gt;&lt;/pre&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;
&lt;/ul&gt;  </content></entry><entry><title>JavaScript strict mode restrictions</title><link href="http://blogorama.nerdworks.in/entry-JavaScriptstrictmoderestrictio.aspx" rel="alternate" type="text/html" /><id>http://blogorama.nerdworks.in/comment.aspx?entryID=59</id><updated>2011-09-19T08:30:38Z</updated><published>2011-09-01T23:04:52Z</published><content type="html">&lt;p&gt;In the &lt;a href="http://blogorama.nerdworks.in/entry-OnJavaScriptstrictmode.aspx" target="_blank"&gt;previous post&lt;/a&gt; we took a look at what strict mode was all about.&amp;#160; Today we review some of the key restrictions that become applicable when strict mode is active.&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;     &lt;h4&gt;Identifiers must be declared before they can be assigned to&lt;/h4&gt;      &lt;p&gt;This aspect in my opinion makes strict mode worthwhile all on its own even if there was nothing more to it. Undeclared variable assignments do not automatically get added as expando properties on the global object.&lt;/p&gt;      &lt;blockquote&gt;       &lt;pre class="prettyprint"&gt;&amp;quot;use strict&amp;quot;;
foo = 10; // ReferenceError: Variable undefined in strict mode&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p&gt;With this in place, the following snippet that I’d given in the &lt;a href="http://blogorama.nerdworks.in/entry-OnJavaScriptstrictmode.aspx" target="_blank"&gt;first post&lt;/a&gt; under the “What is strict mode?” section will fail to run and throw a “ReferenceError” instead because of the typo in the variable name “product” in the assignment inside the “for” loop.&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;pre class="prettyprint"&gt;function findProduct(numbers) {
    &amp;quot;use strict&amp;quot;;
    var product = 0,
        len = numbers.length;
    for(var i = 0; i &amp;lt; len; ++i) {
        &lt;font style="background-color: #ffff00"&gt;prodct&lt;/font&gt; = product * numbers[i]; // ReferenceError: Variable undefined in strict mode
    }
    return product;
}&lt;/pre&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;h4&gt;No automatic context for context-less function calls&lt;/h4&gt;

    &lt;p&gt;Functions that are called without setting an explicit context do not automatically get the “global object” in “this”. Consider the following snippet:&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;pre class="prettyprint"&gt;function foo() {
    // prints “true”
    print(this === window);
}
foo();&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p&gt;Here, “foo” is being invoked without setting an explicit context object, i.e., we are not calling it like so:&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;pre class="prettyprint"&gt;foo.call({foo: &amp;quot;bar&amp;quot;});&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p&gt;In unrestricted mode this causes the context to be automatically initialized to the “global” object, which in browsers is the “window” object. Since the snippet above was running in unrestricted mode, the expression “this === window” evaluates to true. If we modify the function like so however, we see that “this” is no longer equal to “window”:&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;pre class="prettyprint"&gt;function foo() {
    &amp;quot;use strict&amp;quot;;
    // prints “false”
    print(this === window);
}
foo();&lt;/pre&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;h4&gt;Reserved keywords cannot be identifier names&lt;/h4&gt;

    &lt;p&gt;Naming variables and functions as &lt;code&gt;eval&lt;/code&gt;, &lt;code&gt;arguments&lt;/code&gt;, &lt;code&gt;implements&lt;/code&gt;, &lt;code&gt;let&lt;/code&gt;, &lt;code&gt;private&lt;/code&gt;, &lt;code&gt;public&lt;/code&gt;, &lt;code&gt;yield&lt;/code&gt;, &lt;code&gt;interface&lt;/code&gt;, &lt;code&gt;package&lt;/code&gt;, &lt;code&gt;protected&lt;/code&gt; and &lt;code&gt;static&lt;/code&gt; will cause errors.&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;pre class="prettyprint"&gt;&amp;quot;use strict&amp;quot;;
var yield; // SyntaxError: Expected identifier&lt;/pre&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;h4&gt;Violations of ES5 property configuration cause errors&lt;/h4&gt;

    &lt;p&gt;Violations of the configuration as specified in the property descriptor for ES5 properties will cause errors to be thrown in strict mode instead of them being silently ignored. Here are some examples:&lt;/p&gt;

    &lt;ol style="list-style-type: lower-latin"&gt;
      &lt;li&gt;&lt;em&gt;Writing to a non-writable property:&lt;/em&gt; 

        &lt;blockquote&gt;
          &lt;pre class="prettyprint"&gt;&amp;quot;use strict&amp;quot;;
var person = Object.create({}, {
    name: {
        value: &amp;quot;foo&amp;quot;,
        &lt;strong&gt;writable: false&lt;/strong&gt;,
        configurable: true,
        enumerable: true
    }
});

// TypeError: Assignment to read only properties not allowed in 
// strict mode
person.name = &amp;quot;bar&amp;quot;;&lt;/pre&gt;
        &lt;/blockquote&gt;

        &lt;p&gt;Note the line highlighted in bold. Setting the “writable” property descriptor to “false” makes the “name” property of the “person” object read-only. Attempts to assign to this property will be silently ignored in unrestricted mode but causes a “TypeError” to be thrown in strict mode.&lt;/p&gt;
      &lt;/li&gt;

      &lt;li&gt;&lt;em&gt;Changing configuration of a non-configurable property:&lt;/em&gt; 

        &lt;blockquote&gt;
          &lt;pre class="prettyprint"&gt;&amp;quot;use strict&amp;quot;;
var person = Object.create({}, {
    name: {
        value: &amp;quot;foo&amp;quot;,
        writable: false,
        &lt;strong&gt;configurable: false&lt;/strong&gt;,
        enumerable: true
    }
});

// TypeError: Cannot redefine non-configurable property 'name'
Object.defineProperty(person, &amp;quot;name&amp;quot;, {
    value: &amp;quot;bar&amp;quot;,
    writable: true,
    configurable: true,
    enumerable: true
});&lt;/pre&gt;
        &lt;/blockquote&gt;

        &lt;p&gt;Here we attempted to change the property descriptor on a non-configurable object. Again, an error that would have gone unnoticed in unrestricted mode results in a “TypeError” being thrown in strict mode.&lt;/p&gt;
      &lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;h4&gt;Writing to read-only accessor properties&lt;/h4&gt;

    &lt;p&gt;Writing to accessor properties that do not have a “setter” defined causes errors to be thrown instead of being silently ignored:&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;pre class="prettyprint"&gt;&amp;quot;use strict&amp;quot;;
var person = Object.create({}, {
    name: {
        get: function() {
            return &amp;quot;foo&amp;quot;;
        },
        configurable: false,
        enumerable: true
    }
});

// TypeError
person.name = &amp;quot;bar&amp;quot;;&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p&gt;Here, “name” is an accessor property that does not have a “setter” method defined. Attempts to assign a value to this property results in an error in strict mode while being quietly ignored in unrestricted mode.&lt;/p&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;h4&gt;Cannot extend non-extensible objects&lt;/h4&gt;

    &lt;p&gt;Extending a non-extensible object throws an error in strict mode instead of being silently ignored:&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;pre class="prettyprint"&gt;&amp;quot;use strict&amp;quot;;
var person = {
    name: &amp;quot;foo&amp;quot;
};
Object.preventExtensions(person);

// TypeError: Cannot create property for a non-extensible object
person.age = 10;&lt;/pre&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;h4&gt;Other sundry restrictions&lt;/h4&gt;

    &lt;p&gt;There are a few other sundry restrictions for strict mode code which are perhaps somewhat less frequently used. I have briefly reviewed them below:&lt;/p&gt;

    &lt;ol style="list-style-type: lower-latin"&gt;
      &lt;li&gt;
        &lt;p&gt;Numeric constants are no longer interpreted as having an octal base if you put a leading zero.&lt;/p&gt;
      &lt;/li&gt;

      &lt;li&gt;
        &lt;p&gt;Variable/function instantiations in strict mode “eval” code occur in an environment that is local to the “eval” code and not in the environment of the calling code. This means that “eval” code cannot introduce new identifiers in the caller’s execution context/scope.&lt;/p&gt;
      &lt;/li&gt;

      &lt;li&gt;
        &lt;p&gt;“arguments” is immutable, i.e., you cannot arbitrarily extend the “arguments” object by tacking on your own properties to it. Now why anyone would even want to do this is puzzling to me but it must have been happening often enough for Ecma to take the effort to specify that you can no longer do it in strict mode!&lt;/p&gt;
      &lt;/li&gt;

      &lt;li&gt;
        &lt;p&gt;“arguments.callee” and “arguments.caller” are not available in strict functions.&amp;#160; I cannot say that I am completely happy with this particular restriction!&lt;/p&gt;
      &lt;/li&gt;

      &lt;li&gt;
        &lt;p&gt;Creating duplicate property definitions on an object is not allowed in strict mode code. The following snippet for instance, produces an error in strict mode:&lt;/p&gt;

        &lt;blockquote&gt;
          &lt;pre class="prettyprint"&gt;&amp;quot;use strict&amp;quot;;
var o = Object.create({}, {
    name: {
        value: &amp;quot;foo&amp;quot;
    },
    name: {
        value: &amp;quot;bar&amp;quot;
    }
});&lt;/pre&gt;
        &lt;/blockquote&gt;

        &lt;p&gt;This code throws up a “SyntaxError” with the message, “&lt;em&gt;Multiple definitions of a property not allowed in strict mode&lt;/em&gt;”. In unrestricted mode, “o.name” would have the value “bar”.&lt;/p&gt;
      &lt;/li&gt;

      &lt;li&gt;
        &lt;p&gt;Calling “delete” on an ES5 property which has its “configurable” property set to “false” results in an error being thrown in strict mode. This is a variation on the restriction discussed in point 4 above.&lt;/p&gt;
      &lt;/li&gt;

      &lt;li&gt;
        &lt;p&gt;The JavaScript “with” statement is not allowed in strict mode code.&lt;/p&gt;
      &lt;/li&gt;

      &lt;li&gt;
        &lt;p&gt;It is not allowed to create functions with duplicate parameter names in strict mode. Again, it defies logic as to why anyone would want to do this but there it is!&lt;/p&gt;
      &lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;Some best practices&lt;/h3&gt;

&lt;p&gt;Here are some things that you should perhaps consider while writing code that uses strict mode:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;Given that “strict mode” is a fairly recent phenomenon, unless all your users have been conscientiously updating their favorite browser to a new version, chances are high that you will have some percentage of visitors to your web app who are running a JS engine that does not understand “strict mode”. This means that basically all of your code is going to run in unrestricted mode regardless of whether or not you’ve used the strict mode directive. It becomes important therefore to &lt;u&gt;always test your code in unrestricted mode and make sure that everything is still peachy&lt;/u&gt;.&lt;/p&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;p&gt;Now, even if a major chunk of your end users are on browsers that don’t support strict mode it still makes sense to use strict mode in your development environment because a large part of strict mode is about enforcing JavaScript development best practices and you can benefit from automated enforcement at least during development. Just make sure that you test everything in unrestricted mode before going live!&lt;/p&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;p&gt;Enable strict mode in small increments instead of a one-shot quick fix. If you have a 3000 line JS file for instance, it is probably not wise to simply add the &lt;code&gt;&amp;quot;use strict&amp;quot;;&lt;/code&gt; directive at the top of the file as the semantic differences between the two modes can potentially result in subtle unforeseen bugs. Do it in smaller chunks at a function level and certainly use it with abandon for new code that you write.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;I’d encourage you to experiment and read up on strict mode. In my opinion, this is one of the best features introduced as part of ES5. Here are some resources that you are likely to find useful:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href="http://bit.ly/qOpOa7" target="_blank"&gt;IE10 Platform Preview developer guide documentation on strict mode&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://bit.ly/opO8bw" target="_blank"&gt;Strict mode demo on IE test drive&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://hacks.mozilla.org/2011/01/ecmascript-5-strict-mode-in-firefox-4/" target="_blank"&gt;Article on ES5 strict mode in Firefox 4&lt;/a&gt; – has good information about strict mode in general &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://www.ecma-international.org/publications/standards/Ecma-262.htm" target="_blank"&gt;The venerable ES5 spec&lt;/a&gt; – doesn’t exactly make for exhilarating reading but nothing like quoting the spec to nail an argument! &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With that we come to a close of the two part series on JavaScript strict mode. What do you folks think about this feature? Feel free to let me know what you think by leaving a comment.&lt;/p&gt;  </content></entry><entry><title>On JavaScript strict mode</title><link href="http://blogorama.nerdworks.in/entry-OnJavaScriptstrictmode.aspx" rel="alternate" type="text/html" /><id>http://blogorama.nerdworks.in/comment.aspx?entryID=58</id><updated>2011-09-19T08:26:37Z</updated><published>2011-09-01T02:50:25Z</published><content type="html">&lt;p&gt;ECMAScript version 5 is the latest revision of the ECMAScript programming language ratified for widespread adoption by &lt;a href="http://www.ecma-international.org/" target="_blank"&gt;Ecma International&lt;/a&gt; – the standards body responsible for figuring out what goes into the language. If you’re wondering what exactly ECMAScript is and why you should be interested, it turns out that ECMAScript is &lt;i&gt;standardese &lt;/i&gt;for a language that the rest of the world knows as JavaScript. Strictly speaking (no pun on title intended) JavaScript and ECMAScript aren’t identical. JavaScript is a dialect of ECMAScript but the differences are mostly negligible and are largely there for historical backward compatibility reasons. ECMAScript 5 (henceforth referred to as ES5) brings a suite of interesting features to the table, many of which have as their goal, the introduction of greater programming discipline to the language.&lt;/p&gt;  &lt;p&gt;In this post (and over the next few posts), we review one such feature which directly addresses some of the &lt;a href="http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742" target="_blank"&gt;more notorious parts&lt;/a&gt; of the language. This new feature is known as “strict mode”, which briefly, is a whole new execution mode for JavaScript that causes the execution engine to run code with slightly different semantics.&lt;/p&gt;  &lt;h3&gt;What is strict mode?&lt;/h3&gt;  &lt;p&gt;“Strict mode” is a way of causing the runtime engine to interpret and execute JavaScript with different semantics than what one sees with unrestricted code. Code running in strict mode has the following characteristics:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Excludes some syntactic and semantic features, i.e., you can’t do some things that you are allowed to do otherwise &lt;/li&gt;    &lt;li&gt;Modifies semantics of some features, i.e., same code runs differently in strict mode compared to what happens in unrestricted mode &lt;/li&gt;    &lt;li&gt;An expanded list of scenarios that cause errors to be raised instead of them being silently ignored or running with assumed intent &lt;/li&gt;    &lt;li&gt;Applies to specific code units – i.e., you cannot have strict mode apply to all your .js files at one shot (unless you concatenate all of them of course, in which case its one code unit as far as the runtime is concerned) &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;The basic rationale behind strict mode is the introduction of some runtime enforced discipline to JavaScript development. I have always felt that JavaScript is far too dynamic for its own good and in my opinion, strict mode tries to address some of that excessive dynamism. Many of the tricky parts of the language that required programmer discipline are now enforced by the engine when you mark a particular code segment as “strict”. Can you spot the bug in the following snippet? With “strict mode” turned on, the runtime will!&lt;/p&gt;  &lt;blockquote&gt;   &lt;pre class="prettyprint"&gt;function findProduct(numbers) {
    var product = 0,
        len = numbers.length;
    for(var i = 0; i &amp;lt; len; ++i) {
        prodct = product * numbers[i];
    }
    return product;
}&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;h3&gt;Browser support&lt;/h3&gt;

&lt;p&gt;Pretty much all modern browsers support strict mode in their respective JavaScript engines. On Internet Explorer (IE) strict mode is available from version 10 onwards. You can download the latest platform preview of IE10 from the &lt;a href="http://bit.ly/npkR2M"&gt;IE test drive site&lt;/a&gt;. All the samples in this article have been tested on IE10 platform preview 2 (IE10 PP2) using a JavaScript &lt;a href="http://blogorama.nerdworks.in/entry-JavaScriptevalconsole.aspx" target="_blank"&gt;eval console&lt;/a&gt; I had put together sometime back. Selected samples have been tested on &lt;i&gt;Google Chrome 14&lt;/i&gt; and &lt;i&gt;Firefox 7 beta&lt;/i&gt; as well.&lt;/p&gt;

&lt;h3&gt;Strict mode contexts&lt;/h3&gt;

&lt;p&gt;Running a piece of JavaScript under strict mode is simplicity itself. Here’s an example:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="prettyprint"&gt;&amp;quot;use strict&amp;quot;;
alert(&amp;quot;Look ma! Strict mode!&amp;quot;);&lt;/pre&gt;
&lt;/blockquote&gt;

&lt;p&gt;The nice thing here is that this is perfectly valid ECMAScript 3 code as well (ES3 is the previous edition of ECMAScript. What happened to ES4? It &lt;a href="http://en.wikipedia.org/wiki/ECMAScript#Versions" target="_blank"&gt;went the way of the dodo!&lt;/a&gt;). An ES3 JavaScript engine will simply ignore the noop line and proceed with running the rest of the script. In fact, this sort of syntactic backward compatibility with ES3 has been a key design goal for ES5 and a surprisingly large part of the ES5 specification can be implemented completely in ES3 JavaScript. Strict mode however, is an example of an ES5 feature that perhaps cannot be implemented purely in ES3 JavaScript without additional support from the runtime.&lt;/p&gt;

&lt;p&gt;The following kinds of JavaScript code can be made to run under strict mode:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;h4&gt;Global code&lt;/h4&gt;

    &lt;p&gt;This is basically executable code that you enter inside a &lt;code&gt;script&lt;/code&gt; tag. For example:&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;pre class="prettyprint"&gt;&amp;lt;script&amp;gt;
  &amp;quot;use strict&amp;quot;;
  // global strict mode code here
&amp;lt;/script&amp;gt;&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p&gt;Note that with HTML5, there is no longer a need to add the type attribute for script tags.&lt;/p&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;h4&gt;Eval code&lt;/h4&gt;

    &lt;p&gt;Eval code that has the strict mode directive prefix:&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;pre class="prettyprint"&gt;eval(&amp;quot;'use strict'; // strict code here&amp;quot;);&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p&gt;Or is invoked from strict mode code:&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;pre class="prettyprint"&gt;&amp;quot;use strict&amp;quot;;
eval(&amp;quot;// strict code here&amp;quot;);&lt;/pre&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;h4&gt;Function code&lt;/h4&gt;

    &lt;p&gt;Functions that have the strict mode directive prefixed before the rest of the code (putting the directive anywhere else doesn’t count):&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;pre class="prettyprint"&gt;function foo() {
    &amp;quot;use strict&amp;quot;;
    // strict code here
}&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p&gt;Functions declared in strict mode code inherit the strictness:&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;pre class="prettyprint"&gt;function foo() {
    &amp;quot;use strict&amp;quot;;
    var bar = function () {
        // strict code here
    };
    bar();
}&lt;/pre&gt;
    &lt;/blockquote&gt;

    &lt;p&gt;Note that the latter case is particularly relevant when you are defining callbacks for various event handlers. Also, note that strictness does not extend across call stacks. Here’s an example:&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;pre class="prettyprint"&gt;function foo() {
    // not strict mode even though
    // foo is being invoked from a
    // &amp;quot;strict&amp;quot; function
}

function bar() {
    &amp;quot;use strict&amp;quot;;
    foo();
}

bar();&lt;/pre&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In the &lt;a href="http://blogorama.nerdworks.in/entry-JavaScriptstrictmoderestrictio.aspx" target="_blank"&gt;next post&lt;/a&gt; we’ll start taking a look at some of the restrictions that ES5 strict mode imposes on the language and how they help you write better JavaScript.&lt;/p&gt;  </content></entry></feed>
