<?xml version="1.0" encoding="utf-8"?>

<feed xmlns="http://www.w3.org/2005/Atom">
    <title type="text">Adequately Good</title>
    <subtitle type="html">decent programming advice</subtitle>
    <updated>2014-04-14T10:38:21-07:00</updated>
    <id>tag:example.org,2003:3</id>
    <link rel="alternate" type="text/html" hreflang="en" href="http://www.adequatelygood.com/"/>
    <link rel="self" type="application/atom+xml" href="http://www.adequatelygood.com/feeds/atom.xml" />
    <rights>Copyright (c) 2013, Ben Cherry</rights>

    <generator uri="http://www.adequatelygood.com" version="">
        Adequately Good
    </generator>

    
    <entry>
        <title>Replacing `setTimeout` Globally</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/Replacing-setTimeout-Globally.html"/>
        <id>http://www.adequatelygood.com/2011/4/Replacing-setTimeout-Globally</id>
        <updated>2011-04-07T00:00:00-07:00</updated>
        <published>2011-04-07T00:00:00-07:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;p&gt;Sometimes, you might want to overwrite built-in global methods like &lt;code&gt;setTimeout&lt;/code&gt; and &lt;code&gt;setInterval&lt;/code&gt;. If you try, you might find that it&amp;#8217;s much harder than you think to accomplish this in every browser, particularly if you ever want to find the originals again. After a lot of painful experimentation, I think I have a definitive solution that works in all browsers with minimal side-effects.&lt;/p&gt;

&lt;h2 id=&#39;failed_approaches&#39;&gt;Failed Approaches&lt;/h2&gt;

&lt;p&gt;I started out with the simple approach:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;setTimeout = function() {};
// or
window.setTimeout = function() {};&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This seems to work in most browsers. However, Internet Explorer 8 and below are not appreciative of this technique. In the first case, IE will actually throw an exception saying &lt;code&gt;&amp;quot;Object doesn&amp;#39;t support this action&amp;quot;&lt;/code&gt;. The second option works, but it will only affect the value of &lt;code&gt;window.setTimeout&lt;/code&gt;, leaving plain old global &lt;code&gt;setTimeout&lt;/code&gt; alone. This is workable, but not ideal. Time to look for another solution.&lt;/p&gt;

&lt;h3 id=&#39;another_attempt&#39;&gt;Another Attempt&lt;/h3&gt;

&lt;p&gt;After speaking with @jcummins about this, we thought about using the &lt;code&gt;var&lt;/code&gt; keyword, and seeing if that would help. So that brings me to my next approach:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var setTimeout = function() {};&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The good news is that this works across the board! Both &lt;code&gt;setTimeout&lt;/code&gt; and &lt;code&gt;window.setTimeout&lt;/code&gt; now reference my new function, in all browsers, and you can safely do any assignments needed, no exceptions thrown. But now the question is, where did the original &lt;code&gt;setTimeout&lt;/code&gt; go? It&amp;#8217;s not an easy thing to find.&lt;/p&gt;

&lt;p&gt;You might try something like the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var temp = setTimeout,
    setTimeout = function() {};&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now, you might expect &lt;code&gt;temp&lt;/code&gt; to contain the original &lt;code&gt;setTimeout&lt;/code&gt;, but it unfortunately will come up &lt;code&gt;undefined&lt;/code&gt;. This is due to &lt;a href=&#39;http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting&#39;&gt;JavaScript hoisting&lt;/a&gt;. I even tried &lt;code&gt;var temp = window.setTimeout&lt;/code&gt; first, but the property on &lt;code&gt;window&lt;/code&gt; was immediately hoisted on top.&lt;/p&gt;

&lt;p&gt;So, I resolved to find another way to get at the original value. After some digging, I discovered a reference to the original &lt;code&gt;setTimeout&lt;/code&gt; on the window&amp;#8217;s prototype, which you can access at &lt;code&gt;window.constructor.prototype.setTimeout&lt;/code&gt;. Alright! Things are looking good. Unfortunately, things quickly went downhill.&lt;/p&gt;

&lt;p&gt;1. In most browsers, &lt;code&gt;window&lt;/code&gt; is constructed by a function named &lt;code&gt;&amp;quot;DOMWindow&amp;quot;&lt;/code&gt;. That is, &lt;code&gt;window.constructor.name === &amp;quot;DOMWindow&amp;quot;&lt;/code&gt;. However, in Safari this is not the case, the &lt;code&gt;constructor&lt;/code&gt; property instead references &lt;code&gt;Object&lt;/code&gt;. We don&amp;#8217;t have a way to access &lt;code&gt;DOMWindow&lt;/code&gt; directly, so we can&amp;#8217;t get to the prototype. Luckily, we can use the ECMAScript 5 &lt;code&gt;__proto__&lt;/code&gt; property, and find &lt;code&gt;setTimeout&lt;/code&gt; at &lt;code&gt;window.__proto__.setTimeout&lt;/code&gt;. So my catch-all became &lt;code&gt;(window.__proto__ || window.constructor.prototype).setTimeout&lt;/code&gt;. 2. It turns out Opera has the same problem as Safari, and we can&amp;#8217;t access the correct prototype at &lt;code&gt;window.constructor.prototype&lt;/code&gt;. However, it also doesn&amp;#8217;t seem able to access it at &lt;code&gt;window.__proto__&lt;/code&gt;, leaving us low on options. More on that in a bit. 3. IE7 and below don&amp;#8217;t have a &lt;code&gt;constructor&lt;/code&gt; &lt;em&gt;or&lt;/em&gt; a &lt;code&gt;__proto__&lt;/code&gt; property on &lt;code&gt;window&lt;/code&gt;, and there doesn&amp;#8217;t seem to be any other way to get direct access to the window&amp;#8217;s prototype.&lt;/p&gt;

&lt;p&gt;At this point, I declared searching for the original copies of &lt;code&gt;setTimeout&lt;/code&gt; outside of the global scope a lost cause, and went back to the drawing board. You could, in theory, instantiate a new &lt;code&gt;&amp;lt;iframe&amp;gt;&lt;/code&gt; and copy &lt;code&gt;setTimeout&lt;/code&gt; from it, but I didn&amp;#8217;t want to introduce that much overhead.&lt;/p&gt;

&lt;h2 id=&#39;a_solution&#39;&gt;A Solution&lt;/h2&gt;

&lt;p&gt;At this point, I figured the best solution would be to circumvent JavaScript&amp;#8217;s hoisting rules. As we know, hoisting occurs immediately after entering an execution context. So, to dodge it, we&amp;#8217;d have to introduce a second execution context. You could do this easily in HTML:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;script&amp;gt;
  var temp = setTimeout;
&amp;lt;/script&amp;gt;
&amp;lt;script&amp;gt;
  var setTimeout = function() {};
&amp;lt;/script&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;However, I was looking for a pure JS solution. So, after some soul-searching, I decided I&amp;#8217;d pull out &lt;code&gt;eval&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var temp = setTimeout;
eval(&amp;quot;var setTimeout;&amp;quot;);
setTimeout = function() {};&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Done and done. The most flexible thing to do is just to quickly fix the inconsistency where IE doesn&amp;#8217;t allow you to overwrite &lt;code&gt;setTimeout&lt;/code&gt; directly, and then proceed to do as you need. Here&amp;#8217;s some quick sample code, though you could easily adapt this better into your own project:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var __originals = {
  st: setTimeout,
  si: setInterval,
  ct: clearTimeout,
  ci: clearInterval
};

eval(&amp;quot;var setTimeout, setInterval, clearTimeout, clearInterval;&amp;quot;);

setTimeout = __originals.st;
setInterval = __originals.si;
clearTimeout = __originals.ct;
clearInterval = __originals.ci;

__originals = undefined;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This snippet will smooth out that inconsistency in Internet Explorer, and allow you to proceed with whatever overrides or replacements you need on those methods. No need to use &lt;code&gt;var&lt;/code&gt; again in the future, so you can avoid the hoisting pains. I&amp;#8217;ve tested this in IE6, 7, 8, and 9, as well as Chrome, Safari, Firefox 3/4, and Opera, all on Mac and Windows, and it&amp;#8217;s rock-solid.&lt;/p&gt;

&lt;h2 id=&#39;update_a_better_solution&#39;&gt;Update! A Better Solution&lt;/h2&gt;

&lt;p&gt;After further investigation, helped by many including @angusTweets and @kangax, I have fully uncovered the problem in IE, with an extremely simple and safe solution.&lt;/p&gt;

&lt;p&gt;It turns out that the problem is not always present. For instance, open up a brand new, blank window in IE7 or IE8, and try the following in the JS console:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;window.setTimeout = 1;
setTimeout; // 1
setTimeout = 2; // 2&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But then, try this instead (again, in a fresh window):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;setTimeout;
window.setTimeout = 1;
setTimeout; // {...}
window.setTimeout; // 1
setTimeout = 1; // Error&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So what&amp;#8217;s going on here? Well, I&amp;#8217;ve come up with a solid theory.&lt;/p&gt;

&lt;p&gt;Initially, the property &lt;code&gt;setTimeout&lt;/code&gt; exists on the &lt;code&gt;prototype&lt;/code&gt; of &lt;code&gt;window&lt;/code&gt;, not on &lt;code&gt;window&lt;/code&gt; itself. So, when you ask for &lt;code&gt;window.setTimeout&lt;/code&gt;, it actually traverses one step on the prototype chain to resolve the reference. Similarly, when you ask for &lt;code&gt;setTimeout&lt;/code&gt;, it traverses down the scope chain, then to &lt;code&gt;window&lt;/code&gt;, then down the prototype chain to resolve the reference.&lt;/p&gt;

&lt;p&gt;I suspect that IE has a built-in optimization where it automatically caches the resolution of implied globals that are discovered all the way down on the prototype of the global object. It would have good reason to do so, as these are commonly requested references, and traversing that chain is costly. However, it must be setting this reference as read-only, since it&amp;#8217;s just a caching optimization. This has the unfortunate side-effect of causing an exception to be thrown when attempting to assign to the reference by using it as an lvalue. The only way to kill this new reference is by using &lt;code&gt;var&lt;/code&gt; in the global scope, but this puts us in the hoisting problem. What to do?&lt;/p&gt;

&lt;p&gt;Assuming this theory is correct, there&amp;#8217;s actually a simple solution. To prevent this &amp;#8220;optimization&amp;#8221;, we simply need to move the reference one step up the chain, directly onto &lt;code&gt;window&lt;/code&gt;. Luckily, this is quite easy:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;window.setTimeout = window.setTimeout;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That&amp;#8217;s it! Assuming you&amp;#8217;ve done this &lt;strong&gt;before&lt;/strong&gt; any reference to &lt;code&gt;setTimeout&lt;/code&gt; on its own, this will move the reference and completely avoid this problem. You may now safely assign to &lt;code&gt;setTimeout&lt;/code&gt; without using &lt;code&gt;var&lt;/code&gt;. This works because &lt;code&gt;window.setTimeout&lt;/code&gt;, when used as an lvalue (on the left side of the assignment), does not walk the prototype chain, but on the right side, it does. So this will always pull a property out of the prototype chain and put it right on the object. Incidentally, IE exhibits the same problem with every other property on the window prototype, and the same solution will fix them. You can easily find the other properties, but a few of them are &lt;code&gt;alert&lt;/code&gt;, &lt;code&gt;attachEvent&lt;/code&gt;, &lt;code&gt;scrollTo&lt;/code&gt;, &lt;code&gt;blur&lt;/code&gt;, and many others.&lt;/p&gt;

&lt;p&gt;This solution has been tested in all browsers, has no side effects, and is wonderfully simple. It&amp;#8217;s always nice when things work out that way.&lt;/p&gt;
            </div>
        </content>
    </entry>
    
    <entry>
        <title>Thoughts on the Hashbang</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/Thoughts-on-the-Hashbang.html"/>
        <id>http://www.adequatelygood.com/2011/2/Thoughts-on-the-Hashbang</id>
        <updated>2011-02-11T00:00:00-08:00</updated>
        <published>2011-02-11T00:00:00-08:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;p&gt;There&amp;#8217;s &lt;a href=&#39;http://isolani.co.uk/blog/javascript/BreakingTheWebWithHashBangs&#39;&gt;been&lt;/a&gt; &lt;a href=&#39;http://adactio.com/journal/4346/&#39;&gt;a&lt;/a&gt; &lt;a href=&#39;http://simonwillison.net/tags/hashbanghell/&#39;&gt;lot&lt;/a&gt; &lt;a href=&#39;http://www.tbray.org/ongoing/When/201x/2011/02/09/Hash-Blecch&#39;&gt;of&lt;/a&gt; &lt;a href=&#39;http://groups.google.com/group/jsmentors/browse_thread/thread/e493573c4de5d5f9?hl=en_US&#39;&gt;discussion&lt;/a&gt; this week about the &amp;#8220;hashbang&amp;#8221;, that ugly little bit you find in the middle of URLs like this one: &lt;a href=&#39;http://twitter.com/#!/ded/status/18308450276&#39;&gt;http://twitter.com/#!/ded/status/18308450276&lt;/a&gt;. I wanted to provide a rebuttal to the arguments that the hashbang is bad for the Web, based on a lot of discussions we&amp;#8217;ve been having inside Twitter since the #newtwitter project began last summer, and have continued right up until today.&lt;/p&gt;

&lt;h2 id=&#39;its_not_about_the_hashbang&#39;&gt;It&amp;#8217;s Not About the Hashbang&lt;/h2&gt;

&lt;p&gt;The hashbang is in the unfortunate position of being the messenger of a big change that&amp;#8217;s been slowly occurring on the Web in the past few years, and will only continue to pick up steam: many Web domains are now serving &lt;a href=&#39;http://itsnat.sourceforge.net/php/spim/spi_manifesto_en.php&#39;&gt;desktop-class applications&lt;/a&gt; via HTTP, instead of traditional Web sites. For instance, twitter.com is no longer a collection of Web pages that represent a Web site, but is simply an application that you happen to launch by pointing a browser at &lt;a href=&#39;http://twitter.com&#39;&gt;http://twitter.com&lt;/a&gt;*. This has many wide-reaching implications, and the hashbang is merely a side-effect. In this way, the hashbang is an easy-to-hate straw-man, whereas the real debate to be had is about this shift towards applications.&lt;/p&gt;

&lt;h2 id=&#39;why_applications_on_the_web&#39;&gt;Why Applications on the Web?&lt;/h2&gt;

&lt;p&gt;Services such as Twitter, Flickr, Facebook, and others have every reason to build rich applications. An application allows an experience that is faster, more seamless, and much better for users than traditional Web sites. However, we do not have to choose to host our apps on the Web, and could easily use other options, such as building a native OS application, or using another cross-platform platform such as Adobe AIR. We all choose Web applications however, because the Web is ubiquitous, well-understood, and mostly superior to other application delivery options.&lt;/p&gt;

&lt;p&gt;We get URLs in our Web applications as a legacy of Web sites, and this feature is unique to this class of applications. The power of URLs bring benefits like bookmarks, sharing of application states for free, and search engine indexing. Unfortunately, supporting a standard URL structure for this type of application is not possible in current browsers, without using the URL hash. So, we use the URL hash to take advantage of this sort of thing, but not because we believe our application to be a traditional Web site. We do lose indexability and some other benefits of HTTP we may otherwise have, but these are not losses to our application, since we did not have to use a URL at all. Google has &lt;a href=&#39;http://googlewebmastercentral.blogspot.com/2009/10/proposal-for-making-ajax-crawlable.html&#39;&gt;thankfully provided&lt;/a&gt; &lt;a href=&#39;http://code.google.com/web/ajaxcrawling/docs/getting-started.html&#39;&gt;an implementation for crawling applications&lt;/a&gt;, based on the hashbang, which brings search engine indexing to the URL hash, and is easy enough to implement.&lt;/p&gt;

&lt;h2 id=&#39;the_tradeoff&#39;&gt;The Tradeoff&lt;/h2&gt;

&lt;p&gt;We&amp;#8217;ve made a tradeoff, however, in making twitter.com into an application using the hash, which is that it now cannot be both an app and a site at the same time. This capability might not sound compelling, but it is. For instance, browsers without JavaScript cannot access content that has been shared using the URL hash, since that is a marker to the JS app, not to a Web page. In a perfect world, we would have been able to use the original URL structure with the hashes for our application, and served both the site and the app simultaneously. This would be the absolute best thing for users of all kinds, and this debate would not be happening.&lt;/p&gt;

&lt;p&gt;There is hope on the horizon, in the form of the HTML5 History API. This new browser feature will allow developers to change the entire URL path and query string without incurring a page refresh. By using this, we could drop the hash, and get all the benefits of traditional Web sites with all the benefits of a desktop-class application. Support for this has been in Chrome and Safari for some time (albeit with &lt;a href=&#39;https://bugs.webkit.org/show_bug.cgi?id=42940&#39;&gt;a bug we found&lt;/a&gt; (now fixed)), and will arrive in Firefox 4. Internet Explorer currently has no plans to implement this in IE9, which is a shame. Had it not been for the bug we found, we would have shipped #newtwitter with HTML5 History on day one (and in fact, the integration is already built).&lt;/p&gt;

&lt;h2 id=&#39;the_hashbang_is_a_good_thing&#39;&gt;The Hashbang is a Good Thing&lt;/h2&gt;

&lt;p&gt;It&amp;#8217;s not perfect. It&amp;#8217;s not pretty (despite what Google says). But the hashbang is useful. Users benefit from the trend towards full-fledged applications, with increased speed and functionality. URLs are not necessary in this context, but we provide them (via the hash) because they bring tangible benefits for applications. The hashbang also brings a tangible benefit. Someday, we will hopefully be rid of the thing, when HTML5 History (or &lt;a href=&#39;http://www.adequatelygood.com/2010/7/Saner-HTML5-History-Management&#39;&gt;something like it&lt;/a&gt;) is standard in all browsers. The Web application is not going anywhere, and the hash is a fact of life.&lt;/p&gt;
&lt;span class=&#39;note&#39;&gt;&lt;em&gt;* Technically, twitter.com does still host a Web site.  For instance, &lt;a href=&#39;http://twitter.com/jobs&#39;&gt;twitter.com/jobs&lt;/a&gt; is a normal Web page, as is &lt;a href=&#39;http://twitter.com/bcherry&#39;&gt;twitter.com/bcherry&lt;/a&gt; when viewed logged-out.  We have, however, begun serving an application to logged-in visitors.&lt;/em&gt;&lt;/span&gt;
            </div>
        </content>
    </entry>
    
    <entry>
        <title>Saner HTML5 History Management</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/Saner-HTML5-History-Management.html"/>
        <id>http://www.adequatelygood.com/2010/7/Saner-HTML5-History-Management</id>
        <updated>2010-07-25T00:00:00-07:00</updated>
        <published>2010-07-25T00:00:00-07:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;h2 id=&#39;hashchange&#39;&gt;Hashchange&lt;/h2&gt;

&lt;p&gt;This event is quite simple. Whenever the &lt;code&gt;window.location.hash&lt;/code&gt; property changes, by following a link, setting the property, editing the URL bar, or using back/forward to move through browser history, the &amp;#8220;hashchange&amp;#8221; event is fired from the window. Using it is really easy:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;window.onhashchange = function() {
	alert(&amp;quot;hash changed!&amp;quot;);
};
window.location.hash = Math.random(); // alerts &amp;quot;hash changed!&amp;quot;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This feature is implemented in recent versions of all major browsers. In older browsers like Internet Explorer 6 and 7, you can easily provide it by polling the hash property on an interval, and manually firing an event when it changes. This is easy to build into a jQuery plugin, which &lt;a href=&#39;http://benalman.com/&#39;&gt;Ben Alman&lt;/a&gt; did in the robust &lt;a href=&#39;http://benalman.com/projects/jquery-hashchange-plugin/&#39;&gt;jquery.hashchange.js plugin&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&#39;history_management&#39;&gt;History Management&lt;/h2&gt;

&lt;p&gt;This feature is a bit more complex. Browsers that support it add a &lt;code&gt;window.history&lt;/code&gt; object, with the following properties:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;window.history.back()&lt;/code&gt; and &lt;code&gt;window.history.forward()&lt;/code&gt;, which provide programmatic interfaces to browser back and forward functions.&lt;/li&gt;

&lt;li&gt;&lt;code&gt;window.history.pushState(stateObj, title, url)&lt;/code&gt;. This method pushes a new entry into the browser history, which then becomes the browser&amp;#8217;s current state. You can provide any JSON-stringifiable object to send with it, and the browser will provide that object again when you navigate to that point (more on that in a bit). More importantly, if you provide a URL, the browser will change the URL displayed in the address bar, without reloading the page. The new URL must be on the same domain, but you can change the rest of it, which is the &lt;code&gt;window.location.pathname&lt;/code&gt; and &lt;code&gt;window.location.hash&lt;/code&gt;. Changing the URL in this way will not trigger a &amp;#8220;hashchange&amp;#8221; event, though.&lt;/li&gt;

&lt;li&gt;&lt;code&gt;window.history.replaceState(stateObj, title, url)&lt;/code&gt;. This is just like &lt;code&gt;window.history.pushState&lt;/code&gt;, except that the current browser state is removed from the history, so you cannot hit &amp;#8220;back&amp;#8221; to return to it.&lt;/li&gt;

&lt;li&gt;&lt;code&gt;window.onpopstate&lt;/code&gt;. This event is fired whenever a state object is removed from the browser history, which occurs on browser &amp;#8220;back&amp;#8221; or &amp;#8220;forward&amp;#8221;. State objects are persisted on the user&amp;#8217;s hard disk between sessions, which is a nice feature. The object passed into a call to &lt;code&gt;pushState&lt;/code&gt; or &lt;code&gt;replaceState&lt;/code&gt; is provided as the &lt;code&gt;state&lt;/code&gt; property on the event object in the &amp;#8220;popstate&amp;#8221; event.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This feature is implemented in the latest versions of WebKit, which includes Safari and Chrome. Additionally, the Firefox 4 betas include support for this.&lt;/p&gt;

&lt;h2 id=&#39;whats_the_use_case&#39;&gt;What&amp;#8217;s the Use Case?&lt;/h2&gt;

&lt;p&gt;The new history management stuff is very promising, because it allows a web application to live across many physical URLs, but be run in a single instance. This is important for certain kinds of applications, where using hashes is not universally suitable.&lt;/p&gt;

&lt;p&gt;For instance, at Twitter, we currently update your URL hash as you navigate around the application, to make bookmarkable pages like &lt;a href=&#39;http://twitter.com/#replies&#39;&gt;http://twitter.com/#replies&lt;/a&gt;. However, we force a full page load for certain pages, most notably profile pages (e.g. &lt;a href=&#39;http://twitter.com/bcherry&#39;&gt;http://twitter.com/bcherry&lt;/a&gt;) and permalink pages (e.g. &lt;a href=&#39;http://twitter.com/bcherry/status/18966802499&#39;&gt;http://twitter.com/bcherry/status/18966802499&lt;/a&gt;). This is so that those URLs can be copied from the address bar and posted on the web.&lt;/p&gt;

&lt;p&gt;We want to make sure that users without JavaScript and search engine bots crawling links to our site will get the correct page from the server (since the browser does not send a hash along to the server). This would not be possible if those URLs used hashes. Unfortunately, this means the application is slower, because a full page load is needed going into and out of those locations.&lt;/p&gt;

&lt;p&gt;This is where HTML5 History Management could be useful.&lt;/p&gt;

&lt;h2 id=&#39;so_whats_the_problem&#39;&gt;So What&amp;#8217;s the Problem?&lt;/h2&gt;

&lt;p&gt;Unfortunately, the existing implementation of history management is not useful, and not in the spirit of the web.&lt;/p&gt;

&lt;p&gt;Our web applications should be built to respond to a URL. Both the client and server versions of an application should understand a shared URL structure, and know how to present the same page to the browser that reflects that URL.&lt;/p&gt;

&lt;p&gt;Allowing developers to store extra state information in the browser history is missing the point. The only thing stored in history should be a URL, and the browser can associate a title with it if it chooses.&lt;/p&gt;

&lt;p&gt;This is RESTful design, mirrored on client and server. Modern browsers can support changing the URL without reloading the page from the server, and older ones can continue to hit the server every time.&lt;/p&gt;

&lt;p&gt;In this way, we can build applications that degrade correctly in older browsers, and when viewed by bots, while providing a faster experience for users with modern browsers.&lt;/p&gt;

&lt;h2 id=&#39;enter_pathchange&#39;&gt;Enter &amp;#8220;pathchange&amp;#8221;&lt;/h2&gt;

&lt;p&gt;Both &amp;#8220;hashchange&amp;#8221; and &lt;code&gt;pushState&lt;/code&gt;/&amp;#8221;popstate&amp;#8221; should be replaced with &amp;#8220;pathchange&amp;#8221;, which is an event that fires when the URL changes in any way. This event does not provide any information, the application should inspect the current URL to discover the state it should enter. Relative links within a page should not force page reloads, they should instead just trigger the &amp;#8220;pathchange&amp;#8221; event.&lt;/p&gt;

&lt;p&gt;It turns out that it&amp;#8217;s possible to implement this event in modern browsers now, based on the features they already have. Here&amp;#8217;s how:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Listen to &amp;#8220;hashchange&amp;#8221;, and trigger &amp;#8220;pathchange&amp;#8221; when it occurs&lt;/li&gt;

&lt;li&gt;Poll the hash in browsers without &amp;#8220;hashchange&amp;#8221; support, and trigger &amp;#8220;hashchange&amp;#8221;, which triggers &amp;#8220;pathchange&amp;#8221;&lt;/li&gt;

&lt;li&gt;With history support, listen to &amp;#8220;popstate&amp;#8221;, and trigger &amp;#8220;pathchange&amp;#8221; when it occurs&lt;/li&gt;

&lt;li&gt;With history support, intercept all relative links when they are clicked, and prevent normal navigation. Call &lt;code&gt;window.history.pushState(null, null, href)&lt;/code&gt; instead, and trigger a &amp;#8220;pathchange&amp;#8221;.&lt;/li&gt;

&lt;li&gt;Provide a helper function to make navigation to new URLs using &lt;code&gt;window.history.pushState&lt;/code&gt;, when supported, easy.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;I&amp;#8217;ve implemented all of this as a &lt;a href=&#39;http://www.bcherry.net/static/lib/js/jquery.pathchange.js&#39;&gt;jQuery plugin&lt;/a&gt; that is quite easy to use:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$(function() {
	$.pathchange.init(); // setup event listeners, etc.
	$(window).pathchange(function() {
		respondToUrl();
	}).trigger(&amp;quot;pathchange&amp;quot;);

	$.pathchange.changeTo(&amp;quot;/foo&amp;quot;);
});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I&amp;#8217;ve also created a demo page that presents &lt;a href=&#39;http://www.bcherry.net/playground/sanerhtml5history&#39;&gt;A Saner HTML5 History App&lt;/a&gt; that uses &lt;a href=&#39;http://www.bcherry.net/static/lib/js/jquery.pathchange.js&#39;&gt;jquery.pathchange.js&lt;/a&gt; under the hood. Check it out in various browsers to see the HTML5 magic at work, and be sure to use your browser &amp;#8220;back&amp;#8221; and &amp;#8220;forward&amp;#8221; buttons, and reload the page a few times.&lt;/p&gt;

&lt;p&gt;That&amp;#8217;s my take on the HTML5 history features. It&amp;#8217;s unfortunate that what the browsers are implementing is not what we really need, but it&amp;#8217;s encouraging that they do provide enough to implement what we do really need. Let me know in the comments if you agree, disagree, or have questions about my approach.&lt;/p&gt;
&lt;span class=&#39;note&#39;&gt;___Note Number One: It&#39;s also worth pointing out that I discovered a [serious bug](https://bugs.webkit.org/show_bug.cgi?id=42940) in WebKit&#39;s implementation of history management while working on this today.  In short, the &quot;popstate&quot; event is often lost when the network is occupied, which makes little sense.  [Here&#39;s a demo page with a reproducible case](http://www.bcherry.net/playground/pushstate) that I threw together.  It fires off a request to download an image which takes 1s on every &quot;popstate&quot;, which means hitting &quot;back&quot; more than once every second leads to lost history entries and an application that gets out of sync with the URL.  You could work around this by polling the URL in addition to listening to &quot;popstate&quot;, but it&#39;s not a good workaround.  Until this is fixed, you&#39;ll have to be wary of this if you ship this feature to your users, and it probably is not suitable for very complex AJAX apps.  Firefox 4 does not have the same problem.___&lt;/span&gt;&lt;span class=&#39;note&#39;&gt;___Note Number 2: This article was originally published around 4am PST on July 26th.  The author published a revision around 8pm PST the following day, to make it a little less incohorent and a little more useful.  Luckily, the author uses Git to prepare Markdown-formatted articles, so you can [view the diff](http://github.com/bcherry/adequatelygood/commit/eb688c7809e8d5f61f9ed12442d3a578d46fab97) if you&#39;d like to find out what changed.___&lt;/span&gt;
            </div>
        </content>
    </entry>
    
    <entry>
        <title>Writing Testable JavaScript</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/Writing-Testable-JavaScript.html"/>
        <id>http://www.adequatelygood.com/2010/7/Writing-Testable-JavaScript</id>
        <updated>2010-07-08T00:00:00-07:00</updated>
        <published>2010-07-08T00:00:00-07:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;p&gt;The engineering culture at Twitter requires tests. Lots of tests. I haven&amp;#8217;t had formal experience with JavaScript testing before Twitter, so I&amp;#8217;ve been learning a lot as I go. In particular, a number of patterns I used to use, write about, and encourage have turned out to be bad for writing testable code. So I thought it would be worthwhile to share a few of the most important principles I&amp;#8217;ve developed for writing testable JavaScript. The examples I provide are based on &lt;a href=&#39;http://docs.jquery.com/QUnit&#39;&gt;QUnit&lt;/a&gt;, but should be just as applicable to any JavaScript testing framework.&lt;/p&gt;

&lt;h2 id=&#39;avoid_singletons&#39;&gt;Avoid Singletons&lt;/h2&gt;

&lt;p&gt;One of my most popular posts was about using &lt;a href=&#39;http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth&#39;&gt;JavaScript Module Pattern&lt;/a&gt; to create powerful &lt;strong&gt;singletons&lt;/strong&gt; in your application. This approach can be simple and useful, but it creates problems for testing, for one simple reason: &lt;strong&gt;&lt;em&gt;singletons suffer state pollution between tests&lt;/em&gt;&lt;/strong&gt;. Rather than creating your singletons as modules, you should compose them as constructable objects, and assign a single, default instance at the global level in your application init.&lt;/p&gt;

&lt;p&gt;For example, consider the following singleton module (contrived example, of course):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var dataStore = (function() {
	var data = [];
	return {
		push: function (item) {
			data.push(item);
		},
		pop: function() {
			return data.pop();
		},
		length: function() {
			return data.length;
		}
	};
}());&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With this module, we may wish to test the &lt;code&gt;foo.bar&lt;/code&gt; method. Here&amp;#8217;s a simple QUnit test suite:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;module(&amp;quot;dataStore&amp;quot;);
test(&amp;quot;pop&amp;quot;, function() {
	dataStore.push(&amp;quot;foo&amp;quot;);
	dataStore.push(&amp;quot;bar&amp;quot;)
	equal(dataStore.pop(), &amp;quot;bar&amp;quot;, &amp;quot;popping returns the most-recently pushed item&amp;quot;);
});

test(&amp;quot;length&amp;quot;, function() {
	dataStore.push(&amp;quot;foo&amp;quot;);
	equal(dataStore.length(), 1, &amp;quot;adding 1 item makes the length 1&amp;quot;);
});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When running this test suite, the assertion in the &lt;code&gt;length&lt;/code&gt; test will fail, but it&amp;#8217;s not clear from looking at it why it should. The problem is that state has been left in &lt;code&gt;dataStore&lt;/code&gt; from the previous test. Merely re-ordering these tests will cause the &lt;code&gt;length&lt;/code&gt; test to pass, which is a clear red flag that something is wrong. We could fix this with setup or teardown that reverts the state of &lt;code&gt;dataStore&lt;/code&gt;, but that means that we need to constantly maintain our test boilerplate as we make implementation changes in the &lt;code&gt;dataStore&lt;/code&gt; module. A better approach is the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function newDataStore() {
	var data = [];
	return {
		push: function (item) {
			data.push(item);
		},
		pop: function() {
			return data.pop();
		},
		length: function() {
			return data.length;
		}
	};
}

var dataStore = newDataStore();&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now, your test suite will look like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;module(&amp;quot;dataStore&amp;quot;);
test(&amp;quot;pop&amp;quot;, function() {
	var dataStore = newDataStore();
	dataStore.push(&amp;quot;foo&amp;quot;);
	dataStore.push(&amp;quot;bar&amp;quot;)
	equal(dataStore.pop(), &amp;quot;bar&amp;quot;, &amp;quot;popping returns the most-recently pushed item&amp;quot;);
});

test(&amp;quot;length&amp;quot;, function() {
	var dataStore = newDataStore();
	dataStore.push(&amp;quot;foo&amp;quot;);
	equal(dataStore.length(), 1, &amp;quot;adding 1 item makes the length 1&amp;quot;);
});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This allows our global &lt;code&gt;dataStore&lt;/code&gt; to behave exactly as it did before, while allowing our tests to avoid polluting each other. Each test owns its own instance of a &lt;code&gt;DataStore&lt;/code&gt; object, which will be garbage collected when the test completes.&lt;/p&gt;

&lt;h2 id=&#39;avoid_closurebased_privacy&#39;&gt;Avoid Closure-based Privacy&lt;/h2&gt;

&lt;p&gt;Another pattern I used to promote is &lt;a href=&#39;http://www.crockford.com/javascript/private.html&#39;&gt;real private members in JavaScript&lt;/a&gt;. The advantage is that you can keep globally-accessible namespaces free of unnecessary references to private implementation details. However, overuse of this pattern can lead to untestable code. This is because &lt;strong&gt;&lt;em&gt;your test suite cannot access, and thus cannot test, private functions hidden in closures&lt;/em&gt;&lt;/strong&gt;. Consider the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function Templater() {
	function supplant(str, params) {
		for (var prop in params) {
			str.split(&amp;quot;{&amp;quot; + prop +&amp;quot;}&amp;quot;).join(params[prop]);
		}
		return str;
	}

	var templates = {};

	this.defineTemplate = function(name, template) {
		templates[name] = template;
	};

	this.render = function(name, params) {
		if (typeof templates[name] !== &amp;quot;string&amp;quot;) {
			throw &amp;quot;Template &amp;quot; + name + &amp;quot; not found!&amp;quot;;
		}

		return supplant(templates[name], params);
	};
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The crucial method for our &lt;code&gt;Templater&lt;/code&gt; object is &lt;code&gt;supplant&lt;/code&gt;, but we cannot access it from outside the closure of the constructor. Thus, a testing suite like QUnit cannot hope to verify that it works as intended. In addition, we cannot verify that our &lt;code&gt;defineTemplate&lt;/code&gt; method does anything without trying a &lt;code&gt;.render()&lt;/code&gt; call on the template and watching for an exception. We could simply add a &lt;code&gt;getTemplate()&lt;/code&gt; method, but then we&amp;#8217;d be adding methods to the public interface solely to allow testing, which is not a good approach. While the issues here are probably just fine in this simple example, building complex objects with important private methods will lead to relying on untestable code, which is a red flag. Here&amp;#8217;s a testable version of the above:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function Templater() {
	this._templates = {};
}

Templater.prototype = {
	_supplant: function(str, params) {
		for (var prop in params) {
			str.split(&amp;quot;{&amp;quot; + prop +&amp;quot;}&amp;quot;).join(params[prop]);
		}
		return str;
	},
	render: function(name, params) {
		if (typeof this._templates[name] !== &amp;quot;string&amp;quot;) {
			throw &amp;quot;Template &amp;quot; + name + &amp;quot; not found!&amp;quot;;
		}

		return this._supplant(this._templates[name], params);
	},
	defineTemplate: function(name, template) {
		this._templates[name] = template;
	}
};&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And here&amp;#8217;s a QUnit test suite for it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;module(&amp;quot;Templater&amp;quot;);
test(&amp;quot;_supplant&amp;quot;, function() {
	var templater = new Templater();
	equal(templater._supplant(&amp;quot;{foo}&amp;quot;, {foo: &amp;quot;bar&amp;quot;}), &amp;quot;bar&amp;quot;))
	equal(templater._supplant(&amp;quot;foo {bar}&amp;quot;, {bar: &amp;quot;baz&amp;quot;}), &amp;quot;foo baz&amp;quot;));
});

test(&amp;quot;defineTemplate&amp;quot;, function() {
	var templater = new Templater();
	templater.defineTemplate(&amp;quot;foo&amp;quot;, &amp;quot;{foo}&amp;quot;);
	equal(template._templates.foo, &amp;quot;{foo}&amp;quot;);
});

test(&amp;quot;render&amp;quot;, function() {
	var templater = new Templater();
	templater.defineTemplate(&amp;quot;hello&amp;quot;, &amp;quot;hello {world}!&amp;quot;);
	equal(templater.render(&amp;quot;hello&amp;quot;, {world: &amp;quot;internet&amp;quot;}), &amp;quot;hello internet!&amp;quot;);
});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice that our test for &lt;code&gt;render&lt;/code&gt; is really just a test that &lt;code&gt;defineTemplate&lt;/code&gt; and &lt;code&gt;supplant&lt;/code&gt; integrate correctly with each other. We&amp;#8217;ve already tested those methods in isolation, which will allow us to easily discover which components are really breaking when tests of the &lt;code&gt;render&lt;/code&gt; method fail.&lt;/p&gt;

&lt;h2 id=&#39;write_tight_functions&#39;&gt;Write Tight Functions&lt;/h2&gt;

&lt;p&gt;Tight functions are important in any language, but JavaScript presents its own reasons to do so. Much of what you do with JavaScript is done against global singletons provided by the environment, and which your test suite relies on. For instance, testing a URL re-writer will be difficult if all of your methods try to assign &lt;code&gt;window.location&lt;/code&gt;. Instead, you should &lt;strong&gt;&lt;em&gt;break your system into its logical components that decide what to do, then write short functions that actually do it&lt;/em&gt;&lt;/strong&gt;. You can test the logical functions with various inputs and outputs, and leave the final function that modifies &lt;code&gt;window.location&lt;/code&gt; untested. Provided you&amp;#8217;ve composed your system correctly, this should be safe.&lt;/p&gt;

&lt;p&gt;Here&amp;#8217;s an example URL rewriter that is not testable:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function redirectTo(url) {
	if (url.charAt(0) === &amp;quot;#&amp;quot;) {
		window.location.hash = url;
	} else if (url.charAt(0) === &amp;quot;/&amp;quot;) {
		window.location.pathname = url;
	} else {
		window.location.href = url;
	}
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The logic in this example is relatively simple, but we can imagine a more complex redirecter. As complexity grows, we will not be able to test this method without causing the window to redirect, thus leaving our test suite entirely.&lt;/p&gt;

&lt;p&gt;Here&amp;#8217;s a testable version:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function _getRedirectPart(url) {
	if (url.charAt(0) === &amp;quot;#&amp;quot;) {
		return &amp;quot;hash&amp;quot;;
	} else if (url.charAt(0) === &amp;quot;/&amp;quot;) {
		return &amp;quot;pathname&amp;quot;;
	} else {
		return &amp;quot;href&amp;quot;;
	}
}

function redirectTo(url) {
	window.location[_getRedirectPart(url)] = url;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And now we can write a simple test suite for &lt;code&gt;_getRedirectPart&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;test(&amp;quot;_getRedirectPart&amp;quot;, function() {
	equal(_getRedirectPart(&amp;quot;#foo&amp;quot;), &amp;quot;hash&amp;quot;);
	equal(_getRedirectPart(&amp;quot;/foo&amp;quot;), &amp;quot;pathname&amp;quot;);
	equal(_getRedirectPart(&amp;quot;http://foo.com&amp;quot;), &amp;quot;href&amp;quot;);
});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now the meat of &lt;code&gt;redirectTo&lt;/code&gt; has been tested, and we don&amp;#8217;t have to worry about accidentally redirecting out of our test suite.&lt;/p&gt;
&lt;span class=&#39;note&#39;&gt;__Note__: There is an alternative solution, which is to create a `performRedirect` function that does the location change, but stub that out in your test suite.	 This is a common practice for many, but I&#39;ve been trying to avoid method stubbing.	 I find basic QUnit to work well in all situations I&#39;ve found so far, and would prefer to not have to remember to stub out a method like that for my tests, but your case may differ.&lt;/span&gt;
&lt;h2 id=&#39;write_lots_of_tests&#39;&gt;Write Lots of Tests&lt;/h2&gt;

&lt;p&gt;This is a no-brainer, but it&amp;#8217;s important to remember. Many programmers write too few tests because writing tests is hard, or lots of work. I suffer from this problem all the time, so I threw together a little helper for QUnit that makes writing lots of tests a lot easier. It&amp;#8217;s a function called &lt;code&gt;testCases&lt;/code&gt; which you call within a &lt;code&gt;test&lt;/code&gt; block, passing a function, calling context, and array of inputs/outputs to try and compare. You can quickly build up a robust suite for your input/output functions for rigorous testing.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function testCases(fn, context, tests) {
	for (var i = 0; i &amp;lt; tests.length; i++) {
		same(fn.apply(context, tests[i][0]), tests[i][1],
			tests[i][2] || JSON.stringify(tests[i]));
	}
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And here&amp;#8217;s a simple example use:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;test(&amp;quot;foo&amp;quot;, function() {
	testCases(foo, null, [
		[[&amp;quot;bar&amp;quot;, &amp;quot;baz&amp;quot;], &amp;quot;barbaz&amp;quot;],
		[[&amp;quot;bar&amp;quot;, &amp;quot;bar&amp;quot;], &amp;quot;barbar&amp;quot;, &amp;quot;a passing test&amp;quot;]
	]);
});&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&#39;conclusions&#39;&gt;Conclusions&lt;/h2&gt;

&lt;p&gt;There is plenty more to write about testable JavaScript, and I&amp;#8217;m sure there are many good books, but I hope this was a good overview of practical cases I encounter on a daily basis. I&amp;#8217;m by no means a testing expert, so please let me know if I&amp;#8217;ve made mistakes or given bad advice.&lt;/p&gt;
            </div>
        </content>
    </entry>
    
    <entry>
        <title>Spying Constructors in JavaScript</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/Spying-Constructors-in-JavaScript.html"/>
        <id>http://www.adequatelygood.com/2010/5/Spying-Constructors-in-JavaScript</id>
        <updated>2010-05-12T00:00:00-07:00</updated>
        <published>2010-05-12T00:00:00-07:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;p&gt;When writing unit-tests for code, a common technique is &lt;strong&gt;spying&lt;/strong&gt;, where you set expectations on a method&amp;#8217;s invocation, run some code, and verify that the method was invoked as expected. This is pretty straightforward. Here&amp;#8217;s a simple example using &lt;a href=&#39;http://jsmockito.org/&#39;&gt;JsMockito&lt;/a&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function foo(a) { return a; }
foo = spy(foo);
foo(1);
verify(foo)(1); // verified!
verify(foo)(2); // never run&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here, we&amp;#8217;re spying on the &lt;code&gt;foo&lt;/code&gt; method, and checking that it was invoked at least once with the parameter &lt;code&gt;1&lt;/code&gt;, and once with the parameter &lt;code&gt;2&lt;/code&gt;. As it turns out, this &lt;code&gt;spy&lt;/code&gt; method does not work well with JavaScript constructors, in &lt;a href=&#39;http://jsmockito.org/&#39;&gt;JsMockito&lt;/a&gt;, &lt;a href=&#39;http://github.com/pivotal/jasmine&#39;&gt;Jasmine&lt;/a&gt;, or many other testing frameworks. The basic problem is that the prototype is not transferred appropriately, so code like this will fail:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function Foo(a) {
	this.a = a;
}
Foo.prototype = {
	bar: function () {
		console.log(this.a);
	}
};

var f = new Foo(1);
f.bar(); // 1

Foo = spy(Foo);
var g = new Foo(1);
g.bar(); // error

verify(Foo)(1); // not reached&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It turns out it&amp;#8217;s really easy to write a constructor-safe spying function, and it doesn&amp;#8217;t even take very many lines of code.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function spy(F) {
	function G() {
		var args = Array.prototype.slice.call(arguments);
		G.calls.push(args);
		F.apply(this, args);
	}

	G.prototype = F.prototype;
	G.calls = [];

	return G;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This &lt;code&gt;spy&lt;/code&gt; function works just like the one in JsMockito, but it doesn&amp;#8217;t fail with constructors. For completeness, here&amp;#8217;s an implementation of a simple &lt;code&gt;verify&lt;/code&gt; function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function verify(F) {
	return function () {
		var args = Array.prototype.slice.call(arguments),
			i,
			j,
			call,
			count = 0,
			matched;

		for (i = 0; i &amp;lt; F.calls.length; i += 1) {
			call = F.calls[i];
			matched = true;
			for (j = 0; j &amp;lt; args.length; j += 1) {
				if (args[j] !== call[j]) {
					matched = false;
					break;
				}
			}
			if (matched) {
				count += 1;
			}
		}

		return count &amp;gt; 0;
	};
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It would be easy to extend this &lt;code&gt;verify&lt;/code&gt; implementation to allow more types of verify like &lt;code&gt;.once()&lt;/code&gt; or &lt;code&gt;.never()&lt;/code&gt;, working off the &lt;code&gt;count&lt;/code&gt; variable.&lt;/p&gt;

&lt;p&gt;And that&amp;#8217;s it! Here&amp;#8217;s an example of code that will work with this &lt;code&gt;spy&lt;/code&gt; implementation:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function Foo(name, id) {
	this.name = name;
	this.id = id;
}

Foo.prototype = {
	log: function () {
		console.log(&amp;quot;Foo %o:%o&amp;quot;, this.id, this.name);
	}
};

var f = new Foo(&amp;quot;test&amp;quot;, 1);
f.log();

Foo = spy(Foo);

var f2 = new Foo(&amp;quot;spied&amp;quot;, 2);
f2.log();

console.log(&amp;quot;verify Foo(\&amp;quot;spied\&amp;quot;, 2): %o&amp;quot;, verify(Foo)(&amp;quot;spied&amp;quot;, 2));
console.log(&amp;quot;verify Foo(\&amp;quot;something\&amp;quot;, 2): %o&amp;quot;, verify(Foo)(&amp;quot;something&amp;quot;, 2));

var baz = {
	spam: function (a) {
		console.log(&amp;quot;calling baz.spam(%o), this.other=%o&amp;quot;, a, this.other);
	},
	other: 10
};

baz.spam = spy(baz.spam);

baz.spam(1);
console.log(&amp;quot;verify baz.spam(1)&amp;quot;, verify(baz.spam)(1));
console.log(&amp;quot;verify baz.spam(2)&amp;quot;, verify(baz.spam)(2));&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The other neat thing is that, so long as you&amp;#8217;re not trapping stale references to the original constructor function before it got spied, JavaScript&amp;#8217;s &lt;code&gt;instanceof&lt;/code&gt; operator should work just fine:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function F() {}
F = spy(F)
new F() instanceof F; // true&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can find the complete code (and a bit more) for this excercise at &lt;a href=&#39;http://www.bcherry.net/playground/spying-constructors&#39;&gt;www.bcherry.net/playground/spying-constructors&lt;/a&gt;. I hope this was informative. I think I&amp;#8217;ll probably end up either contributing a patch to JsMockito with this, or building my own bare-bones set of mocking/spying functions for use with &lt;a href=&#39;http://docs.jquery.com/QUnit&#39;&gt;QUnit&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;span class=&#39;note&#39;&gt;___P.S. It&#39;s been some time since I&#39;ve updated, but I&#39;m hoping this will be the first of many new, interesting JavaScript posts inspired by the work I&#39;m doing at Twitter with @bs, @hoverbird, @ded, and @dsa.___&lt;/span&gt;&lt;/p&gt;
            </div>
        </content>
    </entry>
    
    <entry>
        <title>Debugging Closures and Modules</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/Debugging-Closures-and-Modules.html"/>
        <id>http://www.adequatelygood.com/2010/4/Debugging-Closures-and-Modules</id>
        <updated>2010-04-13T00:00:00-07:00</updated>
        <published>2010-04-13T00:00:00-07:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;p&gt;The most common complaint with using closures to keep private variables in JavaScript is that it makes debugging harder. This complaint definitely holds water, and the loss of easy debugging and inspection using the &lt;a href=&#39;http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth&#39;&gt;Module Pattern&lt;/a&gt; is a serious concern. This is where one of JavaScript&amp;#8217;s non-standard but well-supported features comes in: the &lt;strong&gt;debugger statement&lt;/strong&gt;. In this article, I&amp;#8217;ll introduce this statement, and show how I use it to solve this deficiency in closure-based code.&lt;/p&gt;

&lt;h2 id=&#39;intro_to_&#39;&gt;Intro to &lt;code&gt;debugger&lt;/code&gt;&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;debugger&lt;/code&gt; statement is not standardized, but &lt;strong&gt;is provided by all implementations&lt;/strong&gt; of JavaScript. It essentially acts like a programmatic breakpoint. When popular JavaScript debuggers like Firebug or the IE Developer Tools execute a &lt;code&gt;debugger;&lt;/code&gt; statement, execution stops and the script debugger opens up, just like any breakpoint. Here&amp;#8217;s a simple example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function foo() {
	var a = 1;
	debugger; // execution stops until manually resumed
	a = 2;
}
foo();&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the above, we&amp;#8217;ll be able to inspect the local variables when our debugger pauses execution, and we&amp;#8217;ll see that &lt;code&gt;a&lt;/code&gt; is still &lt;code&gt;1&lt;/code&gt;. After resuming execution, the next line will execute and &lt;code&gt;a&lt;/code&gt; will be assigned the value &lt;code&gt;2&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id=&#39;debugging_modules&#39;&gt;Debugging Modules&lt;/h2&gt;

&lt;p&gt;The great thing is that execution stops at the &lt;code&gt;debugger&lt;/code&gt; statement, complete with the local call stack from the point of execution. This provides a really nice ability to pair with the module pattern, or any other closure-based privacy pattern. Let&amp;#8217;s take a simple module, but add extra capabilities to it by exposing a public &lt;code&gt;.debug()&lt;/code&gt; method.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var foo = (function () {
	var privateVar = 10;
	return {
		publicFunc: function () {/*...*/},
		debug: function () {
			debugger;
		}
	};
}());&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we can call &lt;code&gt;foo.debug()&lt;/code&gt; from the Firebug console, and the closure of the anonymous constructor is opened up for inspection. By looking at the &lt;strong&gt;call stack&lt;/strong&gt; in our debugger, we can inspect the &lt;strong&gt;scope chain&lt;/strong&gt; for the private state, which will be in local variables. Checking the value of &lt;code&gt;privateVar&lt;/code&gt; will be quite easy.&lt;/p&gt;

&lt;p&gt;Notice that it&amp;#8217;s very important for the &lt;code&gt;.debug()&lt;/code&gt; property to be created and assigned during the normal construction. Assigning it after-the-fact will not provide the same functionality, because the local call stack will not contain the anonymous constructor. This is an unfortunate limitation, but there isn&amp;#8217;t a way around it.&lt;/p&gt;

&lt;h2 id=&#39;safety_and_configuration&#39;&gt;Safety and Configuration&lt;/h2&gt;

&lt;p&gt;You might not want to make it so easy to stop program execution by triggering the &lt;code&gt;.debug()&lt;/code&gt; function on one of your modules, or you might want to disable this functionality. One approach is to ship a version of your code without this property at all, but that&amp;#8217;s difficult to accomplish in some applications. An easier method would be to do some extra checks in the &lt;code&gt;.debug()&lt;/code&gt; method, before firing the &lt;code&gt;debugger&lt;/code&gt; statement.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;return {
	debug: function () {
		if (DEBUG_MODE) {
			debugger;
		}
	}
};&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Or, perhaps check for a specific debugger first:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;return {
	debug: function () {
		if (DEBUG_MODE &amp;amp;&amp;amp; &amp;quot;firebug&amp;quot; in console) {
			debugger;
		}
	}
};&lt;/code&gt;&lt;/pre&gt;
&lt;span class=&#39;note&#39;&gt;___Note___: I&#39;m assuming you&#39;ve already configured a global flag named `DEBUG_MODE` in your application.&lt;/span&gt;
&lt;p&gt;Methods like this will allow you to provide finer-grained control over when and where your &lt;code&gt;debugger&lt;/code&gt; statement runs. If you&amp;#8217;re building in a lot of logic, it makes sense to write a global helper function for this, but you&amp;#8217;ll have to be careful to preserve the right call stack:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function DEBUG() {
	if (DEBUG_MODE &amp;amp;&amp;amp; &amp;quot;firebug&amp;quot; in console) {
		debugger;
	}
}

var foo = (function () {
	return {
		debug: function () {
			DEBUG();
		}
	};
}());&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here we&amp;#8217;ll keep our callstack in tact, except the one we care about will be two deep instead of one deep.&lt;/p&gt;

&lt;h3 id=&#39;problems_with_minifiers&#39;&gt;Problems With Minifiers&lt;/h3&gt;

&lt;p&gt;I tried running code with such a &lt;code&gt;.debug()&lt;/code&gt; method through the YUI Compressor, and got a disappointing result:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[ERROR] 4:11:identifier is a reserved word&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It seems that the YUI Compressor doesn&amp;#8217;t know about the &lt;code&gt;debugger&lt;/code&gt; statement, which is understandable since it&amp;#8217;s non-standard. However, I didn&amp;#8217;t want to let this defeat my attempts, so a co-worker and I came up with a workaround. Instead of using a raw &lt;code&gt;debugger&lt;/code&gt; statement, we put it behind &lt;code&gt;eval&lt;/code&gt;, like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function debug() {
	eval(&amp;#39;debugger;&amp;#39;);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now YUI no longer complains, and the code works just great. However, there are a few caveats here:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Using &lt;code&gt;eval&lt;/code&gt; is generally considered &lt;strong&gt;dangerous&lt;/strong&gt; and &lt;strong&gt;bad practice&lt;/strong&gt;. Be sure you understand the implications, and are willing to use this workaround anyways. I think this is a reasonable decision to make, for the intended purpose, but ensure you&amp;#8217;ve at least put some thought into it.&lt;/li&gt;

&lt;li&gt;JSLint will complain at you. This isn&amp;#8217;t such a big deal since it would be complaining about the raw &lt;code&gt;debugger&lt;/code&gt; statement anyways.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&#39;conclusions&#39;&gt;Conclusions&lt;/h2&gt;

&lt;p&gt;So that&amp;#8217;s my technique for effectively debugging inside closures, especially when using the Module Pattern. I&amp;#8217;m not saying this is a great technique for all uses or users, but it works well for me, and nicely solves the most common complaint developers have about the Module Pattern. I&amp;#8217;d love to hear alternatives or reasons why my technique is dangerous and should be avoided, so leave a comment!&lt;/p&gt;
            </div>
        </content>
    </entry>
    
    <entry>
        <title>Object-to-Primitive Conversions in JavaScript</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/Object-to-Primitive-Conversions-in-JavaScript.html"/>
        <id>http://www.adequatelygood.com/2010/3/Object-to-Primitive-Conversions-in-JavaScript</id>
        <updated>2010-03-30T00:00:00-07:00</updated>
        <published>2010-03-30T00:00:00-07:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;p&gt;Like most object-oriented programming languages, JavaScript provides built-in ways to convert between objects and primitive values, by way of the special &lt;code&gt;toString&lt;/code&gt; and &lt;code&gt;valueOf&lt;/code&gt; methods. This article will cover the basics of these methods, but then dive into the details of how this stuff really works, bad stuff, performance, and browser support.&lt;/p&gt;

&lt;h3 id=&#39;types_and_primitives&#39;&gt;Types and Primitives&lt;/h3&gt;

&lt;p&gt;To understand this article, you&amp;#8217;ll need to understand the difference between &lt;strong&gt;primitive and non-primitive values&lt;/strong&gt; in JavaScript. There are 5 primitive types, which are associated with the various primitive values.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Null&lt;/strong&gt;: The value &lt;code&gt;null&lt;/code&gt;.&lt;/li&gt;

&lt;li&gt;&lt;strong&gt;Undefined&lt;/strong&gt;: The value &lt;code&gt;undefined&lt;/code&gt;.&lt;/li&gt;

&lt;li&gt;&lt;strong&gt;Number&lt;/strong&gt;: All numbers, such as &lt;code&gt;0&lt;/code&gt; and &lt;code&gt;3.14&lt;/code&gt;. Also &lt;code&gt;NaN&lt;/code&gt;, and &lt;code&gt;Infinity&lt;/code&gt;.&lt;/li&gt;

&lt;li&gt;&lt;strong&gt;Boolean&lt;/strong&gt;: The values &lt;code&gt;true&lt;/code&gt; and &lt;code&gt;false&lt;/code&gt;.&lt;/li&gt;

&lt;li&gt;&lt;strong&gt;String&lt;/strong&gt;: All strings, such as &lt;code&gt;&amp;quot;foo&amp;quot;&lt;/code&gt; and &lt;code&gt;&amp;quot;&amp;quot;&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;All other values are non-primitive, including arrays, functions, and plain old objects. For completeness, here are the results of the &lt;code&gt;typeof&lt;/code&gt; operator, applied to these values:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;typeof null; // &amp;quot;object&amp;quot;
typeof undefined; // &amp;quot;undefined&amp;quot;
typeof 0; // &amp;quot;number&amp;quot; (`typeof NaN` is also &amp;quot;number&amp;quot;)
typeof true; // &amp;quot;boolean&amp;quot;
typeof &amp;quot;foo&amp;quot;; // &amp;quot;string&amp;quot;
typeof {}; // &amp;quot;object&amp;quot;
typeof function () {}; // &amp;quot;function&amp;quot;
typeof []; // &amp;quot;object&amp;quot;&lt;/code&gt;&lt;/pre&gt;
&lt;span class=&#39;note&#39;&gt;__Note__: `typeof null` should _not_ be `&quot;object&quot;`.  This is a mistake from the first versions of JavaScript, but it&#39;s really too late to fix.  A more sensible type would have been `&quot;null&quot;`, but this is what we&#39;re stuck with.&lt;/span&gt;
&lt;p&gt;If you&amp;#8217;ve got that down, then we&amp;#8217;re ready to move on to the basics of &lt;code&gt;toString&lt;/code&gt; and &lt;code&gt;valueOf&lt;/code&gt;. If you&amp;#8217;re already familiar with the basics, feel free to skip ahead to &amp;#8220;How it Works&amp;#8221;.&lt;/p&gt;

&lt;h2 id=&#39;basic_usage&#39;&gt;Basic Usage&lt;/h2&gt;

&lt;p&gt;We&amp;#8217;ll be using a simple example &lt;code&gt;population&lt;/code&gt; object that holds a country name and a population. Lets code that up.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function population(country, pop) {
	return {
		country: country,
		pop: pop
	};
}

var america_pop = population(&amp;quot;USA&amp;quot;, 350e6);
var mexico_pop = population(&amp;quot;Mexico&amp;quot;, 200e6);
var canada_pop = population(&amp;quot;Canada&amp;quot;, 200e6);

alert(america_pop); // [object Object]

var north_america_pop = america_pop + mexico_pop + canada_pop;

alert(north_america_pop); // [object Object][object Object][object Object]&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This works, but the calls to &lt;code&gt;alert&lt;/code&gt; are not very useful. What we&amp;#8217;d really like is for the first &lt;code&gt;alert&lt;/code&gt; to show &lt;code&gt;&amp;#39;[Population &amp;quot;USA&amp;quot; 350000000]&amp;#39;&lt;/code&gt; and the second to show &lt;code&gt;&amp;quot;750000000&amp;quot;&lt;/code&gt;. So, let&amp;#8217;s code that up next.&lt;/p&gt;

&lt;h3 id=&#39;tostring&#39;&gt;toString&lt;/h3&gt;

&lt;p&gt;All objects inherit the method &lt;code&gt;toString&lt;/code&gt; from &lt;code&gt;Object.prototype&lt;/code&gt;, which returns &lt;code&gt;&amp;quot;[object Object]&amp;quot;&lt;/code&gt;. However, we can easily override this by providing &lt;code&gt;toString&lt;/code&gt; as a method of our object, or its prototype. In this example, we&amp;#8217;ll attach it directly to each instance, but feel free to use the prototype instead.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function population(country, pop) {
	return {
		country: country,
		pop: pop,
		
		toString: function () {
			return &amp;quot;[Population &amp;quot; + 
				&amp;quot;\&amp;quot;&amp;quot; + country + &amp;quot;\&amp;quot; &amp;quot; +
				pop +
			&amp;quot;]&amp;quot;;
		}
	}
}

var america_pop = population(&amp;quot;USA&amp;quot;, 350e6);
alert(america_pop); // [Population &amp;quot;USA&amp;quot; 350000000]&lt;/code&gt;&lt;/pre&gt;
&lt;span class=&#39;note&#39;&gt;__Note__: I&#39;m using __closure__ on the `country` parameter, rather than using `this.country`.  This only works due to how the constructor is set up.  If you placed `toString` on the prototype, you would need to use `this.country`.&lt;/span&gt;
&lt;h3 id=&#39;valueof&#39;&gt;valueOf&lt;/h3&gt;

&lt;p&gt;All JavaScript objects also inherit the method &lt;code&gt;valueOf&lt;/code&gt; from &lt;code&gt;Object.prototype&lt;/code&gt;. By default, this method simply returns the object itself, but is generally overridden to convert an object to a &lt;code&gt;Number&lt;/code&gt;, or another primitive value, so it can be used by operators like &lt;code&gt;+&lt;/code&gt;. We can do the same thing as above to complete our basic example.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function population(country, pop) {
	return {
		country: country,
		pop: pop,
		
		toString: function () {
			return &amp;quot;[Population &amp;quot; + 
				&amp;quot;\&amp;quot;&amp;quot; + country + &amp;quot;\&amp;quot; &amp;quot; +
				pop +
			&amp;quot;]&amp;quot;;
		},
		
		valueOf: function () {
			return pop;
		}
	};
}

var america_pop = population(&amp;quot;USA&amp;quot;, 350e6);
var mexico_pop = population(&amp;quot;Mexico&amp;quot;, 200e6);
var canada_pop = population(&amp;quot;Canada&amp;quot;, 200e6);

alert(america_pop); // [Population &amp;quot;USA&amp;quot; 350000000

var north_america_pop = america_pop + mexico_pop + canada_pop;

alert(north_america_pop); // 750000000&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here we&amp;#8217;ve defined the &lt;code&gt;valueOf&lt;/code&gt; function of our &lt;code&gt;population&lt;/code&gt; object to return the population, which should be a &lt;code&gt;Number&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id=&#39;how_it_works&#39;&gt;How It Works&lt;/h2&gt;

&lt;p&gt;As with most things in JavaScript, the process by which &lt;code&gt;toString&lt;/code&gt; gets called is not as simple as you&amp;#8217;d think. Let&amp;#8217;s explore what happens when &lt;code&gt;alert(america_pop)&lt;/code&gt; is called.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;code&gt;alert&lt;/code&gt; calls &lt;code&gt;GetValue&lt;/code&gt; on the reference. This returns the object it points at.&lt;/li&gt;

&lt;li&gt;&lt;code&gt;alert&lt;/code&gt; calls &lt;code&gt;ToString&lt;/code&gt; on the value (this is &lt;em&gt;not&lt;/em&gt; the same as the object&amp;#8217;s &lt;code&gt;toString&lt;/code&gt;)&lt;/li&gt;

&lt;li&gt;&lt;code&gt;ToString&lt;/code&gt; calls &lt;code&gt;ToPrimitive&lt;/code&gt; on the value, passing the &lt;em&gt;hint&lt;/em&gt; &lt;code&gt;String&lt;/code&gt;.&lt;/li&gt;

&lt;li&gt;&lt;code&gt;ToPrimitive&lt;/code&gt; calls the object&amp;#8217;s internal &lt;code&gt;[[DefaultValue]]&lt;/code&gt; method with the &lt;em&gt;hint&lt;/em&gt; &lt;code&gt;String&lt;/code&gt;.&lt;/li&gt;

&lt;li&gt;&lt;code&gt;[[DefaultValue]]&lt;/code&gt; calls the &lt;code&gt;toString&lt;/code&gt; property of the object, with the object as &lt;code&gt;this&lt;/code&gt;.&lt;/li&gt;

&lt;li&gt;The result of &lt;code&gt;toString&lt;/code&gt; is a primitive value, so it is returned, all the way up the chain to the &lt;code&gt;ToString&lt;/code&gt; method.&lt;/li&gt;

&lt;li&gt;Since the result is of type &lt;code&gt;String&lt;/code&gt;, &lt;code&gt;ToString&lt;/code&gt; returns all the way to &lt;code&gt;alert&lt;/code&gt;.&lt;/li&gt;

&lt;li&gt;&lt;code&gt;alert&lt;/code&gt; displays the value.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;While this is a lot, it&amp;#8217;s pretty straightforward. However, he key mechanism that needs more explaining is the &lt;code&gt;ToPrimitive&lt;/code&gt; function. This function is used to take an arbitrary value and get a corresponding primitive value instead. If the input is already a primitive value then the value will be returned without conversion. However, if the value is non-primitive, then it will call the internal &lt;code&gt;[[DefaultValue]]&lt;/code&gt; method to find a &lt;strong&gt;default value&lt;/strong&gt; for the object.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;[[DefaultValue]]&lt;/code&gt; is an internal property of every object. It&amp;#8217;s a method that takes an optional &lt;em&gt;hint&lt;/em&gt;, which should be either &lt;code&gt;Number&lt;/code&gt; or &lt;code&gt;String&lt;/code&gt;. If a &lt;em&gt;hint&lt;/em&gt; is not provided, it will default to &lt;code&gt;Number&lt;/code&gt; unless the object is a &lt;code&gt;Date&lt;/code&gt;, in which case it defaults to &lt;code&gt;String&lt;/code&gt; (this is silly). After this has been figured out, it will call &lt;code&gt;toString&lt;/code&gt; and &lt;code&gt;valueOf&lt;/code&gt;, in order, to find a primitive value. This is where the &lt;em&gt;hint&lt;/em&gt; comes into play. If the &lt;em&gt;hint&lt;/em&gt; is &lt;code&gt;Number&lt;/code&gt;, then &lt;code&gt;valueOf&lt;/code&gt; will be tried first, but if it&amp;#8217;s &lt;code&gt;String&lt;/code&gt; then &lt;code&gt;toString&lt;/code&gt; will be tried first. Here&amp;#8217;s the ensuing process:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;If the first method exists, and is callable, call it and get the result, otherwise skip to 3.&lt;/li&gt;

&lt;li&gt;If the result of 1 is a primitive, return it.&lt;/li&gt;

&lt;li&gt;If the second method exists, and is callable, call it and get the result, otherwise skip to 5.&lt;/li&gt;

&lt;li&gt;If the result of 3 is a primitive, return it.&lt;/li&gt;

&lt;li&gt;Throw a &lt;code&gt;TypeError&lt;/code&gt; exception.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The value that is returned by &lt;code&gt;[[DefaultValue]]&lt;/code&gt; is guaranteed to be primitive. If it was not, a &lt;code&gt;TypeError&lt;/code&gt; would have been thrown. This also implies that &lt;code&gt;toString&lt;/code&gt; and &lt;code&gt;valueOf&lt;/code&gt; should return primitives on order to be useful in this context.&lt;/p&gt;

&lt;h3 id=&#39;confusion_about_the__operator&#39;&gt;Confusion About the + Operator&lt;/h3&gt;

&lt;p&gt;Here&amp;#8217;s an example with a (possibly) unexpected result:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var foo = {
	toString: function () {
		return &amp;quot;foo&amp;quot;;
	},
	valueOf: function () {
		return 5;
	}
};

alert(foo + &amp;quot;bar&amp;quot;); // 5bar
alert([foo, &amp;quot;bar&amp;quot;].join(&amp;quot;&amp;quot;)); // foobar&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this context, we&amp;#8217;re using the &lt;code&gt;+&lt;/code&gt; operator to do string concatenation. But, &lt;code&gt;foo&lt;/code&gt; was &lt;em&gt;not&lt;/em&gt; converted to a string using &lt;code&gt;toString&lt;/code&gt;, it was turned into a number using &lt;code&gt;valueOf&lt;/code&gt;, then used for string concatenation. This probably isn&amp;#8217;t what we want, but it is how it works. It&amp;#8217;s a side-effect of the overloading of the &lt;code&gt;+&lt;/code&gt; operator for arithmetic and string concatenation. The &lt;code&gt;+&lt;/code&gt;operator has a well-defined process:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Evaluate the left-hand side, and get the value.&lt;/li&gt;

&lt;li&gt;Evaluate the right-hand side, and get the value.&lt;/li&gt;

&lt;li&gt;Call &lt;code&gt;ToPrimitive&lt;/code&gt; on both the left-hand and right-hand sides (without a &lt;em&gt;hint&lt;/em&gt;)&lt;/li&gt;

&lt;li&gt;If either primitive value is a &lt;code&gt;String&lt;/code&gt;, then skip to 7.&lt;/li&gt;

&lt;li&gt;Call &lt;code&gt;ToNumber&lt;/code&gt; on both values.&lt;/li&gt;

&lt;li&gt;Return the sum of the values.&lt;/li&gt;

&lt;li&gt;Call &lt;code&gt;ToString&lt;/code&gt; on both values.&lt;/li&gt;

&lt;li&gt;Return the concatenation of both values.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Since no &lt;em&gt;hint&lt;/em&gt; is passed to the &lt;code&gt;ToPrimitive&lt;/code&gt; calls, the &lt;em&gt;hint&lt;/em&gt; will be defaulted to &lt;code&gt;Number&lt;/code&gt; (unless it&amp;#8217;s a &lt;code&gt;Date&lt;/code&gt;, which defaults to &lt;code&gt;String&lt;/code&gt;). This means that our &lt;code&gt;valueOf&lt;/code&gt; function will be called, instead of &lt;code&gt;toString&lt;/code&gt;. It&amp;#8217;s not until &lt;em&gt;after&lt;/em&gt; the primitive values are retrieved that the interpreter decides whether it is going to do string concatenation or arithmetic. That&amp;#8217;s why our example above returns &lt;code&gt;&amp;quot;5bar&amp;quot;&lt;/code&gt; instead of &lt;code&gt;&amp;quot;foobar&amp;quot;&lt;/code&gt;.&lt;/p&gt;

&lt;h3 id=&#39;bad_stuff&#39;&gt;Bad Stuff&lt;/h3&gt;

&lt;p&gt;There is one really bad feature of all this, which is that &lt;code&gt;ToPrimitive&lt;/code&gt; does not enforce any type-checking on the return values, other than that they are primitive. This means you can write code like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var foo = {
	toString: function () {
		return 5;
	},
	valueOf: function () {
		return &amp;quot;foo&amp;quot;;
	}
};
alert(foo.toString() + 1); // 6 (bad!)
alert(foo + 1); // &amp;quot;foo1&amp;quot; (no good!)
alert(+foo); // NaN (the worst!)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;valueOf&lt;/code&gt; method can be forgiven for not type-checking, because it is more generic. You&amp;#8217;d expect it to be able to return any suitable primitive value. However, the &lt;code&gt;toString&lt;/code&gt; method has &lt;em&gt;no such excuse&lt;/em&gt;. This is simply a bad feature. You can, of course, mitigate by using &lt;code&gt;String(foo)&lt;/code&gt; instead of &lt;code&gt;foo.toString()&lt;/code&gt;, which will call &lt;code&gt;toString&lt;/code&gt; and then convert that result to a string. But you should not have to do this, or worry about this. Please do not make objects with &lt;code&gt;toString&lt;/code&gt; methods that do not return strings.&lt;/p&gt;

&lt;h2 id=&#39;how_about_performance&#39;&gt;How About Performance?&lt;/h2&gt;

&lt;p&gt;After understanding the complexity that goes into these implicit conversion, I got curious about how that affects performance. So I decided to test the time it takes to perform an &lt;code&gt;[].join(obj)&lt;/code&gt; over 1,000,000 iterations in the major browsers. I did one test with the object being implicitly cast to a string, and one where I called the &lt;code&gt;toString&lt;/code&gt; method manually (i.e. &lt;code&gt;[].join(obj.toString())&lt;/code&gt;). As expected, the explicit call was faster in most cases.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Firefox 3.6.2&lt;/strong&gt;: 874ms vs. 320ms - &lt;strong&gt;almost 3x faster&lt;/strong&gt;.&lt;/li&gt;

&lt;li&gt;&lt;strong&gt;Chrome 5&lt;/strong&gt;: 94ms vs. 47ms - &lt;strong&gt;2x faster&lt;/strong&gt;.&lt;/li&gt;

&lt;li&gt;&lt;strong&gt;Opera 10.50&lt;/strong&gt;: 155ms vs 182ms - &lt;strong&gt;a little slower&lt;/strong&gt;.&lt;/li&gt;

&lt;li&gt;&lt;strong&gt;Safari 4&lt;/strong&gt;: 409ms vs 280ms - &lt;strong&gt;almost 2x faster&lt;/strong&gt;.&lt;/li&gt;

&lt;li&gt;&lt;strong&gt;Internet Explorer 8&lt;/strong&gt;: 2856ms vs 2786ms - &lt;strong&gt;about the same&lt;/strong&gt;.&lt;/li&gt;

&lt;li&gt;&lt;strong&gt;Internet Explorer 9&lt;/strong&gt; (preview): 645ms vs 633ms - &lt;strong&gt;about the same&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;span class=&#39;note&#39;&gt;___Note 1___: The Firefox, Chrome, Opera, and Safari tests were all run on a Macbook Pro running OS X 10.5.  The IE tests were run on a desktop running Windows 7.  [Run the tests yourself here.](http://www.bcherry.net/playground/defaultvalues)&lt;/span&gt;&lt;span class=&#39;note&#39;&gt;___Note 2___: I chose to use the `[].join` method because doing so was most likely to avoid any dead-code elimination optimizations in modern browsers.  I&#39;ve had trouble with this before, in Firefox.  I _did_ try testing with the `String()` constructor, with similar results in most browsers.  Opera was an exception where using the explicit `toString` was close to __5x faster__.  In Firefox, the explicit cast was a bit faster, but both cases were about 100x faster than the `[].join` method (and other browsers), which means the code-path was probably being removed by the dead code eliminator.&lt;/span&gt;
&lt;p&gt;The takeaway from this performance test is that it&amp;#8217;s always best to call your object&amp;#8217;s type-conversion methods directly, rather than relying on the interpreter to do the complex series of method calls and comparisons needed to do it automatically. The Opera 10.50 result is very strange, but it&amp;#8217;s not particularly slower, so I wouldn&amp;#8217;t worry about it. The gains made in other browsers more than make up for the outlier Opera result.&lt;/p&gt;

&lt;h2 id=&#39;how_about_browser_support&#39;&gt;How About Browser Support?&lt;/h2&gt;

&lt;p&gt;Like many things in the ECMAScript specification, these processes are complex, and I doubted that all browsers would implement them exactly as specified. So, in that &lt;a href=&#39;http://www.bcherry.net/playground/defaultvalues&#39;&gt;test suite from earlier&lt;/a&gt;, I added compliance checks. I was quite surprised to see that all major browsers, including versions of Internet Explorer going back to at least IE 5.5, implement these mechanisms correctly. This is even the case with the awkward handling when developers do things like make &lt;code&gt;toString&lt;/code&gt; return a number instead of a string. All browsers handle the code according to the specification. This is great news.&lt;/p&gt;

&lt;p&gt;But the specification unhelpfully introduced ambiguity in one particular area: the absence of a &lt;em&gt;hint&lt;/em&gt; for the &lt;code&gt;ToPrimitive&lt;/code&gt; function. Here&amp;#8217;s the exact wording:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;All native ECMAScript objects except Date objects handle the absence of a hint as if the hint Number were given; Date objects handle the absence of a hint as if the hint String were given. Host objects may handle the absence of a hint in some other manner.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;That the standard explicitly allows browsers to deviate here worried me. Included in that test suite was a check that, in the absence of a &lt;em&gt;hint&lt;/em&gt;, &lt;code&gt;Date&lt;/code&gt; objects will default to &lt;code&gt;String&lt;/code&gt; and &lt;code&gt;Boolean&lt;/code&gt; objects will default to &lt;code&gt;Number&lt;/code&gt;. All browsers passed this check as well, which means that browser support for all of this functionality seems to be &lt;strong&gt;consistent&lt;/strong&gt; and &lt;strong&gt;correct&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&#39;conclusions&#39;&gt;Conclusions&lt;/h2&gt;

&lt;p&gt;I hope this was useful in understanding how these mechanisms work in JavaScript. There are three important things to take away from this article:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Implement &lt;code&gt;toString&lt;/code&gt; and &lt;code&gt;valueOf&lt;/code&gt; on your commonly-reused objects. They can help you write clearer, more concise code, and make debugging easier too.&lt;/li&gt;

&lt;li&gt;All browsers implement object-to-primitive conversion according to the specification, so you can safely consult it for more detail.&lt;/li&gt;

&lt;li&gt;When performance is important, always try to call your type-conversion methods directly, instead of relying on JavaScript&amp;#8217;s implicit calls.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;You can find the &lt;a href=&#39;http://www.bcherry.net/playground/defaultvalues&#39;&gt;test suite used for this article here&lt;/a&gt; if you&amp;#8217;re interested in trying to replicate my results. Please let me know if you find contradictory results to what I posted here.&lt;/p&gt;

&lt;p&gt;Thanks for reading! If you have questions or feedback then leave a comment below or contact me directly.&lt;/p&gt;
            </div>
        </content>
    </entry>
    
    <entry>
        <title>JavaScript-Style Objects in Python</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/JavaScript-Style-Objects-in-Python.html"/>
        <id>http://www.adequatelygood.com/2010/3/JavaScript-Style-Objects-in-Python</id>
        <updated>2010-03-26T00:00:00-07:00</updated>
        <published>2010-03-26T00:00:00-07:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;p&gt;One of JavaScript&amp;#8217;s most convenient features is the object syntax. Objects are so easy to work with. You&amp;#8217;ve got a lot of ways to make them, although the object literal syntax in particular kicks ass. You can access and assign them with either the dot operator or dictionary syntax. Missing properties just return &lt;code&gt;undefined&lt;/code&gt;. This is just a really fantastic object model.&lt;/p&gt;

&lt;p&gt;So, today, I sat down to write my first serious Python code in a while, and found myself trying use a dictionary like a JavaScript object. This was a total failure, obviously. Python simply does not have that. Luckily, it&amp;#8217;s an incredibly malleable language, if you&amp;#8217;re willing to do the legwork. So, in about 30 min, I implemented JavaScript-style objects.&lt;/p&gt;

&lt;p&gt;To make a JavaScript-style object, you use &lt;code&gt;js.JsObject()&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import js
foo = js.JsObject()&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can assign properties with either dictionary syntax or the dot operator.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;foo.bar = 1
foo[&amp;#39;baz&amp;#39;] = 2&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Reading properties works the same, and properties that don&amp;#8217;t exist simply return &lt;code&gt;None&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;foo[&amp;#39;bar&amp;#39;] # 1
foo.baz # 2
foo.spam # None
foo[&amp;#39;spam&amp;#39;] # None&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It just prints out as a dictionary when you convert it to a string, as is done by the &lt;code&gt;print&lt;/code&gt; operator. It also does the same when viewed in the interpreter.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;print foo # {&amp;#39;baz&amp;#39;: 2, &amp;#39;bar&amp;#39;: 1}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The properties are iterable just as in JavaScript. This is different than normal Python dictionaries, where you iterate on a tuple of &lt;code&gt;(key, value)&lt;/code&gt;. Here we just get the keys.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;for prop in foo:
	print prop, foo[prop] # bar 1, baz 2&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can also delete properties, using either the dot operator or dictionary syntax. It won&amp;#8217;t &lt;code&gt;raise&lt;/code&gt; if the property doesn&amp;#8217;t exist, either.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;del foo.bar
del foo[&amp;#39;spam&amp;#39;]&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can also easily check if properties exist using the &lt;code&gt;in&lt;/code&gt; operator.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;#39;baz&amp;#39; in foo # True
&amp;#39;bar&amp;#39; in foo # False&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And object comparison works as in JavaScript. Two will never be the same, even if they have the same properties and values.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;js.JsObject() == js.JsObject() # False
js.JsObject() is js.JsObject() # False&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And, finally, the constructor function is more flexible than I let on initially. You can pass in keyword arguments, which will end up as properties. You can also pass a dictionary to initialize it with. Or, you can pass both!&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;foo = js.JsObject(a=1, b=2)
print foo # {&amp;#39;a&amp;#39;: 1, &amp;#39;b&amp;#39;: 2}

foo = js.JsObject({&amp;#39;a&amp;#39;: 1, &amp;#39;b&amp;#39;: 2})
print foo # {&amp;#39;a&amp;#39;: 1, &amp;#39;b&amp;#39;: 2}

foo = js.JsObject({&amp;#39;a&amp;#39;: 1}, b=2)
print foo # {&amp;#39;a&amp;#39;: 1, &amp;#39;b&amp;#39;: 2}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So yeah, that&amp;#8217;s pretty awesome. I thought about handling prototypal inheritance too, but I just don&amp;#8217;t see the need. I almost never use prototypes in JavaScript, I&amp;#8217;m positive I would never use them in Python. I&amp;#8217;m also not crazy about the creation syntax, but I couldn&amp;#8217;t find a way to re-purpose the dictionary literal &lt;code&gt;{}&lt;/code&gt;, and didn&amp;#8217;t want to override built-in names like &lt;code&gt;dict&lt;/code&gt; or &lt;code&gt;object&lt;/code&gt;. I also wanted to keep with Python conventions and UpperCamelCase the class name, so &lt;code&gt;js.JsObject()&lt;/code&gt; is what I settled on.&lt;/p&gt;

&lt;p&gt;You&amp;#8217;re probably curious about the implementation, so here&amp;#8217;s the full source code. I&amp;#8217;m probably missing some useful things, but this is what I have so far. It&amp;#8217;s quite simple; for the most part it just overrides everything to some form of dictionary method on &lt;code&gt;self.___dict__&lt;/code&gt;. You can also find &lt;a href=&#39;http://github.com/bcherry/js-py/blob/master/js.py&#39;&gt;js.py on GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class JsObject(object):
	def __init__(self, *args, **kwargs):
		for arg in args:
			self.__dict__.update(arg)

		self.__dict__.update(kwargs)

	def __getitem__(self, name):
		return self.__dict__.get(name, None)

	def __setitem__(self, name, val):
		return self.__dict__.__setitem__(name, val)

	def __delitem__(self, name):
		if self.__dict__.has_key(name):
			del self.__dict__[name]

	def __getattr__(self, name):
		return self.__getitem__(name)

	def __setattr__(self, name, val):
		return self.__setitem__(name, val)

	def __delattr__(self, name):
		return self.__delitem__(name)

	def __iter__(self):
		return self.__dict__.__iter__()

	def __repr__(self):
		return self.__dict__.__repr__()

	def __str__(self):
		return self.__dict__.__str__()&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So, there you go. I&amp;#8217;d love to hear what you think, leave a comment!&lt;/p&gt;
            </div>
        </content>
    </entry>
    
    <entry>
        <title>JavaScript: Better and Faster</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/JavaScript-Better-and-Faster.html"/>
        <id>http://www.adequatelygood.com/2010/3/JavaScript-Better-and-Faster</id>
        <updated>2010-03-21T00:00:00-07:00</updated>
        <published>2010-03-21T00:00:00-07:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;p&gt;&amp;#8220;JavaScript: Better and Faster&amp;#8221; is the name of a presentation I gave at &lt;a href=&#39;http://www.slide.com&#39;&gt;Slide&lt;/a&gt; last week. It was generally well-received by the Slide crew so I decided to put a (slightly edited) copy of the &lt;a href=&#39;http://www.bcherry.net/talks/js-better-faster&#39;&gt;accompanying slideshow online&lt;/a&gt; (runs in your browser). It&amp;#8217;s not particularly dense, and doesn&amp;#8217;t get into too much depth on any one topic, but I think it gives a great practical overview of the JavaScript landscape, including what things to look out for and neat techniques to write better code. The original intent was to cover the ins and outs of writing good, efficient JavaScript, targeted at people who write JavaScript every day, but have a strong background in Python.&lt;/p&gt;

&lt;p&gt;I&amp;#8217;d like to give a huge thanks to &lt;a href=&#39;http://scottchacon.com/&#39;&gt;Scott Chacon&lt;/a&gt;, whose &lt;a href=&#39;http://github.com/schacon/showoff&#39;&gt;Showoff&lt;/a&gt; software made compiling this slideshow the most enjoyable thing imaginable. It took a little work to port the resultant slideshow to Google AppEngine, but I got it up and running. I&amp;#8217;ll probably work on a more generalized Python/AppEngine adaptation of Showoff for my future use, since that&amp;#8217;s my web platform and I want to keep using Showoff in the future. This experience also got me really turned on to &lt;a href=&#39;http://daringfireball.net/projects/markdown/&#39;&gt;Markdown&lt;/a&gt;, which I wasted no time in integrating into this blog.&lt;/p&gt;

&lt;p&gt;This is the first presentation I&amp;#8217;ve given in my professional career, and would much appreciate feedback on the slides.&lt;/p&gt;
            </div>
        </content>
    </entry>
    
    <entry>
        <title>JavaScript Module Pattern: In-Depth</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html"/>
        <id>http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth</id>
        <updated>2010-03-12T00:00:00-08:00</updated>
        <published>2010-03-12T00:00:00-08:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;p&gt;The module pattern is a common JavaScript coding pattern. It&amp;#8217;s generally well understood, but there are a number of advanced uses that have not gotten a lot of attention. In this article, I&amp;#8217;ll review the basics and cover some truly remarkable advanced topics, including one which I think is original.&lt;/p&gt;

&lt;h2 id=&#39;the_basics&#39;&gt;The Basics&lt;/h2&gt;

&lt;p&gt;We&amp;#8217;ll start out with a simple overview of the module pattern, which has been well-known since Eric Miraglia (of YUI) first &lt;a href=&#39;http://yuiblog.com/blog/2007/06/12/module-pattern/&#39;&gt;blogged about it&lt;/a&gt; three years ago. If you&amp;#8217;re already familiar with the module pattern, feel free to skip ahead to &amp;#8220;Advanced Patterns&amp;#8221;.&lt;/p&gt;

&lt;h3 id=&#39;anonymous_closures&#39;&gt;Anonymous Closures&lt;/h3&gt;

&lt;p&gt;This is the fundamental construct that makes it all possible, and really is the single &lt;strong&gt;best feature of JavaScript&lt;/strong&gt;. We&amp;#8217;ll simply create an anonymous function, and execute it immediately. All of the code that runs inside the function lives in a &lt;strong&gt;closure&lt;/strong&gt;, which provides &lt;strong&gt;privacy&lt;/strong&gt; and &lt;strong&gt;state&lt;/strong&gt; throughout the lifetime of our application.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(function () {
	// ... all vars and functions are in this scope only
	// still maintains access to all globals
}());&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice the &lt;code&gt;()&lt;/code&gt; around the anonymous function. This is required by the language, since statements that begin with the token &lt;code&gt;function&lt;/code&gt; are always considered to be &lt;strong&gt;function declarations&lt;/strong&gt;. Including &lt;code&gt;()&lt;/code&gt; creates a &lt;strong&gt;function expression&lt;/strong&gt; instead.&lt;/p&gt;

&lt;h3 id=&#39;global_import&#39;&gt;Global Import&lt;/h3&gt;

&lt;p&gt;JavaScript has a feature known as &lt;strong&gt;implied globals&lt;/strong&gt;. Whenever a name is used, the interpreter walks the scope chain backwards looking for a &lt;code&gt;var&lt;/code&gt; statement for that name. If none is found, that variable is assumed to be global. If it&amp;#8217;s used in an assignment, the global is created if it doesn&amp;#8217;t already exist. This means that using or creating global variables in an anonymous closure is easy. Unfortunately, this leads to hard-to-manage code, as it&amp;#8217;s not obvious (to humans) which variables are global in a given file.&lt;/p&gt;

&lt;p&gt;Luckily, our anonymous function provides an easy alternative. By passing globals as parameters to our anonymous function, we &lt;strong&gt;import&lt;/strong&gt; them into our code, which is both &lt;strong&gt;clearer&lt;/strong&gt; and &lt;strong&gt;faster&lt;/strong&gt; than implied globals. Here&amp;#8217;s an example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(function ($, YAHOO) {
	// now have access to globals jQuery (as $) and YAHOO in this code
}(jQuery, YAHOO));&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id=&#39;module_export&#39;&gt;Module Export&lt;/h3&gt;

&lt;p&gt;Sometimes you don&amp;#8217;t just want to &lt;em&gt;use&lt;/em&gt; globals, but you want to &lt;em&gt;declare&lt;/em&gt; them. We can easily do this by exporting them, using the anonymous function&amp;#8217;s &lt;strong&gt;return value&lt;/strong&gt;. Doing so will complete the basic module pattern, so here&amp;#8217;s a complete example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var MODULE = (function () {
	var my = {},
		privateVariable = 1;

	function privateMethod() {
		// ...
	}

	my.moduleProperty = 1;
	my.moduleMethod = function () {
		// ...
	};

	return my;
}());&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice that we&amp;#8217;ve declared a global module named &lt;code&gt;MODULE&lt;/code&gt;, with two public properties: a method named &lt;code&gt;MODULE.moduleMethod&lt;/code&gt; and a variable named &lt;code&gt;MODULE.moduleProperty&lt;/code&gt;. In addition, it maintains &lt;strong&gt;private internal state&lt;/strong&gt; using the closure of the anonymous function. Also, we can easily import needed globals, using the pattern we learned above.&lt;/p&gt;

&lt;h2 id=&#39;advanced_patterns&#39;&gt;Advanced Patterns&lt;/h2&gt;

&lt;p&gt;While the above is enough for many uses, we can take this pattern farther and create some very powerful, extensible constructs. Lets work through them one-by-one, continuing with our module named &lt;code&gt;MODULE&lt;/code&gt;.&lt;/p&gt;

&lt;h3 id=&#39;augmentation&#39;&gt;Augmentation&lt;/h3&gt;

&lt;p&gt;One limitation of the module pattern so far is that the entire module must be in one file. Anyone who has worked in a large code-base understands the value of splitting among multiple files. Luckily, we have a nice solution to &lt;strong&gt;augment modules&lt;/strong&gt;. First, we import the module, then we add properties, then we export it. Here&amp;#8217;s an example, augmenting our &lt;code&gt;MODULE&lt;/code&gt; from above:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var MODULE = (function (my) {
	my.anotherMethod = function () {
		// added method...
	};

	return my;
}(MODULE));&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We use the &lt;code&gt;var&lt;/code&gt; keyword again for consistency, even though it&amp;#8217;s not necessary. After this code has run, our module will have gained a new public method named &lt;code&gt;MODULE.anotherMethod&lt;/code&gt;. This augmentation file will also maintain its own private internal state and imports.&lt;/p&gt;

&lt;h3 id=&#39;loose_augmentation&#39;&gt;Loose Augmentation&lt;/h3&gt;

&lt;p&gt;While our example above requires our initial module creation to be first, and the augmentation to happen second, that isn&amp;#8217;t always necessary. One of the best things a JavaScript application can do for performance is to load scripts asynchronously. We can create flexible multi-part modules that can load themselves in any order with &lt;strong&gt;loose augmentation&lt;/strong&gt;. Each file should have the following structure:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var MODULE = (function (my) {
	// add capabilities...

	return my;
}(MODULE || {}));&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this pattern, the &lt;code&gt;var&lt;/code&gt; statement is always necessary. Note that the import will create the module if it does not already exist. This means you can use a tool like &lt;a href=&#39;http://labjs.com/&#39;&gt;LABjs&lt;/a&gt; and load all of your module files in parallel, without needing to block.&lt;/p&gt;

&lt;h3 id=&#39;tight_augmentation&#39;&gt;Tight Augmentation&lt;/h3&gt;

&lt;p&gt;While loose augmentation is great, it does place some limitations on your module. Most importantly, you cannot override module properties safely. You also cannot use module properties from other files during initialization (but you can at run-time after intialization). &lt;strong&gt;Tight augmentation&lt;/strong&gt; implies a set loading order, but allows &lt;strong&gt;overrides&lt;/strong&gt;. Here is a simple example (augmenting our original &lt;code&gt;MODULE&lt;/code&gt;):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var MODULE = (function (my) {
	var old_moduleMethod = my.moduleMethod;

	my.moduleMethod = function () {
		// method override, has access to old through old_moduleMethod...
	};

	return my;
}(MODULE));&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here we&amp;#8217;ve overridden &lt;code&gt;MODULE.moduleMethod&lt;/code&gt;, but maintain a reference to the original method, if needed.&lt;/p&gt;

&lt;h3 id=&#39;cloning_and_inheritance&#39;&gt;Cloning and Inheritance&lt;/h3&gt;

&lt;pre&gt;&lt;code&gt;var MODULE_TWO = (function (old) {
	var my = {},
		key;

	for (key in old) {
		if (old.hasOwnProperty(key)) {
			my[key] = old[key];
		}
	}

	var super_moduleMethod = old.moduleMethod;
	my.moduleMethod = function () {
		// override method on the clone, access to super through super_moduleMethod
	};

	return my;
}(MODULE));&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This pattern is perhaps the &lt;strong&gt;least flexible&lt;/strong&gt; option. It does allow some neat compositions, but that comes at the expense of flexibility. As I&amp;#8217;ve written it, properties which are objects or functions will &lt;em&gt;not&lt;/em&gt; be duplicated, they will exist as one object with two references. Changing one will change the other. This could be fixed for objects with a recursive cloning process, but probably cannot be fixed for functions, except perhaps with &lt;code&gt;eval&lt;/code&gt;. Nevertheless, I&amp;#8217;ve included it for completeness.&lt;/p&gt;

&lt;h3 id=&#39;crossfile_private_state&#39;&gt;Cross-File Private State&lt;/h3&gt;

&lt;p&gt;One severe limitation of splitting a module across multiple files is that each file maintains its own private state, and does not get access to the private state of the other files. This can be fixed. Here is an example of a loosely augmented module that will &lt;strong&gt;maintain private state&lt;/strong&gt; across all augmentations:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var MODULE = (function (my) {
	var _private = my._private = my._private || {},
		_seal = my._seal = my._seal || function () {
			delete my._private;
			delete my._seal;
			delete my._unseal;
		},
		_unseal = my._unseal = my._unseal || function () {
			my._private = _private;
			my._seal = _seal;
			my._unseal = _unseal;
		};

	// permanent access to _private, _seal, and _unseal

	return my;
}(MODULE || {}));&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Any file can set properties on their local variable &lt;code&gt;_private&lt;/code&gt;, and it will be immediately available to the others. Once this module has loaded completely, the application should call &lt;code&gt;MODULE._seal()&lt;/code&gt;, which will prevent external access to the internal &lt;code&gt; _private&lt;/code&gt;. If this module were to be augmented again, further in the application&amp;#8217;s lifetime, one of the internal methods, in any file, can call &lt;code&gt; _unseal()&lt;/code&gt; before loading the new file, and call &lt;code&gt; _seal()&lt;/code&gt; again after it has been executed. This pattern occurred to me today while I was at work, I have not seen this elsewhere. I think this is a very useful pattern, and would have been worth writing about all on its own.&lt;/p&gt;

&lt;h3 id=&#39;submodules&#39;&gt;Sub-modules&lt;/h3&gt;

&lt;p&gt;Our final advanced pattern is actually the simplest. There are many good cases for creating sub-modules. It is just like creating regular modules:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;MODULE.sub = (function () {
	var my = {};
	// ...

	return my;
}());&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;While this may have been obvious, I thought it worth including. Sub-modules have all the advanced capabilities of normal modules, including augmentation and private state.&lt;/p&gt;

&lt;h2 id=&#39;conclusions&#39;&gt;Conclusions&lt;/h2&gt;

&lt;p&gt;Most of the advanced patterns can be combined with each other to create more useful patterns. If I had to advocate a route to take in designing a complex application, I&amp;#8217;d combine &lt;strong&gt;loose augmentation&lt;/strong&gt;, &lt;strong&gt;private state&lt;/strong&gt;, and &lt;strong&gt;sub-modules&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;I haven&amp;#8217;t touched on performance here at all, but I&amp;#8217;d like to put in one quick note: The module pattern is &lt;strong&gt;good for performance&lt;/strong&gt;. It minifies really well, which makes downloading the code faster. Using &lt;strong&gt;loose augmentation&lt;/strong&gt; allows easy non-blocking parallel downloads, which also speeds up download speeds. Initialization time is probably a bit slower than other methods, but worth the trade-off. Run-time performance should suffer no penalties so long as globals are imported correctly, and will probably gain speed in sub-modules by shortening the reference chain with local variables.&lt;/p&gt;

&lt;p&gt;To close, here&amp;#8217;s an example of a sub-module that loads itself dynamically to its parent (creating it if it does not exist). I&amp;#8217;ve left out private state for brevity, but including it would be simple. This code pattern allows an entire complex heirarchical code-base to be loaded completely in parallel with itself, sub-modules and all.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var UTIL = (function (parent, $) {
	var my = parent.ajax = parent.ajax || {};

	my.get = function (url, params, callback) {
		// ok, so I&amp;#39;m cheating a bit :)
		return $.getJSON(url, params, callback);
	};

	// etc...

	return parent;
}(UTIL || {}, jQuery));&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I hope this has been useful, and please leave a comment to share your thoughts. Now, go forth and write better, more modular JavaScript!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;This post was &lt;a href=&#39;http://ajaxian.com/archives/a-deep-dive-and-analysis-of-the-javascript-module-pattern&#39;&gt;featured on Ajaxian.com&lt;/a&gt;, and there is a little bit more discussion going on there as well, which is worth reading in addition to the comments below.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
            </div>
        </content>
    </entry>
    
    <entry>
        <title>Performance of === vs. ==</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/Performance-of-vs-.html"/>
        <id>http://www.adequatelygood.com/2010/3/Performance-of-vs-</id>
        <updated>2010-03-08T00:00:00-08:00</updated>
        <published>2010-03-08T00:00:00-08:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;p&gt;One particular weirdness and unpleasantry in JavaScript is the set of equality operators. Like virtually every language, JavaScript has the standard &lt;code&gt;==&lt;/code&gt;, &lt;code&gt;!=&lt;/code&gt;, &lt;code&gt;&amp;lt;&lt;/code&gt;, &lt;code&gt;&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;=&lt;/code&gt;, and &lt;code&gt;&amp;gt;=&lt;/code&gt; operators. However, &lt;code&gt;==&lt;/code&gt; and &lt;code&gt;!=&lt;/code&gt; are NOT the operators most would think they are. These operators do &lt;strong&gt;type coercion&lt;/strong&gt;, which is why &lt;code&gt;[0] == 0&lt;/code&gt; and &lt;code&gt;&amp;quot;\n0\t &amp;quot; == 0&lt;/code&gt; both evaluate to &lt;code&gt;true&lt;/code&gt;. This is considered, by sane people, to be a &lt;strong&gt;bad thing&lt;/strong&gt;. Luckily, JavaScript does provide a normal set of equality operators, which do what you expect: &lt;code&gt;===&lt;/code&gt; and &lt;code&gt;!==&lt;/code&gt;. It sucks that we need these at all, and &lt;code&gt;===&lt;/code&gt; is a pain to type, but at least &lt;code&gt;[0] !== 0&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;So, that&amp;#8217;s all well and good, but when making the decision to use &lt;code&gt;===&lt;/code&gt; instead of &lt;code&gt;==&lt;/code&gt; it&amp;#8217;s important to understand if there are any performance implications. Reasonable people, like myself, would expect the strict equality operators to be faster than their type-coercing counterparts, because the type coercion must take time. But, being &lt;a href=&#39;http://xkcd.com/242/&#39;&gt;a scientist&lt;/a&gt;, I had to set up an experiment to test this hypothesis.&lt;/p&gt;

&lt;h2 id=&#39;for_science&#39;&gt;For Science!&lt;/h2&gt;

&lt;p&gt;&lt;a href=&#39;http://www.bcherry.net/playground/comparisons&#39;&gt;My experiment&lt;/a&gt; times the execution time of 24 different tests, in the browser you view it in. These tests represent every permutation of the following factors:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Use&lt;/strong&gt;: Whether the result is computed and thrown away, or assigned into a local variable.&lt;/li&gt;

&lt;li&gt;&lt;strong&gt;Comparison&lt;/strong&gt;: Comparing integers vs. integers, strings vs. strings, and integers vs. strings.&lt;/li&gt;

&lt;li&gt;&lt;strong&gt;Operands&lt;/strong&gt;: Whether the operands are actually equal or unequal (with forced type coercion in the case of &lt;code&gt;===&lt;/code&gt;).&lt;/li&gt;

&lt;li&gt;&lt;strong&gt;Operator&lt;/strong&gt;: Using either &lt;code&gt;==&lt;/code&gt; or &lt;code&gt;===&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Note that I am specifically &lt;strong&gt;not&lt;/strong&gt; testing the relative performance when comparing against values like &lt;code&gt;null&lt;/code&gt;, &lt;code&gt;undefined&lt;/code&gt;, or &lt;code&gt;false&lt;/code&gt;. This is because those are falsy values which have even worse type coercion characteristics. Some integers and strings can, of course, also be falsy, such as &lt;code&gt;0&lt;/code&gt; or &lt;code&gt;&amp;quot;&amp;quot;&lt;/code&gt;, but these are normal values which occur during arithmetic or string comparison, so I&amp;#8217;ve tested with them.&lt;/p&gt;

&lt;p&gt;The tests were run over two million iterations, except in Internet Explorer, where it produced a long-running script error, so I cut it to 500,000 iterations. Here are the browser configurations I tested:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Mozilla Firefox 3.6 (Mac)&lt;/li&gt;

&lt;li&gt;Google Chrome 5 (Mac dev channel)&lt;/li&gt;

&lt;li&gt;Internet Explorer 8 (iterations reduced by 4x)&lt;/li&gt;

&lt;li&gt;Safari 4 (Mac)&lt;/li&gt;

&lt;li&gt;Opera 10.5 beta (Mac)&lt;/li&gt;

&lt;li&gt;Mozilla Firefox 3.6 (Mac) with Firebug open&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&#39;results&#39;&gt;Results&lt;/h2&gt;

&lt;p&gt;My results are &lt;a href=&#39;http://spreadsheets.google.com/pub?key=taW8f6kvj3kUVObtg4p9vqQ&amp;amp;output=html&#39;&gt;available as a Google spreadsheet here&lt;/a&gt;. It turns out that there is little practical performance difference between &lt;code&gt;==&lt;/code&gt; and &lt;code&gt;===&lt;/code&gt;. While the strict operator is marginally faster (roughly 10%) in most browsers when combined with explicit type conversion, such as &lt;code&gt;a === +b&lt;/code&gt;, the only real performance gains will come from avoiding type conversion entirely. &lt;strong&gt;Converting a string to an integer for comparison with another integer is significantly slower (up to 10x) than simple comparing two integers&lt;/strong&gt;. You should never allow integers to be stored as strings internally, as the type conversion will incur a performance penalty.&lt;/p&gt;

&lt;p&gt;While that was the basic takeaway from the numbers, I did find one interesting outlier when testing with Firefox. In Firefox, the comparison &lt;code&gt;a === +b&lt;/code&gt; is about 20x slower than the equivalent &lt;code&gt;a == b&lt;/code&gt; when &lt;code&gt;a&lt;/code&gt; is an integer and &lt;code&gt;b&lt;/code&gt; is a string integer. This result seems suspicious to me, and nothing similar occurred in any other browser. Oddly, when the Firebug script debugger is turned on, this result changes, and &lt;code&gt;a === +b&lt;/code&gt; becomes about 10% faster than the other. I&amp;#8217;m not sure what to make of this result, but it does serve as a reminder that integers should always be stored in numbers, not in strings.&lt;/p&gt;

&lt;h2 id=&#39;conclusion&#39;&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Not much surprise in these results, other than the Firefox result. But, it did help me avoid a nagging worry that I&amp;#8217;m silently slowing down my code whenever I use &lt;code&gt;===&lt;/code&gt; instead of &lt;code&gt;==&lt;/code&gt; in my JavaScript.&lt;/p&gt;

&lt;p&gt;Again, find the test &lt;a href=&#39;http://www.bcherry.net/playground/comparisons&#39;&gt;here&lt;/a&gt; and my results &lt;a href=&#39;http://spreadsheets.google.com/pub?key=taW8f6kvj3kUVObtg4p9vqQ&amp;amp;output=html&#39;&gt;here&lt;/a&gt;. I hope you found this information interesting. Let me know in the comments if you see different results than I got.&lt;/p&gt;
            </div>
        </content>
    </entry>
    
    <entry>
        <title>Minimum Timer Intervals in JavaScript</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/Minimum-Timer-Intervals-in-JavaScript.html"/>
        <id>http://www.adequatelygood.com/2010/2/Minimum-Timer-Intervals-in-JavaScript</id>
        <updated>2010-02-26T00:00:00-08:00</updated>
        <published>2010-02-26T00:00:00-08:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;p&gt;I was talking with a co-worker today about the behavior of &lt;code&gt;setTimeout&lt;/code&gt; and &lt;code&gt;setInterval&lt;/code&gt; when given a small interval, like &lt;code&gt;0&lt;/code&gt; or &lt;code&gt;1&lt;/code&gt;. The &lt;em&gt;expectation&lt;/em&gt; would be that the timer will fire in 0ms, or 1ms. However, as with &lt;a href=&#39;http://wtfjs.com&#39; target=&#39;_blank&#39;&gt;other things&lt;/a&gt; in JavaScript, the &lt;em&gt;reality&lt;/em&gt; is a bit different. It turns out that browsers actually have a &lt;strong&gt;minimum timer interval&lt;/strong&gt; which they can&amp;#8217;t work any faster than. John Resig wrote about &lt;a href=&#39;http://ejohn.org/blog/analyzing-timer-performance/&#39; target=&#39;_blank&#39;&gt;timer performance&lt;/a&gt; a few years back, and found this behavior. He&amp;#8217;s also covering it in more detail in his new book.&lt;/p&gt;

&lt;p&gt;But, I wasn&amp;#8217;t happy with data a few years old, so I decided to just go and write my own simple test suite, &lt;a href=&#39;http://www.bcherry.net/playground/settimeout&#39; target=&#39;_blank&#39;&gt;How Fast is setTimeout in Your Browser?&lt;/a&gt;. This page simply runs &lt;code&gt;setTimeout&lt;/code&gt; with an interval of 0, 1000 times, and averages the &lt;em&gt;real&lt;/em&gt; timeout experienced in each. Go ahead and check it out in your browser of choice.&lt;/p&gt;

&lt;h2 id=&#39;the_results&#39;&gt;The Results&lt;/h2&gt;

&lt;p&gt;Well, it turns out that things aren&amp;#8217;t so bad. Most browsers are in the &lt;strong&gt;10-15ms&lt;/strong&gt; range for their bottom limit, having improved in recent versions. Notable exceptions are Internet Explorer, which has the same bottom of around &lt;strong&gt;16ms&lt;/strong&gt; in all versions since IE6, and Google Chrome, which, at least since version 4, has a bottom limit closer to &lt;strong&gt;5ms&lt;/strong&gt; It&amp;#8217;s important to keep this limitation in mind when using &lt;code&gt;setTimeout&lt;/code&gt; or &lt;code&gt;setInterval&lt;/code&gt;. In particular, if you&amp;#8217;re looking for consistent timer intervals across browsers, you have to use something &lt;strong&gt;&amp;gt;15ms&lt;/strong&gt;. But, don&amp;#8217;t forget that JavaScript is single-threaded, and the timer won&amp;#8217;t execute while other code is executing. This means that in the following code sample, you can guarantee that the timer &lt;strong&gt;will not run&lt;/strong&gt; until the loop has completed. You cannot, however, guarantee precisely when that will happen, nor that it will be the next piece of code to run following the loop.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;setTimeout(function () { alert(&amp;quot;timer&amp;quot;); }, 0);
for (var i = 0; i &amp;lt; 1000; i += 1) {
	// something
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So it should be safe to use timers with an interval of 0ms when your only expectation is that the timer will fire as soon as it can, but not until after the current code path has completed. Relying on timers to respect the interval you give them is foolish, since, as I&amp;#8217;ve shown, they have a lower-bound, and since they wait even after firing, before executing, for other code to return.&lt;/p&gt;

&lt;h2 id=&#39;the_source_code&#39;&gt;The Source Code&lt;/h2&gt;

&lt;p&gt;This test is really simple. Here&amp;#8217;s the complete JavaScript source code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var target = document.getElementById(&amp;quot;target&amp;quot;),
	results = 0,
	iterations = 1000,
	i = 0;

function go() {
	var fn = function () {
			results += new Date().getTime() - d;
			i += 1;
			if (i &amp;lt; iterations) {
				go();
			} else {
				finish();
			}
		},
		d = new Date().getTime();
	setTimeout(fn, 0);
}

function finish() {
	target.innerHTML = &amp;quot;Average timer delay was &amp;lt;span class=\&amp;quot;num\&amp;quot;&amp;gt;&amp;quot; + results/iterations + 
		&amp;quot;&amp;lt;/span&amp;gt;ms, over &amp;lt;span class=\&amp;quot;num\&amp;quot;&amp;gt;&amp;quot; + iterations + &amp;quot;&amp;lt;/span&amp;gt; iterations.&amp;quot;;
}

go();&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And that&amp;#8217;s all there is to it. I hope you found this useful or interesting. Timers are very fickle, but also incredibly useful, so it&amp;#8217;s worth taking the time to understand what it is they do, and how they do it.&lt;/p&gt;
            </div>
        </content>
    </entry>
    
    <entry>
        <title>This Blog - Now With HTML5</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/This-Blog-Now-With-HTML5.html"/>
        <id>http://www.adequatelygood.com/2010/2/This-Blog-Now-With-HTML5</id>
        <updated>2010-02-19T00:00:00-08:00</updated>
        <published>2010-02-19T00:00:00-08:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;p&gt;Take a look at this web site. Notice anything out of the ordinary. Hopefully you don&amp;#8217;t, none of the layout or styling has changed noticeably recently. However, try a &amp;#8220;View Source&amp;#8221;. Now do you see something different? This page is now rendered with the following doctype:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That&amp;#8217;s right, this web site is now HTML5! In fact it even &lt;a href=&#39;http://validator.w3.org/check?uri=http%3A%2F%2Fwww.adequatelygood.com&#39;&gt;validates as HTML5&lt;/a&gt; successfully! If you dig past the doctype, you&amp;#8217;ll find all sorts of HTML5 semantic elements, including &lt;code&gt;&amp;lt;nav&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;article&amp;gt;&lt;/code&gt;, and &lt;code&gt;&amp;lt;time&amp;gt;&lt;/code&gt;, among others. Making the transition was reasonably painless with the help of Mark Pilgrim&amp;#8217;s &lt;a href=&#39;http://diveintohtml5.org/semantics.html&#39;&gt;excellent article on making the switch&lt;/a&gt;. For the most part, I just had to change a few elements and rewrite my CSS. There were a few headaches because &lt;a href=&#39;http://blueprintcss.org&#39;&gt;Blueprint CSS&lt;/a&gt; expects your grid elements to be &lt;code&gt;&amp;lt;div&amp;gt;&lt;/code&gt;s, but the following CSS added the right capabilities to my semantic elements to be compatible with Blueprint:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;header, footer, nav, article {
	float: left;
	margin-right: 10px;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Of course, IE doesn&amp;#8217;t understand the new HTML5 elements. Luckily, there&amp;#8217;s an easy solution. I chose to write it myself, since it&amp;#8217;s so simple, but there&amp;#8217;s a &lt;a href=&#39;http://html5shiv.googlecode.com/svn/trunk/html5.js&#39;&gt;publicly available complete solution&lt;/a&gt; you can use as well. Here&amp;#8217;s mine, for reference (in the &lt;code&gt;&amp;lt;head&amp;gt;&lt;/code&gt;):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;!-- IE HTML5 Compatibility --&amp;gt;
&amp;lt;!--[if IE]&amp;gt;
	&amp;lt;script type=&amp;quot;text/javascript&amp;quot;&amp;gt;
		(function () {
			var tags = &amp;quot;header hgroup nav article time footer&amp;quot;.split(&amp;quot; &amp;quot;),
				i = 0,
				l = tags.length;
			for (; i &amp;lt; l; i += 1) {
				document.createElement(tags[i]);
			}
		}());
	&amp;lt;/script&amp;gt;
&amp;lt;![endif]--&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And that&amp;#8217;s all there was to it! It&amp;#8217;s great that you can start using basic HTML5 &lt;em&gt;right now&lt;/em&gt; without any difficulties, and it will work in all browsers, even IE6! Of course, you can&amp;#8217;t just start using the more advanced features like &lt;code&gt;&amp;lt;video&amp;gt;&lt;/code&gt; or Web Workers, but basic markup is a great start.&lt;/p&gt;

&lt;p&gt;So what do you think? You ready to upgrade your own personal site?&lt;/p&gt;
            </div>
        </content>
    </entry>
    
    <entry>
        <title>Finding Improper JavaScript Globals</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/Finding-Improper-JavaScript-Globals.html"/>
        <id>http://www.adequatelygood.com/2010/2/Finding-Improper-JavaScript-Globals</id>
        <updated>2010-02-12T00:00:00-08:00</updated>
        <published>2010-02-12T00:00:00-08:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;p&gt;When I interview web developers, my first JavaScript question is usually the following:&lt;/p&gt;
&lt;blockquote&gt;What is the difference, in JavaScript, between &lt;code class=&quot;js inline&quot;&gt;x = 1&lt;/code&gt; and &lt;code class=&quot;js inline&quot;&gt;var x = 1&lt;/code&gt;.  Feel free to answer in as much or as little detail as you feel comfortable.&lt;/blockquote&gt;
&lt;p&gt;Most people would give an answer about how the &lt;code class=&quot;js inline&quot;&gt;var&lt;/code&gt; keyword makes something a local variable, omitting it makes it a global variable.  While I&#39;d love to hear about scope chains, the window object, and hear the term &quot;implied global&quot; in an answer, that basic answer is good enough.  It might not show a thorough knowledge of JavaScript, but at least it shows some level of understanding of the most common dangerous feature.&lt;/p&gt;
&lt;p&gt;There are three basic ways to make a global variable in JavaScript.  You can use &lt;code class=&quot;js inline&quot;&gt;var&lt;/code&gt; (&lt;strong&gt;declared global&lt;/strong&gt;), you can just assign to it without having declared it (&lt;strong&gt;implied global&lt;/strong&gt;), or you can set a property on the &lt;code class=&quot;js inline&quot;&gt;window&lt;/code&gt; object (&lt;strong&gt;window global&lt;/strong&gt;).  Here&#39;s those three:&lt;/p&gt;
&lt;pre class=&quot;js&quot;&gt;var x = 1; // declared global
y = 2; // implied global
window.z = 3; // window global&lt;/pre&gt;
&lt;p&gt;Implied globals are bad because they&#39;re hard to keep track of, and their declarations aren&#39;t &lt;a href=&quot;http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting&quot;&gt;hoisted&lt;/a&gt;.  I don&#39;t like window globals either, because mixing &lt;code class=&quot;js inline&quot;&gt;window.x&lt;/code&gt; and &lt;code class=&quot;js inline&quot;&gt;x&lt;/code&gt; is bad form.  In my opinion, &lt;strong&gt;all globals should be declared globals&lt;/strong&gt;.  Unfortunately, JavaScript makes this really hard to maintain.  There are tools like &lt;a href=&quot;http://www.jslint.com/&quot;&gt;JSLint&lt;/a&gt; that will perform analysis of your code and help you out, but it can&#39;t do an entire code base at once, at least not easily.&lt;/p&gt;
&lt;p&gt;I&#39;ve written a tool that performs &lt;strong&gt;run-time analysis&lt;/strong&gt; of your application, and finds all of the improperly declared globals (both implied and window globals).  Check out a demo &lt;a href=&quot;http://www.bcherry.net/badglobals&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Introducing badglobals.js&lt;/h2&gt;
&lt;p&gt;&lt;a href=&quot;http://www.bcherry.net/static/lib/js/badglobals.js&quot;&gt;badglobals.js&lt;/a&gt; is a tool for finding all of the improperly declared global variables in your application.  Using it is simple, but don&#39;t use it in production code (see &quot;How It Works&quot; below).&lt;/p&gt;
&lt;ol&gt;
	&lt;li&gt;Include &lt;a href=&quot;http://www.bcherry.net/static/lib/js/badglobals.js&quot;&gt;badglobals.js&lt;/a&gt; in your page, before any other scripts.&lt;/li&gt;
	&lt;li&gt;When you want to do analysis, open Firebug and run &lt;code class=&quot;js inline&quot;&gt;BADGLOBALS.check()&lt;/code&gt;.&lt;/li&gt;
	&lt;li&gt;You&#39;ll see a warning statement in the console for every bad global found.  These contain both the name, and the value.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In addition, there are a few slightly more advanced features you might be interested in.&lt;/p&gt;
&lt;h3&gt;Exclusions&lt;/h3&gt;
&lt;p&gt;If you have some globals you don&#39;t want to be reported about (such as third-party libraries), you can easily exclude them manually.  Before you run the check, just call &lt;code class=&quot;js inline&quot;&gt;.exclude&lt;/code&gt;, like so:&lt;/p&gt;
&lt;pre class=&quot;js&quot;&gt;BADGLOBALS.exclude(&quot;jQuery&quot;, &quot;$&quot;, &quot;YAHOO&quot;);&lt;/pre&gt;
&lt;p&gt;Feel free to call this method as many times as you&#39;d like, it always adds, and never removes.  By default, all browser built-ins are excluded (these are found when the script is included).  Sometimes, the variable &lt;code class=&quot;js inline&quot;&gt;_firebug&lt;/code&gt; enters after the script include, and shows in the report.  You should exclude this.&lt;/p&gt;
&lt;h3&gt;Report Object&lt;/h3&gt;
&lt;p&gt;While the warnings are probably enough, badglobals.js also builds a report object, containing more information.  Access it by calling &lt;code class=&quot;js inline&quot;&gt;BADGLOBALS.report()&lt;/code&gt;.  This will run &lt;code class=&quot;js inline&quot;&gt;.check()&lt;/code&gt; if it has not run already.  The report object has the following properties:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;&lt;strong&gt;bad:&lt;/strong&gt; An array of the names of the bad globals found.&lt;/li&gt;
	&lt;li&gt;&lt;strong&gt;good:&lt;/strong&gt; An array of the names of the good globals found.&lt;/li&gt;
	&lt;li&gt;&lt;strong&gt;skipped:&lt;/strong&gt; An array of the names of the globals that were not checked.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;And that&#39;s all there is to badglobals.js.  It&#39;s really simple to use, but remarkably effective.&lt;/p&gt;
&lt;h2&gt;How It Works&lt;/h2&gt;
&lt;p&gt;badglobals.js works because of one key difference between implied/window globals and declared globals:  &lt;strong&gt;declared globals cannot be deleted&lt;/strong&gt;.  This is because using &lt;code class=&quot;js inline&quot;&gt;var&lt;/code&gt; causes the internal property [[DontDelete]] to be set.&lt;/p&gt;
&lt;pre class=&quot;js&quot;&gt;var x = 1;
y = 2;
window.z = 3;

delete x; // false
delete y; // true
delete z; // true

x; // 1
y; // undefined
z; // undefined&lt;/pre&gt;
&lt;p&gt;badglobals.js simply tries to delete every property of window (skipping the built-ins, of course).  If the delete succeeds, it was declared wrong.  It always puts it back, but I wouldn&#39;t trust this to run in production code, because it just &lt;em&gt;seems dangerous&lt;/em&gt;.  Here&#39;s the core section of badglobals.js:&lt;/p&gt;
&lt;pre class=&quot;js&quot;&gt;for (prop in window) {
	if (window.hasOwnProperty(prop)) {
		if (skip.indexOf(prop) &gt;= 0 || exclude.indexOf(prop) &gt;= 0) {
			skipped.push(prop);
		} else {
			val = window[prop];
			if (delete window[prop]) {
				console.warn(&quot;Found non-var global %o with value %o&quot;, prop, val);
				bad.push(prop);
				try {
					window[prop] = val;
				} catch (e) {
					console.error(&quot;Oops, there was an error putting %o back :(&quot;, prop);
				}
			} else {
				good.push(prop);
			}
		}
	}
}&lt;/pre&gt;
&lt;h3&gt;Browser Support&lt;/h3&gt;
&lt;p&gt;This script will not work in Internet Explorer, because I use the array &lt;code class=&quot;js inline&quot;&gt;indexOf&lt;/code&gt; method, among other things.  I also think IE doesn&#39;t exactly follow the standard when it comes to &lt;code class=&quot;js inline&quot;&gt;delete&lt;/code&gt;, so the checks might not work.  I don&#39;t consider this a problem, because this is a &lt;strong&gt;developer tool&lt;/strong&gt;, not production code.  You&#39;ll find the complete set of bad globals with Firefox or Chrome, so you should not need to check in Internet Explorer as well.  I have not tested it in Opera, but the &lt;code class=&quot;js inline&quot;&gt;console&lt;/code&gt; references will certainly fail.&lt;/p&gt;
&lt;h3&gt;Thanks to...&lt;/h3&gt;
&lt;p&gt;I got the idea for this tool from the &lt;a href=&quot;http://perfectionkills.com/understanding-delete/&quot;&gt;excellent article&lt;/a&gt; on &lt;code class=&quot;js inline&quot;&gt;delete&lt;/code&gt; by kangax, over at &lt;a href=&quot;http://perfectionkills.com&quot;&gt;his blog&lt;/a&gt;.  If you haven&#39;t read that article, you really should.  The depth and quality is incredible.&lt;/p&gt;
&lt;h2&gt;Get badglobals.js&lt;/h2&gt;
&lt;p&gt;Here are the links, one more time:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;&lt;a href=&quot;http://www.bcherry.net/static/lib/js/badglobals.js&quot;&gt;Raw Script&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://github.com/bcherry/bcherry/blob/master/bcherry-web/static/lib/js/badglobals.js&quot;&gt;Script at GitHub&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://www.bcherry.net/badglobals&quot;&gt;Demo Page&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

            </div>
        </content>
    </entry>
    
    <entry>
        <title>JavaScript Scoping and Hoisting</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html"/>
        <id>http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting</id>
        <updated>2010-02-08T00:00:00-08:00</updated>
        <published>2010-02-08T00:00:00-08:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;p&gt;Do you know what value will be alerted if the following is executed as a JavaScript program?&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var foo = 1;
function bar() {
	if (!foo) {
		var foo = 10;
	}
	alert(foo);
}
bar();&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If it surprises you that the answer is &amp;#8220;10&amp;#8221;, then this one will probably really throw you for a loop:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var a = 1;
function b() {
	a = 10;
	return;
	function a() {}
}
b();
alert(a);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here, of course, the browser will alert &amp;#8220;1&amp;#8221;. So what&amp;#8217;s going on here? While it might seem strange, dangerous, and confusing, this is actually a powerful and expressive feature of the language. I don&amp;#8217;t know if there is a standard name for this specific behavior, but I&amp;#8217;ve come to like the term &amp;#8220;hoisting&amp;#8221;. This article will try to shed some light on this mechanism, but first lets take a necessary detour to understand JavaScript&amp;#8217;s scoping.&lt;/p&gt;

&lt;h2 id=&#39;scoping_in_javascript&#39;&gt;Scoping in JavaScript&lt;/h2&gt;

&lt;p&gt;One of the sources of most confusion for JavaScript beginners is scoping. Actually, it&amp;#8217;s not just beginners. I&amp;#8217;ve met a lot of experienced JavaScript programmers who don&amp;#8217;t fully understand scoping. The reason scoping is so confusing in JavaScript is because it looks like a C-family language. Consider the following C program:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;
int main() {
	int x = 1;
	printf(&amp;quot;%d, &amp;quot;, x); // 1
	if (1) {
		int x = 2;
		printf(&amp;quot;%d, &amp;quot;, x); // 2
	}
	printf(&amp;quot;%d\n&amp;quot;, x); // 1
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The output from this program will be &lt;code&gt;1, 2, 1&lt;/code&gt;. This is because C, and the rest of the C family, has &lt;strong&gt;block-level scope&lt;/strong&gt;. When control enters a block, such as the &lt;code&gt;if&lt;/code&gt; statement, new variables can be declared within that scope, without affecting the outer scope. This is not the case in JavaScript. Try the following in Firebug:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var x = 1;
console.log(x); // 1
if (true) {
	var x = 2;
	console.log(x); // 2
}
console.log(x); // 2&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this case, Firebug will show &lt;code&gt;1, 2, 2&lt;/code&gt;. This is because JavaScript has &lt;strong&gt;function-level scope&lt;/strong&gt;. This is radically different from the C family. Blocks, such as &lt;code&gt;if&lt;/code&gt; statements, &lt;strong&gt;do not&lt;/strong&gt; create a new scope. Only functions create a new scope.&lt;/p&gt;

&lt;p&gt;To a lot of programmers who are used to languages like C, C++, C#, or Java, this is unexpected and unwelcome. Luckily, because of the flexibility of JavaScript functions, there is a workaround. If you must create temporary scopes within a function, do the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function foo() {
	var x = 1;
	if (x) {
		(function () {
			var x = 2;
			// some other code
		}());
	}
	// x is still 1.
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This method is actually quite flexible, and can be used anywhere you need a temporary scope, not just within block statements. However, I strongly recommend that you take the time to really understand and appreciate JavaScript scoping. It&amp;#8217;s quite powerful, and one of my favorite features of the language. If you understand scoping, hoisting will make a lot more sense to you.&lt;/p&gt;

&lt;h2 id=&#39;declarations_names_and_hoisting&#39;&gt;Declarations, Names, and Hoisting&lt;/h2&gt;

&lt;p&gt;In JavaScript, a name enters a scope in one of four basic ways:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Language-defined:&lt;/strong&gt; All scopes are, by default, given the names &lt;code&gt;this&lt;/code&gt; and &lt;code&gt;arguments&lt;/code&gt;.&lt;/li&gt;

&lt;li&gt;&lt;strong&gt;Formal parameters:&lt;/strong&gt; Functions can have named formal parameters, which are scoped to the body of that function.&lt;/li&gt;

&lt;li&gt;&lt;strong&gt;Function declarations:&lt;/strong&gt; These are of the form &lt;code&gt;function foo() {}&lt;/code&gt;.&lt;/li&gt;

&lt;li&gt;&lt;strong&gt;Variable declarations:&lt;/strong&gt; These take the form &lt;code&gt;var foo;&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Function declarations and variable declarations are always moved (&amp;#8220;hoisted&amp;#8221;) invisibly to the top of their containing scope by the JavaScript interpreter. Function parameters and language-defined names are, obviously, already there. This means that code like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function foo() {
	bar();
	var x = 1;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;is actually interpreted like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function foo() {
	var x;
	bar();
	x = 1;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It turns out that it doesn&amp;#8217;t matter whether the line that contains the declaration would ever be executed. The following two functions are equivalent:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function foo() {
	if (false) {
		var x = 1;
	}
	return;
	var y = 1;
}
function foo() {
	var x, y;
	if (false) {
		x = 1;
	}
	return;
	y = 1;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice that the assignment portion of the declarations were not hoisted. Only the name is hoisted. This is not the case with function declarations, where the entire function body will be hoisted as well. But remember that there are two normal ways to declare functions. Consider the following JavaScript:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function test() {
	foo(); // TypeError &amp;quot;foo is not a function&amp;quot;
	bar(); // &amp;quot;this will run!&amp;quot;
	var foo = function () { // function expression assigned to local variable &amp;#39;foo&amp;#39;
		alert(&amp;quot;this won&amp;#39;t run!&amp;quot;);
	}
	function bar() { // function declaration, given the name &amp;#39;bar&amp;#39;
		alert(&amp;quot;this will run!&amp;quot;);
	}
}
test();&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this case, only the function declaration has its body hoisted to the top. The name &amp;#8216;foo&amp;#8217; is hoisted, but the body is left behind, to be assigned during execution.&lt;/p&gt;

&lt;p&gt;That covers the basics of hoisting, which is not as complex or confusing as it seems. Of course, this being JavaScript, there is a little more complexity in certain special cases.&lt;/p&gt;

&lt;h3 id=&#39;name_resolution_order&#39;&gt;Name Resolution Order&lt;/h3&gt;

&lt;p&gt;The most important special case to keep in mind is name resolution order. Remember that there are four ways for names to enter a given scope. The order I listed them above is the order they are resolved in. In general, if a name has already been defined, it is never overridden by another property of the same name. This means that a function declaration takes priority over a variable declaration. This does not mean that an assignment to that name will not work, just that the declaration portion will be ignored. There are a few exceptions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The built-in name &lt;code&gt;arguments&lt;/code&gt; behaves oddly. It seems to be declared following the formal parameters, but before function declarations. This means that a formal parameter with the name &lt;code&gt;arguments&lt;/code&gt; will take precedence over the built-in, even if it is undefined. This is a bad feature. Don&amp;#8217;t use the name &lt;code&gt;arguments&lt;/code&gt; as a formal parameter.&lt;/li&gt;

&lt;li&gt;Trying to use the name &lt;code&gt;this&lt;/code&gt; as an identifier anywhere will cause a SyntaxError. This is a good feature.&lt;/li&gt;

&lt;li&gt;If multiple formal parameters have the same name, the one occurring latest in the list will take precedence, even if it is undefined.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&#39;named_function_expressions&#39;&gt;Named Function Expressions&lt;/h3&gt;

&lt;p&gt;You can give names to functions defined in function expressions, with syntax like a function declaration. This does not make it a function declaration, and the name is not brought into scope, nor is the body hoisted. Here&amp;#8217;s some code to illustrate what I mean:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;foo(); // TypeError &amp;quot;foo is not a function&amp;quot;
bar(); // valid
baz(); // TypeError &amp;quot;baz is not a function&amp;quot;
spam(); // ReferenceError &amp;quot;spam is not defined&amp;quot;

var foo = function () {}; // anonymous function expression (&amp;#39;foo&amp;#39; gets hoisted)
function bar() {}; // function declaration (&amp;#39;bar&amp;#39; and the function body get hoisted)
var baz = function spam() {}; // named function expression (only &amp;#39;baz&amp;#39; gets hoisted)

foo(); // valid
bar(); // valid
baz(); // valid
spam(); // ReferenceError &amp;quot;spam is not defined&amp;quot;&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&#39;how_to_code_with_this_knowledge&#39;&gt;How to Code With This Knowledge&lt;/h2&gt;

&lt;p&gt;Now that you understand scoping and hoisting, what does that mean for coding in JavaScript? The most important thing is to always declare your variables with a &lt;code&gt;var&lt;/code&gt; statement. I &lt;strong&gt;strongly&lt;/strong&gt; recommend that you have &lt;em&gt;exactly one&lt;/em&gt; &lt;code&gt;var&lt;/code&gt; statement per scope, and that it be at the top. If you force yourself to do this, you will never have hoisting-related confusion. However, doing this can make it hard to keep track of which variables have actually been declared in the current scope. I recommend using &lt;a href=&#39;http://www.jslint.com&#39; target=&#39;_blank&#39;&gt;JSLint&lt;/a&gt; with the &lt;code&gt;onevar&lt;/code&gt; option to enforce this. If you&amp;#8217;ve done all of this, your code should look something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/*jslint onevar: true [...] */
function foo(a, b, c) {
    var x = 1,
    	bar,
    	baz = &amp;quot;something&amp;quot;;
}&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&#39;what_the_standard_says&#39;&gt;What the Standard Says&lt;/h2&gt;

&lt;p&gt;I find that it&amp;#8217;s often useful to just consult the &lt;a href=&#39;http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf&#39; target=&#39;_blank&#39;&gt;ECMAScript Standard (pdf)&lt;/a&gt; directly to understand how these things work. Here&amp;#8217;s what it has to say about variable declarations and scope (section 12.2.2 in the older version):&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;If the variable statement occurs inside a FunctionDeclaration, the variables are defined with function-local scope in that function, as described in section 10.1.3. Otherwise, they are defined with global scope (that is, they are created as members of the global object, as described in section 10.1.3) using property attributes { DontDelete }. Variables are created when the execution scope is entered. A Block does not define a new execution scope. Only Program and FunctionDeclaration produce a new scope. Variables are initialised to undefined when created. A variable with an Initialiser is assigned the value of its AssignmentExpression when the VariableStatement is executed, not when the variable is created.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I hope this article has shed some light on one of the most common sources of confusion to JavaScript programmers. I have tried to be as thorough as possible, to avoid creating more confusion. If I have made any mistakes or have large omissions, please let me know.&lt;/p&gt;
            </div>
        </content>
    </entry>
    
    <entry>
        <title>Search/Replace in the DOM with jQuery</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/SearchReplace-in-the-DOM-with-jQuery.html"/>
        <id>http://www.adequatelygood.com/2010/2/SearchReplace-in-the-DOM-with-jQuery</id>
        <updated>2010-02-03T00:00:00-08:00</updated>
        <published>2010-02-03T00:00:00-08:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;p&gt;Ever had a need to to a text search/replace through the DOM?  For articles in drafting on this blog I often use the form (TODO: something) as notes for myself to do some more research.  I don&#39;t want them sticking around in the text I publish, so I highlighted them red (only for myself).  Here&#39;s the script I used to accomplish that:&lt;/p&gt;
&lt;pre class=&quot;js inline&quot;&gt;jQuery(function () {
	jQuery(&quot;:contains(TODO)&quot;).not(&quot;:has(:contains(TODO))&quot;).each(function () {
		var that = $(this),
			html = that.html();

		html = html.replace(/(\(TODO:.*?\))/g, &quot;&amp;lt;span class=\&quot;todo\&quot;&amp;gt;$1&amp;lt;/span&amp;gt;&quot;);
		that.html(html);
	});
});&lt;/pre&gt;
&lt;p&gt;The trick is to find only the nodes that contain the actual text, not ancestors of such nodes, which is what you would get with just &lt;code class=&quot;js inline&quot;&gt;jQuery(&quot;:contains(TOOD)&quot;)&lt;/code&gt;.  Filtering with &lt;code class=&quot;js inline&quot;&gt;.not(&quot;:has(:contains(TODO))&quot;)&lt;/code&gt; ensures you&#39;ve got the bottom most ones.  I tried doing this with the &lt;code class=&quot;js inline&quot;&gt;&quot;:not()&quot;&lt;/code&gt; filter, but it didn&#39;t work.  I guess that might be a jQuery bug, but the &lt;code class=&quot;js inline&quot;&gt;.not()&lt;/code&gt; method is a fine alternative.&lt;/p&gt;
            </div>
        </content>
    </entry>
    
    <entry>
        <title>Why JavaScript&#39;s &quot;new&quot; Keyword Sucks</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/Why-JavaScripts-new-Keyword-Sucks.html"/>
        <id>http://www.adequatelygood.com/2010/2/Why-JavaScripts-new-Keyword-Sucks</id>
        <updated>2010-02-01T00:00:00-08:00</updated>
        <published>2010-02-01T00:00:00-08:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;pre&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; function F() { return function inner() { return &amp;quot;inner invoked&amp;quot;; }; }
&amp;gt;&amp;gt;&amp;gt; F()
inner()
&amp;gt;&amp;gt;&amp;gt; F()()
&amp;quot;inner invoked&amp;quot;
&amp;gt;&amp;gt;&amp;gt; new F
inner()
&amp;gt;&amp;gt;&amp;gt; new F()
inner()
&amp;gt;&amp;gt;&amp;gt; (new F)
inner()
&amp;gt;&amp;gt;&amp;gt; (new F)()
&amp;quot;inner invoked&amp;quot;
&amp;gt;&amp;gt;&amp;gt; new (F())
{ }
&amp;gt;&amp;gt;&amp;gt; new ((F)())
{ }
&amp;gt;&amp;gt;&amp;gt; (new F())()
&amp;quot;inner invoked&amp;quot;&lt;/code&gt;&lt;/pre&gt;
            </div>
        </content>
    </entry>
    
    <entry>
        <title>Preloading JS and CSS as Print Stylesheets</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/Preloading-JS-and-CSS-as-Print-Stylesheets.html"/>
        <id>http://www.adequatelygood.com/2010/1/Preloading-JS-and-CSS-as-Print-Stylesheets</id>
        <updated>2010-01-29T00:00:00-08:00</updated>
        <published>2010-01-29T00:00:00-08:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;p&gt;&lt;em&gt;&lt;strong&gt;UPDATE: This technique has turned out to be dangerous in Chrome.  It seems that Chrome will load the JS files into the cache, but  then set an implied type=&quot;text/css&quot; on them.  This means that it will refuse to re-use them as JavaScript on future pages, until they have left the cache.  I can no longer recommend this technique, but hope that it was at least interesting.  I&#39;ll be working on a follow-up post about alternatives.&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;One of Yahoo&#39;s &lt;a href=&quot;http://developer.yahoo.com/performance/rules.html&quot; target=&quot;_blank&quot;&gt;Best Practices for Speeding Up Your Web Site&lt;/a&gt; is &quot;Preload Components&quot;.  Most people are already familiar with doing this for images.  Code for that usually looks like this:&lt;/p&gt;
&lt;p&gt;&lt;pre class=&quot;js&quot;&gt;var img = Image();
img.src = &quot;/path/to/something.jpg&quot;;&lt;/pre&gt;&lt;/p&gt;
&lt;p&gt;This code works in all browsers, and causes that image to be downloaded and placed in the browser&#39;s cache.&lt;/p&gt;
&lt;p&gt;But what if we want to go further?  For a lot of today&#39;s big applications, images are no longer the only bandwidth hog.  An application I work on has more than 2MB worth of JavaScript, CSS, and data (stored in JavaScript files).  We found that users on slow connections could take up to &lt;em&gt;60 seconds&lt;/em&gt; to load our application for the first time!  Obviously, we could benefit from intelligently pre-loading this data in the background, on an earlier page where they don&#39;t need it yet.  But how?&lt;/p&gt;
&lt;p&gt;My first attempt was just to use the &lt;code class=&quot;js inline&quot;&gt;Image()&lt;/code&gt; method above, but point at our text files instead.  This didn&#39;t work in Firefox.  I&#39;m not sure why, but those files never appeared in the cache with that method.  So our next idea was to use &lt;code class=&quot;html inline&quot;&gt;&amp;lt;iframe&amp;gt;&lt;/code&gt; tags.  This worked great, until we tried it in Internet Explorer.  IE chose to warn the user that our page was trying to download data they didn&#39;t ask for, and blocked the downloads until they approved them.  Obviously, this wouldn&#39;t work either.&lt;/p&gt;
&lt;p&gt;This left us scratching our heads, but we eventually had a breakthrough.  There is one other tag that is used to include text files in a web page.  That&#39;s the &lt;code class=&quot;html inline&quot;&gt;&amp;lt;link rel=&quot;stylesheet&quot;&amp;gt;&lt;/code&gt; tag.  But this couldn&#39;t possibly work with JavaScript, could it?  It turns out it could!&lt;/p&gt;
&lt;pre class=&quot;js&quot;&gt;var preload = function (file) {
	var elem,
		tag = &quot;link&quot;,
		attr = &quot;href&quot;,
		extra = &quot; rel=\&quot;stylesheet\&quot; media=\&quot;print\&quot; &quot;,
		target = &quot;head&quot;;

	elem = jQuery([&quot;&amp;lt;&quot;, tag, extra, attr, &quot;=\&quot;&quot;, file, &quot;\&quot;&amp;lt;&amp;gt;/&quot;, tag, &quot;&amp;gt;&quot;].join(&#39;&#39;));
	elem.load(function () {
		elem.remove();
	});
	jQuery(target).append(elem);

	return elem;
};&lt;/pre&gt;
&lt;p&gt;This function creates a temporary &lt;code class=&quot;html inline&quot;&gt;&amp;lt;link&amp;gt;&lt;/code&gt; tag in the &lt;code class=&quot;html inline&quot;&gt;&amp;lt;head&amp;gt;&lt;/code&gt; of your page, pointing at the requested file.  To work across all browsers, we needed to give it the rel=&quot;stylesheet&quot; attribute.  To not cause preloaded CSS files to try and apply themselves to the current page, or trigger a re-flow, we added media=&quot;print&quot;.  Once the element has loaded, it removes itself from the DOM, but the file remains in the browser&#39;s cache.  While this example relies on the jQuery library, there is no reason it could not be easily re-written without such a dependency, or written as a jQuery plugin (providing &lt;code class=&quot;js inline&quot;&gt;jQuery.preload()&lt;/code&gt;).&lt;/p&gt;
&lt;p&gt;This technique cut our aforementioned page load from 60s to 20s, over a slow connection.  I think this is a complete solution, and seems to work in all major browsers.  What do you think?&lt;/p&gt;
            </div>
        </content>
    </entry>
    
    <entry>
        <title>Consul.js, Simple Logging Abstraction</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/Consuljs-Simple-Logging-Abstraction.html"/>
        <id>http://www.adequatelygood.com/2009/11/Consuljs-Simple-Logging-Abstraction</id>
        <updated>2009-11-28T00:00:00-08:00</updated>
        <published>2009-11-28T00:00:00-08:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;p&gt;I&#39;ve been reading &lt;em&gt;Coders At Work&lt;/em&gt; by Peter Seibel, and one question he asks in every interview is &quot;How do you debug - print statements, debugger like gdb, or something else?&quot;.  For me, print statements are my first tool for any situation.  That&#39;s why Firebug is so crucial to my work on the web, because writing and debugging advanced JavaScript would be a nightmare without it.  While working on code, my files are littered with &lt;code class=&quot;js inline&quot;&gt;console.log()&lt;/code&gt; statements and the like.  Unfortunately, shipping code with these statements is a no-no, so I usually pull them out.  Frustrated with this process, I decided to build an alternative and throw some new features in along the way.&lt;/p&gt;

&lt;p&gt;&lt;pre class=&quot;js&quot;&gt;consul.log(&quot;This is a log message&quot;);
consul.warn(&quot;I even support fancier %s features like %o.&quot;, &quot;Firebug&quot;, &quot;format strings&quot;);
consul.turnOff();
consul.assert(false, &quot;I&#39;m off, so you won&#39;t see this error fire.&quot;);
consul.turnOn();
consul.info(&quot;See this message in Firebug, Chrome, Safari, Firebug Lite, IE8, and Opera.&quot;)&lt;/pre&gt;&lt;/p&gt;

&lt;p&gt;Meet &lt;a href=&quot;http://github.com/bcherry/bcherry/blob/master/bcherry-web/static/lib/js/consul.js&quot;&gt;consul.js&lt;/a&gt;, which acts as a wrapper for the standard &lt;code class=&quot;js inline&quot;&gt;window.console&lt;/code&gt; features from &lt;a href=&quot;http://getfirebug.com/wiki/index.php/Console_API&quot;&gt;Firebug&lt;/a&gt;.  Using it is simple, as you see above.  Just include the file, and start using &lt;code class=&quot;js inline&quot;&gt;consul&lt;/code&gt; instead of &lt;code class=&quot;js inline&quot;&gt;console&lt;/code&gt;.  You can easily turn it off for your live code, but have easy access to the messages by simply turning it back on from the command line.&lt;/p&gt;

&lt;p&gt;In addition to what you&#39;d expect, using consul.js ensures that you can view your messages and assertions in any browser.  Currently, it supports the latest versions of Firebug, Chrome, and Safari (you&#39;ll need the JS console for the latter two).  I also built in support for most commands in Internet Explorer 8, provided you&#39;ve got the developer tools open.  Opera Dragonfly support was harder, since it doesn&#39;t offer much logging features.  However, most things work through &lt;code class=&quot;js inline&quot;&gt;window.opera.postError()&lt;/code&gt;.  Regardless, for IE and Opera (as well as any other browser), it checks for Firebug Lite and outputs there if it finds it, instead of the built-in dev tools.&lt;/p&gt;

&lt;p&gt;For a list of features and browser support, look no further than the code itself:&lt;/p&gt;

&lt;p&gt;&lt;pre class=&quot;js&quot;&gt;var consoleFuncs = {
	log         : b(&quot;firebug&quot;, &quot;firebuglite&quot;, &quot;chromium&quot;, &quot;safari&quot;, &quot;ie&quot;, &quot;opera&quot;),
	debug       : b(&quot;firebug&quot;, &quot;firebuglite&quot;, &quot;chromium&quot;, &quot;safari&quot;),
	info        : b(&quot;firebug&quot;, &quot;firebuglite&quot;, &quot;chromium&quot;, &quot;safari&quot;, &quot;ie&quot;, &quot;opera&quot;),
	warn        : b(&quot;firebug&quot;, &quot;firebuglite&quot;, &quot;chromium&quot;, &quot;safari&quot;, &quot;ie&quot;, &quot;opera&quot;),
	error       : b(&quot;firebug&quot;, &quot;firebuglite&quot;, &quot;chromium&quot;, &quot;safari&quot;, &quot;ie&quot;, &quot;opera&quot;),
	assert      : b(&quot;firebug&quot;, &quot;firebuglite&quot;, &quot;chromium&quot;, &quot;safari&quot;, &quot;ie&quot;, &quot;opera&quot;),
	dir         : b(&quot;firebug&quot;, &quot;firebuglite&quot;, &quot;chromium&quot;, &quot;safari&quot;),
	dirxml      : b(&quot;firebug&quot;, &quot;firebuglite&quot;, &quot;chromium&quot;, &quot;safari&quot;),
	trace       : b(&quot;firebug&quot;, &quot;firebuglite&quot;, &quot;chromium&quot;, &quot;safari&quot;),
	group       : b(&quot;firebug&quot;, &quot;firebuglite&quot;, &quot;chromium&quot;, &quot;safari&quot;),
	groupEnd    : b(&quot;firebug&quot;, &quot;firebuglite&quot;, &quot;chromium&quot;, &quot;safari&quot;),
	time        : b(&quot;firebug&quot;, &quot;firebuglite&quot;, &quot;chromium&quot;, &quot;safari&quot;),
	timeEnd     : b(&quot;firebug&quot;, &quot;firebuglite&quot;, &quot;chromium&quot;, &quot;safari&quot;),
	count       : b(&quot;firebug&quot;, &quot;firebuglite&quot;, &quot;chromium&quot;, &quot;safari&quot;)
};&lt;/pre&gt;&lt;/p&gt;

&lt;p&gt;If a function is not supported in a particular browser, it will simply be ignored, rather than throwing an error.&lt;/p&gt;

&lt;p&gt;So &lt;a href=&quot;http://github.com/bcherry/bcherry/blob/master/bcherry-web/static/lib/js/consul.js&quot;&gt;give it a shot&lt;/a&gt;, and let me know what you think!  This tool helped me build this blog&#39;s front-end code, and has already been ported into the code I use at work, so I can take advantage of the same tool.  I think it&#39;s a big win for JavaScript developers who rely on the Firebug console, and introduces a lot of new flexibility without degrading simplicity.&lt;/p&gt;
            </div>
        </content>
    </entry>
    
    <entry>
        <title>JS Find-and-Replace with Split/Join</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/JS-Find-and-Replace-with-SplitJoin.html"/>
        <id>http://www.adequatelygood.com/2009/11/JS-Find-and-Replace-with-SplitJoin</id>
        <updated>2009-11-05T00:00:00-08:00</updated>
        <published>2009-11-05T00:00:00-08:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;p&gt;&lt;strong&gt;&lt;em&gt;Update: This advice is now totally out-of-date and wrong. Just use &lt;code&gt;replace&lt;/code&gt;. As &lt;a href=&#39;http://jsperf.com/test-join-and-split&#39;&gt;recent Browserscope results show&lt;/a&gt;, all browsers have optimized &lt;code&gt;replace&lt;/code&gt; to be much faster than &lt;code&gt;split&lt;/code&gt;/&lt;code&gt;join&lt;/code&gt;. Thanks to Luigi van der Pal for pointing this out in the comments!&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When trying to do a find-and-replace in Javascript with static search and replace strings, it&amp;#8217;s always faster to use &lt;code&gt;String.split()&lt;/code&gt; and &lt;code&gt;String.join()&lt;/code&gt; than to use &lt;code&gt;String.replace()&lt;/code&gt;. Compare:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var myString = &amp;#39;......some long text.....&amp;#39;; 
mystring.replace(/,/g,&amp;quot;; &amp;quot;); // Replace the commas with semi-colon-space&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;with&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;mystring.split(&amp;quot;,&amp;quot;).join(&amp;quot;; &amp;quot;); // Replace the commas with semi-colon-space&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The latter split/join method will always be faster. Note that this is only useful for static find-and-replace. For instance, you could not do anything like the following with splits and joins:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;mystring.replace(/^[0-9]+([A-Za-z]*)/g, &amp;quot;$1&amp;quot;);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Of course, you could also use this method to strip characters out of a string:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;mystring.split(&amp;quot;,&amp;quot;).join(&amp;#39;&amp;#39;);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Good luck!&lt;/p&gt;
            </div>
        </content>
    </entry>
    
    <entry>
        <title>Javascript Pseudo-threading</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/Javascript-Pseudo-threading.html"/>
        <id>http://www.adequatelygood.com/2009/11/Javascript-Pseudo-threading</id>
        <updated>2009-11-05T00:00:00-08:00</updated>
        <published>2009-11-05T00:00:00-08:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;p&gt;&lt;strong&gt;&lt;em&gt;This post has been migrated from my old, defunct blog at bcherry.net. The links may not work, and the formatting may be wonky.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I&amp;#8217;ve been playing around with asynchronous Javascript for repeated large-set actions, in the hopes of generating some useful techniques for real applications. I&amp;#8217;ve narrowed down a successful technique that I call &amp;#8220;simplethreading&amp;#8221;. Check out a demo &lt;a href=&#39;http://bcherry.net/simplethreading_old&#39;&gt;here&lt;/a&gt; or the resulting source code &lt;a href=&#39;http://github.com/bcherry/simplethreading&#39;&gt;here&lt;/a&gt;. The demo lets you play with the size of the data set, and also the operation queue size. I found that queuing operations in batches was quite a bit faster than queuing them individually, so that each fired event will process a few data objects instead of just 1. I&amp;#8217;d guess the reason for this is that Javascript only supports timeouts at the millisecond level, when most operations are shorter than that. By grouping operations into larger chunks, we can make much better use of the time we&amp;#8217;re given.&lt;/p&gt;

&lt;p&gt;Here&amp;#8217;s the code for both the blocking (I call it &amp;#8220;singlethreaded&amp;#8221;) and non-blocking (I call it &amp;#8220;simplethreaded&amp;#8221; because it&amp;#8217;s not really multi-threaded, but it&amp;#8217;s not really single-threaded either) version. Note that &lt;code&gt; ST.s&lt;/code&gt; and &lt;code&gt; ST.n&lt;/code&gt; refer to the querystring parameters &amp;#8216;s&amp;#8217; and &amp;#8216;n&amp;#8217;.:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;ST.functions = [
	function (n, context) {
		$(context).append($(&amp;quot;&amp;lt;div&amp;gt;&amp;quot;).addClass(&amp;quot;result&amp;quot;).attr(&amp;quot;id&amp;quot;,&amp;quot;r&amp;quot;+n).text(n));
	}, function (n, context) {
		$(&amp;quot;#r&amp;quot; + n + &amp;quot;.result&amp;quot;, context).addClass(&amp;quot;dark&amp;quot;);
	}, function (n, context){
		$(&amp;quot;#r&amp;quot; + n + &amp;quot;.result&amp;quot;, context).remove();
	}
];

/** singlethreaded approach **/
ST.singleStage = 0;
ST.SingleGenerator = function(n) {
	var i = 0;
	this.next = function() {
		if (i &amp;amp;gt; n || i &amp;amp;gt; ST.singlelimit) {
			return null;
		}
		return i++;
	};
};
ST.startsingle = function() {
	var context = $(&amp;quot;#singlethreaded .output&amp;quot;);
	var gen = new ST.SingleGenerator(ST.n);
	var n;
	var workFn = ST.functions[ST.singleStage];
	ST.singleStage++;
	ST.singleStage = ST.singleStage % ST.functions.length;
	while ((n = gen.next()) !== null) {
		workFn(n,context);
	}
};

/** simplethreaded approach **/
ST.simpleStage = 0;
ST.SimpleGenerator = function(n) {
	var i = 0;
	this.next = function() {
		if (i &amp;amp;gt; n) {
			return null;
		}
		return i++;
	};
};
ST.startsimple = function() {
	var context = $(&amp;quot;#simplethreaded .output&amp;quot;);
	var gen = new ST.SimpleGenerator(ST.n);
	var n;
	var workFn = ST.functions[ST.simpleStage];
	ST.simpleStage++;
	ST.simpleStage = ST.simpleStage % ST.functions.length;
	var fn = function() {
		var i = 0;
		while (i++ &amp;amp;lt; ST.s &amp;amp;amp;&amp;amp;amp; (n = gen.next()) !== null) {
			workFn(n,context);
		}
		if (n === null) {
			clearInterval(threadID);
		}
	};
	var threadID = setInterval(fn,1);
};&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The resulting code is actually pretty straightforward. The key is to maintain the ID returned by the &lt;code&gt; setInterval()&lt;/code&gt; call so it can be killed when you&amp;#8217;re done with your work. Normally this would get stuffed into a global, but by wrapping the whole lot into a function and then sending a local function reference into &lt;code&gt; setInterval()&lt;/code&gt;, I can take advantage of Javascript&amp;#8217;s closure to keep the locals I need around for every asynchronous function call, which is really awesome.&lt;/p&gt;

&lt;p&gt;Also, using a generator is a pretty neat way to produce the data I need, and lets me work with arbitrary data pretty easily. In a real application where the data is coming from the server asynchronously, I can have the generator returning data from a queue as it comes in, while returning flags like &amp;#8220;all done&amp;#8221; so the thread knows it won&amp;#8217;t see more data or &amp;#8220;wait for it&amp;#8221; so the thread can stick around and poll for new data when it comes in.&lt;/p&gt;

&lt;p&gt;I think that if I were to bring this into a real application, I would have it decide between singlethreaded or simplethreaded dynamically, because it&amp;#8217;s obvious that singlethreaded is much better for smaller sets.&lt;/p&gt;
            </div>
        </content>
    </entry>
    
    <entry>
        <title>jQuery Micro-templates</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/jQuery-Micro-templates.html"/>
        <id>http://www.adequatelygood.com/2009/11/jQuery-Micro-templates</id>
        <updated>2009-11-05T00:00:00-08:00</updated>
        <published>2009-11-05T00:00:00-08:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;p&gt;John Resig wrote a neat micro-templating Javascript function a &lt;a href=&#39;http://ejohn.org/blog/javascript-micro-templating/&#39;&gt;while back&lt;/a&gt;. I&amp;#8217;ve been playing with this, and have discovered two things:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;These templates are totally nestable. Just make an element to be templated within a template, and call the sub-template code beneath the main call.&lt;/p&gt;
&lt;/li&gt;

&lt;li&gt;
&lt;p&gt;I found myself tending to do lines like &lt;code&gt;$(&amp;quot;...&amp;quot;).html(tmpl(&amp;quot;...&amp;quot;,{...}))&lt;/code&gt;, which seemed clumsy. It was very easy to extend jQuery to include this templating engine (just add this underneath the existing code):&lt;/p&gt;

&lt;p&gt;jQuery.fn.tmpl = function(str,data){ return this.html(tmpl(str,data)); }&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Then you can just do the following to templatize any number of elements:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$(&amp;quot;.myElems&amp;quot;).tmpl(&amp;quot;myTemplate&amp;quot;,myDataObj);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I&amp;#8217;m still playing with these templates, and working on a new project, so I hope to have more to write about it soon.&lt;/p&gt;
            </div>
        </content>
    </entry>
    
    <entry>
        <title>Managing CSS Through JavaScript</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/Managing-CSS-Through-Javascript.html"/>
        <id>http://www.adequatelygood.com/2009/11/Managing-CSS-Through-Javascript</id>
        <updated>2009-11-05T00:00:00-08:00</updated>
        <published>2009-11-05T00:00:00-08:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;p&gt;It&amp;#8217;s often very difficult to keep track of what CSS goes where. Especially when you load up on Javascript controls and files in a large application, which render markup that depends on some CSS being there. One solution is to &amp;#8220;inline&amp;#8221; the CSS in the JavaScript, by adding style to each element as it&amp;#8217;s created. This works, but it&amp;#8217;s messy. Also, browsers are heavily optimized to apply CSS, faster than any Javascript solution could be. But when you&amp;#8217;ve got a fancy script manager like LABjs, remembering to statically link all of the important CSS is a pain. Especially so if you&amp;#8217;re not sure at page load whether certain CSS will be needed. Here&amp;#8217;s a simple function to do this for you (note the XHR stuff is pretty basic, and I&amp;#8217;d recommend changing it to use whatever JS library you use in your applications):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(function() {
  var loadedFiles = {}; 
  this.$css = function(filename) { 
    if (loadedFiles[filename]) { 
      return; 
    } 
    loadedFiles[filename] = true; 
    var xhr = new XMLHttpRequest(); 
    xhr.open(&amp;quot;GET&amp;quot;, filename, true); 
    xhr.onreadystatechange = function() { 
      if (xhr.readyState === 4) { 
        var head = document.getElementsByTagName(&amp;quot;head&amp;quot;)[0]; 
        var styleTag = document.createElement(&amp;quot;style&amp;quot;); 
        var style = document.createTextNode(xhr.responseText);
        styleTag.appendChild(style); 
        head.appendChild(styleTag);
      } 
    }; 
    xhr.send(null); 
  };
})();&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now, from any Javascript, just do the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$css(&amp;quot;styles/main.css&amp;quot;); 
$css(&amp;quot;styles/controls.css&amp;quot;);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;$css()&lt;/code&gt; function keeps track of what&amp;#8217;s already been loaded, so that you&amp;#8217;ll never load the same stylesheet twice. So don&amp;#8217;t be afraid to spell out each CSS dependency your Javascript files have.&lt;/p&gt;
            </div>
        </content>
    </entry>
    
    <entry>
        <title>Building a Better Friend Selector</title>

        <link type="text/html" rel="alternate" href="http://www.adequatelygood.com/Building-a-Better-Friend-Selector.html"/>
        <id>http://www.adequatelygood.com/2009/11/Building-a-Better-Friend-Selector</id>
        <updated>2009-11-05T00:00:00-08:00</updated>
        <published>2009-11-05T00:00:00-08:00</published>
        <author>
            <name>Ben Cherry</name>
            <uri>http://www.adequatelygood.com</uri>
        </author>
        <content type="xhtml" xml:lang="en" xml:base="">
            <div xmlns="http://www.w3.org/1999/xhtml">
                &lt;p&gt;&lt;strong&gt;&lt;em&gt;This post has been migrated from my old, defunct blog at bcherry.net. The links may not work, and the formatting may be wonky.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Working in social entertainment, one of the lynchpins of the entire business is the friend selector. Without it, there is virtually no way to grow your customer base. Having a simple, effective friend selector is absolutely critical. On Facebook, they provide you with either the &lt;a href=&#39;http://wiki.developers.facebook.com/index.php/Fb:multi-friend-selector&#39; target=&#39;_blank&#39;&gt;multi-friend-selector&lt;/a&gt; or the &lt;a href=&#39;http://wiki.developers.facebook.com/index.php/Fb:multi-friend-selector_%28condensed%29&#39; target=&#39;_blank&#39;&gt;condensed multi-friend-selector&lt;/a&gt;. If you&amp;#8217;ve ever played a Facebook game like &lt;a href=&#39;http://apps.new.facebook.com/inthemafia/&#39; target=&#39;_blank&#39;&gt;Mafia Wars&lt;/a&gt; or &lt;a href=&#39;http://apps.facebook.com/onthefarm&#39; target=&#39;_blank&#39;&gt;Farmville&lt;/a&gt; or &lt;a href=&#39;http://apps.facebook.com/slidepets/&#39; target=&#39;_blank&#39;&gt;SuperPoke! Pets&lt;/a&gt;, then you&amp;#8217;re probably already familiar with both of these controls. However, the situation is much more sparse on other networks. And if you&amp;#8217;re talking about implementing a network independent game, like &lt;a href=&#39;http://www.superpokepets.com&#39; target=&#39;_blank&#39;&gt;SuperPokePets.com&lt;/a&gt;, then you&amp;#8217;ll eventually need to write your own.&lt;/p&gt;

&lt;p&gt;I&amp;#8217;ve begun a project in my free time to make a truly great friend selector control, for use in our own applications and elsewhere. You can find the result &lt;a href=&#39;http://bcherry.net/babfs&#39; target=&#39;_blank&#39;&gt;here&lt;/a&gt;, and the source code is available on &lt;a href=&#39;http://github.com/bcherry/babfs/tree/master&#39; target=&#39;_blank&#39;&gt;GitHub&lt;/a&gt;. I&amp;#8217;m constantly working on improving it. What I&amp;#8217;ve built is not useful just for friends lists, but could feasibly serve as a good control for any sort of list selection. It began as a simple exercise in &lt;a href=&#39;http://bcherry.net/archives/89&#39; target=&#39;_blank&#39;&gt;good Javascript&lt;/a&gt;, seeing how quickly I could replicate every feature of the Facebook condensed multi-friend-selector (the answer was about 2 hours). But as I worked on it more, I realized that I was capable of producing something of real value to our business. I hope to tackle advanced problems like performance with our so-called &amp;#8220;whale users&amp;#8221;, who have tens of thousands of friends. My initial attempt starts to break down over 1000 friends, and crashes the browser as I reach above 10000.&lt;/p&gt;

&lt;p&gt;You can use it by including the Javascript and CSS files (found in &lt;a href=&#39;http://github.com/bcherry/babfs/tree/master&#39; target=&#39;_blank&#39;&gt;Git&lt;/a&gt;), then making a simple call to the constructor. The data is expected to be a list of objects, each of which has the properties &amp;#8216;name&amp;#8217;, &amp;#8216;id&amp;#8217;, and &amp;#8216;tabs&amp;#8217; (optional). If you don&amp;#8217;t want the tabs, just don&amp;#8217;t pass a &amp;#8216;tabs&amp;#8217; list, and don&amp;#8217;t include it on your dataset. In the future, the object returned from the constructor will have some useful public methods.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var bfs = new BetterFriendSelector({
  action:&amp;quot;index.html&amp;quot;,
  method:&amp;quot;GET&amp;quot;,
  submit_text:&amp;quot;Send Friend Request&amp;quot;,
  data:fs_data,
  limit:10,
  elem:$(&amp;quot;#bfs&amp;quot;),
  tabs:[{key:&amp;quot;hasapp&amp;quot;,name:&amp;quot;Friends With App&amp;quot;},          {key:&amp;quot;nonapp&amp;quot;,name:&amp;quot;Friends Without App&amp;quot;}],
  extra_form_params:extra_form_params
});&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Anyways, I&amp;#8217;d like to go through the implementation of what I have so far.&lt;/p&gt;
&lt;h3&gt;Disappearing Checkboxes&lt;/h3&gt;&lt;p&gt;This is the best feature of the condensed selector on Facebook.  When a user clicks to select one of their friends, the entry moves to the &quot;selected&quot; area, but with an &#39;X&#39; instead of a checkbox.  This makes it easy to see who&#39;s been selected, even while filtering or tabbing the results.  Here&#39;s how I did that:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Friend selected event
selector.find(&amp;quot;input[type=checkbox]&amp;quot;).change(function(){
  var count = selector.find(&amp;quot;input[type=checkbox][checked=true]     length;
  if (count &amp;gt; limit) {
    $(this).attr(&amp;quot;checked&amp;quot;,false);
    return false;
  }
  $(this).parents(&amp;quot;.friend&amp;quot;).addClass(&amp;quot;hidden&amp;quot;);
  var selected_elem = $(&amp;quot;&amp;lt;div id=&amp;quot;&amp;quot;&amp;gt;&amp;quot;).addClass(&amp;quot;selected_frien    ;
  selected_elem.tmpl(BFS.templates.selected_elem,{&amp;quot;name&amp;quot;:$(this    siblings(&amp;quot;label&amp;quot;).text(), &amp;quot;id&amp;quot;:$(this).attr(&amp;quot;id&amp;quot;)});
  selector.find(&amp;quot;.selected&amp;quot;).append(selected_elem);
});
// Friend unselected event
selector.find(&amp;quot;.remove&amp;quot;).live(&amp;quot;click&amp;quot;,function(){
  selector.find(&amp;quot;.unselected #&amp;quot; + $(this).attr(&amp;quot;id&amp;quot;)).att    &amp;quot;checked&amp;quot;,false).parents(&amp;quot;.friend&amp;quot;).removeClass(&amp;quot;hidden&amp;quot;);
  $(this).parents(&amp;quot;.selected_friend&amp;quot;).remove();
});&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I think this is fairly straightforward, so I&#39;ll just list a few points to help understand it:&lt;/p&gt;&lt;ol&gt;
&lt;li&gt;The correct event to bind is &quot;change&quot;.  My first attempt had me binding to the &quot;click&quot; event on the checkbox, which was flawed.  You can modify the checkbox by clicking it, with your keyboard, or clicking on the label, not to mention other Javascript.  &quot;change&quot; catches all of these options&lt;/li&gt;
&lt;li&gt;I use the friend&#39;s id to index the items.  Checkboxes have an id of &#39;cbXXX&#39; and the corresponding &#39;selected&#39; element has an id of &#39;s_cbXXX&#39;.&lt;/li&gt;
&lt;li&gt;I&#39;m using John Resig&#39;s &lt;a href=&#39;http://bcherry.net/archives/97&#39; target=&#39;_blank&#39;&gt;micro-templates&lt;/a&gt;, so that&#39;s what the &lt;code class=&#39;js inline&#39;&gt;.tmpl()&lt;/code&gt; call is.  The template data is stored in a static collection of strings.&lt;/li&gt;
&lt;li&gt;I allow the developer to specify a selection limit (&quot;select up to X friends&quot;), and enforce that in the &#39;change&#39; event.  Returning false prevents the checkbox from becoming selected.&lt;/li&gt;
&lt;li&gt;My first attempt used &lt;code class=&#39;js inline&#39;&gt;.hide()&lt;/code&gt; and &lt;code class=&#39;js inline&#39;&gt;.show()&lt;/code&gt;, which seems to be natural.  I changed it to a class with &#39;display:none;&#39;.  This is because there are a number of reasons a friend element might be hidden, such as being filtered or toggled.  Using classes for these ensures they stay hidden when I want them to be.&lt;/li&gt;
&lt;/ol&gt;&lt;h3&gt;Typeahead Name Filter&lt;/h3&gt;&lt;p&gt;There are plenty of solutions for typeahead to be found online, but I decided to implement my own.  It turned out to be really easy, so I&#39;ll just show the code and a few points.  The key feature of my implementation is that it filters on the start of the first and last name simultaneously, so entering &#39;be&#39; will keep both &#39;Ben Franklin&#39; and &#39;David Beckham&#39;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var filter = selector.find(&amp;quot;.filter input&amp;quot;);
var reset_filter = function(){
filter.addClass(&amp;quot;empty&amp;quot;).val(filter.siblings(&amp;quot;.__empty_text&amp;quot;).tex    ));
};
// Filter changed event
var do_filter = function() {
var filter_text = filter.val();
if (filter_text == filter.siblings(&amp;quot;.__empty_text&amp;quot;).text()) {
filter_text = &amp;quot;&amp;quot;;
}
selector.find(&amp;quot;.unselected label&amp;quot;).each(function(){
with($(this)) {
if(!text().match(&amp;quot;^&amp;quot; + filter_text) &amp;amp;&amp;amp; !text().match(&amp;quot;[- \t]+&amp;quot;     filter_text)) {
parents(&amp;quot;.friend&amp;quot;).addClass(&amp;quot;filtered&amp;quot;);
} else {
parents(&amp;quot;.friend&amp;quot;).removeClass(&amp;quot;filtered&amp;quot;);
}
}
});
};
filter.keyup(do_filter);
// Filter preloaded text stuff
reset_filter();
filter.focus(function() {
if ($(this).val() == $(this).siblings(&amp;quot;.__empty_text&amp;quot;).text()) {
$(this).removeClass(&amp;quot;empty&amp;quot;).val(&amp;#39;&amp;#39;);
}
});
filter.blur(function() {
if ($(this).val() == &amp;quot;&amp;quot;) {
reset_filter();
}
});
selector.find(&amp;quot;.filter .clear_filter&amp;quot;).click(function(){
reset_filter();
do_filter();
});&lt;/code&gt;&lt;/pre&gt;
&lt;ol&gt;
&lt;li&gt;I&#39;m using a class instead of &lt;code class=&#39;js inline&#39;&gt;.hide()&lt;/code&gt; and &lt;code class=&#39;js inline&#39;&gt;.show()&lt;/code&gt; for the same reason as above&lt;/li&gt;

&lt;li&gt;The textbox is watermarked using the text in a hidden element next to the textbox&lt;/li&gt;
&lt;/ol&gt;&lt;h3&gt;What&#39;s Next?&lt;/h3&gt;&lt;p&gt;I hope someone finds this control or it&#39;s code to be useful.  I&#39;m going to keep working on it, and I hope to create something that becomes useful at Slide.  My next task is to create a mechanism for handling our &quot;whale users&quot;, probably some sort of smart pagination.  I&#39;ll also be adding some public methods like &lt;code class=&#39;js inline&#39;&gt;selectRandom()&lt;/code&gt; to make the control easily programmable.  Another hurdle will be allowing friend data to be loaded dynamically, by passing some sort of generator function to my control.  Again, I hope this was useful, and let me know if you&#39;re using or modifying this!&lt;/p&gt;
            </div>
        </content>
    </entry>
    
</feed>
