<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">

<channel>
	<title>James Padolsey</title>
	
	<link>http://james.padolsey.com</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Sun, 22 Jan 2012 17:04:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/JamesPadolsey" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="jamespadolsey" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">JamesPadolsey</feedburner:emailServiceId><feedburner:feedburnerHostname xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://feedburner.google.com</feedburner:feedburnerHostname><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://add.my.yahoo.com/rss?url=http%3A%2F%2Ffeeds.feedburner.com%2FJamesPadolsey" src="http://us.i1.yimg.com/us.yimg.com/i/us/my/addtomyyahoo4.gif">Subscribe with My Yahoo!</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://www.newsgator.com/ngs/subscriber/subext.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2FJamesPadolsey" src="http://www.newsgator.com/images/ngsub1.gif">Subscribe with NewsGator</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://feeds.my.aol.com/add.jsp?url=http%3A%2F%2Ffeeds.feedburner.com%2FJamesPadolsey" src="http://o.aolcdn.com/favorites.my.aol.com/webmaster/ffclient/webroot/locale/en-US/images/myAOLButtonSmall.gif">Subscribe with My AOL</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://www.bloglines.com/sub/http://feeds.feedburner.com/JamesPadolsey" src="http://www.bloglines.com/images/sub_modern11.gif">Subscribe with Bloglines</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://www.netvibes.com/subscribe.php?url=http%3A%2F%2Ffeeds.feedburner.com%2FJamesPadolsey" src="http://www.netvibes.com/img/add2netvibes.gif">Subscribe with Netvibes</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://fusion.google.com/add?feedurl=http%3A%2F%2Ffeeds.feedburner.com%2FJamesPadolsey" src="http://buttons.googlesyndication.com/fusion/add.gif">Subscribe with Google</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://www.pageflakes.com/subscribe.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2FJamesPadolsey" src="http://www.pageflakes.com/ImageFile.ashx?instanceId=Static_4&amp;fileName=ATP_blu_91x17.gif">Subscribe with Pageflakes</feedburner:feedFlare><item>
		<title>Intellectual property</title>
		<link>http://james.padolsey.com/general/intellectual-property/</link>
		<comments>http://james.padolsey.com/general/intellectual-property/#comments</comments>
		<pubDate>Sun, 22 Jan 2012 16:39:22 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[ACTA]]></category>
		<category><![CDATA[Copyright]]></category>
		<category><![CDATA[PIPA]]></category>
		<category><![CDATA[Society]]></category>
		<category><![CDATA[SOPA]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=2001</guid>
		<description><![CDATA[SOPA, PIPA, ACTA, TPP, DMCA, TRIPS&#8230; There is no question that the goals of the various acts, bills and agreements governing intellectual property and copyright are consistently inline with the goals of the largest entertainment companies and stakeholders. The MPAA and RIAA, respectively, the associations&#8230;]]></description>
			<content:encoded><![CDATA[<p>SOPA, PIPA, ACTA, TPP, DMCA, TRIPS&#8230; There is no question that the goals of the various acts, bills and agreements governing intellectual property and copyright are consistently inline with the goals of the largest entertainment companies and stakeholders. The MPAA and RIAA, respectively, the associations (i.e. lobbying organisations) for the movie and record industries are often found to be sponsors and co-drafters of these legal provisions.</p>

<p>It is no wonder that this is the case. With such staggering financial incentives it is understandable and reasonable, from their perspective, to shape law and public opinion to better their margins. It&#8217;s not complex. It&#8217;s all money.</p>

<p>If you&#8217;re a proponent of intellectual property and copyright in principle or even practice then this is a time at which you should be reviewing the situation and figuring out what, given the status quo, is going to prevent the approaching inhibition of our freedoms. Of course, you needn&#8217;t do this, if you, like the MPAA and RIAA, aren&#8217;t fazed by the idea of having your internet traffic monitored, held on file and released to copyright holders at their whims, and without due-process. If, on the other hand, you think this is all wrong, for whatever reason, then maybe it is time to think about what copyright really means to you&#8230;</p>

<p>It has been said that without copyright there is no incentive to innovate. This runs contrary to works created for the public domain, open source software, and works licensed under copyright-waiving terms (e.g. <a href="http://unlicense.org/">unlicense.org</a>). The claim falls apart. There is, evidently, some other motivations involved in innovating.</p>

<p>So what is intellectual property really worth? Is it worth inhibiting further innovation and creativity? Should I have to pay countless artists millions of dollars to mix a track and create something new? Is this fair? Is it okay to have no privacy or freedom of expression?</p>

<p>Is intellectual property, as a whole, really in the best interest of humanity? If it is, then it follows that it is in the best interest of humanity to create a contentious atmosphere, wherein people are pitted against each other to better not themselves necessarily, nor humanity as a whole, but simply to improve their financial standing in society. It is easy to discount one&#8217;s support of these circumstances by convincing oneself that it&#8217;s &#8220;what we need to survive&#8221;, &#8220;just how things are&#8221;, &#8220;not gonna change&#8221; etc.</p>

<p>I don&#8217;t know what the answer is, but I sure as damn prefer the idea of society where I can distribute my creations freely and have them built upon by other people to better society as a whole. Such a monumental shift in perspective is not going to happen overnight, but maybe something will materialise out of mass opposition, and no, that doesn&#8217;t mean changing a facebook profile pic, adopting a twibbon, or blocking your site for one day. Even this-here text you&#8217;re reading is probably an exercise in futility. This&#8217;ll take continued effort and awareness. Or, we can all stick our heads in the ground and entertain ourselves with the petty spoon-fed ideals we&#8217;ve been conditioned to uphold and never question anything other than what&#8217;s for dinner, or when is the next episode of Celebrity Bullshit Revisited?</p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/general/intellectual-property/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Using proxies to mimic existential-operator behaviour</title>
		<link>http://james.padolsey.com/javascript/using-proxies-to-mimic-existential-operator-behaviour/</link>
		<comments>http://james.padolsey.com/javascript/using-proxies-to-mimic-existential-operator-behaviour/#comments</comments>
		<pubDate>Sun, 01 Jan 2012 20:00:56 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=1990</guid>
		<description><![CDATA[The <a href="http://wiki.ecmascript.org/doku.php?id=harmony:proxies">Proxies API</a> is a low-level catch-all thing that you can wrap around your objects to implement almost anything you want within the syntactic limitations of JavaScript. <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Proxy">Firefox supports it</a>, and so does the latest version of V8 <a href="http://erik.eae.net/archives/2011/12/31/00.00.01/">apparently</a>.

The existential operator (the accessor kind), if&#8230;]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://wiki.ecmascript.org/doku.php?id=harmony:proxies">Proxies API</a> is a low-level catch-all thing that you can wrap around your objects to implement almost anything you want within the syntactic limitations of JavaScript. <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Proxy">Firefox supports it</a>, and so does the latest version of V8 <a href="http://erik.eae.net/archives/2011/12/31/00.00.01/">apparently</a>.</p>

<p>The existential operator (the accessor kind), if it existed in JavaScript, would allow us attempted access of nested properties in JavaScript without ever getting a TypeError. Here&#8217;s what usually happens:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> obj <span class="sy0">=</span> <span class="br0">&#123;</span> foo<span class="sy0">:</span> <span class="nu0">123</span> <span class="br0">&#125;</span><span class="sy0">;</span>
&nbsp;
obj.<span class="me1">foo</span>.<span class="me1">bar</span>.<span class="me1">bob</span><span class="sy0">;</span> <span class="co1">// Throws TypeError (obj.foo.bar is undefined)</span></pre></div></div>




<p>CoffeeScript implements an existential operator that allows you to attempt access at a property without throwing errors. It will fail quietly by returning a harmless <code>undefined</code> value. In CoffeeScript, it looks like this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">obj<span class="sy0">?</span>.<span class="me1">foo</span><span class="sy0">?</span>.<span class="me1">bar</span><span class="sy0">?</span>.<span class="me1">bob</span> <span class="co1">// returns undefined</span></pre></div></div>




<p>We can&#8217;t emulate this entirely but we can make a decent alternative using the Proxies API. In this example we&#8217;re using the dollar sign to indicate a existential-property-accessor-operator:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">obj <span class="sy0">=</span> <span class="br0">&#123;</span><span class="br0">&#125;</span><span class="sy0">;</span>
obj.<span class="me1">foo</span>$bar$bob<span class="sy0">;</span> <span class="co1">// =&gt; undefined</span>
obj <span class="sy0">=</span> <span class="br0">&#123;</span> foo<span class="sy0">:</span> <span class="br0">&#123;</span> bar<span class="sy0">:</span> <span class="br0">&#123;</span> bob<span class="sy0">:</span> <span class="nu0">321</span> <span class="br0">&#125;</span> <span class="br0">&#125;</span> <span class="br0">&#125;</span><span class="sy0">;</span>
obj <span class="sy0">=</span> existentially<span class="br0">&#40;</span>obj<span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// wrap it in magic</span>
obj.<span class="me1">foo</span>$bar$bob<span class="sy0">;</span> <span class="co1">// =&gt; 321</span></pre></div></div>




<p>No, it&#8217;s not as cool and no, you probably shouldn&#8217;t use it in production. Yes, it&#8217;ll fail if <code>obj</code> doesn&#8217;t exist. Anyway, I thought it was pretty neat. Here&#8217;s how it&#8217;s done:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">function</span> existentially<span class="br0">&#40;</span>obj<span class="br0">&#41;</span> <span class="br0">&#123;</span>
&nbsp;
  <span class="kw1">if</span> <span class="br0">&#40;</span>obj <span class="sy0">==</span> <span class="kw2">null</span><span class="br0">&#41;</span> <span class="kw1">return</span> obj<span class="sy0">;</span>
&nbsp;
  <span class="kw2">var</span> proxy <span class="sy0">=</span> handlerMaker<span class="br0">&#40;</span>obj<span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
  proxy.<span class="me1">get</span> <span class="sy0">=</span> <span class="kw2">function</span><span class="br0">&#40;</span>_<span class="sy0">,</span> <span class="kw3">name</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="kw3">name</span> <span class="sy0">=</span> <span class="kw3">name</span>.<span class="me1">split</span><span class="br0">&#40;</span><span class="st0">'$'</span><span class="br0">&#41;</span><span class="sy0">;</span>
    <span class="kw2">var</span> found <span class="sy0">=</span> obj<span class="sy0">;</span>
    <span class="kw1">while</span> <span class="br0">&#40;</span>
      <span class="kw3">name</span><span class="br0">&#91;</span><span class="nu0">0</span><span class="br0">&#93;</span> <span class="sy0">&amp;&amp;</span>
      <span class="kw2">null</span> <span class="sy0">!=</span> <span class="br0">&#40;</span>found <span class="sy0">=</span> found<span class="br0">&#91;</span><span class="kw3">name</span>.<span class="me1">shift</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#93;</span><span class="br0">&#41;</span>
    <span class="br0">&#41;</span><span class="sy0">;</span>
    <span class="kw1">return</span> found<span class="sy0">;</span>
  <span class="br0">&#125;</span><span class="sy0">;</span>
&nbsp;
  proxy.<span class="me1">set</span> <span class="sy0">=</span> <span class="kw2">function</span><span class="br0">&#40;</span>_<span class="sy0">,</span> <span class="kw3">name</span><span class="sy0">,</span> val<span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="kw3">name</span> <span class="sy0">=</span> <span class="kw3">name</span>.<span class="me1">split</span><span class="br0">&#40;</span><span class="st0">'$'</span><span class="br0">&#41;</span><span class="sy0">;</span>
    <span class="kw2">var</span> found <span class="sy0">=</span> obj<span class="sy0">;</span>
    <span class="kw1">while</span> <span class="br0">&#40;</span>
      <span class="kw3">name</span><span class="br0">&#91;</span><span class="nu0">1</span><span class="br0">&#93;</span> <span class="sy0">&amp;&amp;</span>
      <span class="kw2">null</span> <span class="sy0">!=</span> <span class="br0">&#40;</span>found <span class="sy0">=</span> found<span class="br0">&#91;</span><span class="kw3">name</span>.<span class="me1">shift</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#93;</span><span class="br0">&#41;</span>
    <span class="br0">&#41;</span><span class="sy0">;</span>
    <span class="kw1">if</span> <span class="br0">&#40;</span>found<span class="br0">&#41;</span> <span class="br0">&#123;</span>
      found<span class="br0">&#91;</span><span class="kw3">name</span><span class="br0">&#93;</span> <span class="sy0">=</span> val<span class="sy0">;</span>
    <span class="br0">&#125;</span>
    <span class="kw1">return</span> <span class="kw2">true</span><span class="sy0">;</span>
  <span class="br0">&#125;</span><span class="sy0">;</span>
&nbsp;
  <span class="kw1">return</span> Proxy.<span class="me1">create</span><span class="br0">&#40;</span>proxy<span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
<span class="br0">&#125;</span>
&nbsp;
<span class="co1">// fyi</span>
<span class="co1">//   a == null</span>
<span class="co1">// is the same as</span>
<span class="co1">//   a === undefined || a === null</span></pre></div></div>




<p>The referenced <code>handlerMaker</code> simply defines all fundamental traps. You can grab it from <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Proxy#No-op_forwarding_proxy">the MDN Proxy API page</a>.</p>

<p>You&#8217;ll notice that we&#8217;re also defining a <code>get</code> trap, which enables stuff like:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> foo <span class="sy0">=</span> existentially<span class="br0">&#40;</span>document.<span class="me1">getElementById</span><span class="br0">&#40;</span><span class="st0">'foo'</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">;</span>
<span class="kw1">if</span> <span class="br0">&#40;</span>foo<span class="br0">&#41;</span> <span class="br0">&#123;</span> <span class="co1">// yes, we still need the initial null check</span>
  foo.<span class="me1">firstChild</span>$style$display <span class="sy0">=</span> <span class="st0">'none'</span><span class="sy0">;</span>
    <span class="co1">// won't throw an error, even if `firstChild` doesn't exist</span>
<span class="br0">&#125;</span></pre></div></div>




<p>Okay, granted, the dollar sign doesn&#8217;t suit well and we&#8217;re just pandering to what&#8217;s allowed in JS, but it&#8217;s still a good illustration of what&#8217;s possible with the Proxies API. You might want to use another fake operator &#8212; possibly something that isn&#8217;t likely to be found as part of a property name itself&#8230; something like <code>_$_</code> would be okay, except that it&#8217;s ugly and, just like <code>$</code>, carries no semantic value whatsoever.</p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/using-proxies-to-mimic-existential-operator-behaviour/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Making APIs is hard</title>
		<link>http://james.padolsey.com/general/making-apis-is-hard/</link>
		<comments>http://james.padolsey.com/general/making-apis-is-hard/#comments</comments>
		<pubDate>Wed, 21 Dec 2011 23:41:08 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=1981</guid>
		<description><![CDATA[We know naming is hard, and it probably should be, but never has something so seemingly minor made me toil so frequently. It&#8217;s such an interesting topic that I just had to write some stuff down.

When I say naming, I mean something as simple&#8230;]]></description>
			<content:encoded><![CDATA[<p>We know naming is hard, and it probably should be, but never has something so seemingly minor made me toil so frequently. It&#8217;s such an interesting topic that I just had to write some stuff down.</p>

<p>When I say naming, I mean something as simple as naming a variable, or more often: an API endpoint &#8212; the thing that the end-user-programmer-guy is going to use. It&#8217;s hard.</p>

<p>I think code should be readable, but I don&#8217;t think that means it should be readable to everyone, even non-programmers. So, if I show a non-programmer Java and then Perl and they say the former is much easier to understand, I don&#8217;t think that counts as a mark against Perl.</p>

<p>I also don&#8217;t think we should needlessly simplify things to cater to the amateur. In fact, I love the idea of writing code that I expect to only be read by programmers seasoned in that very language. When I write JS, I like to presume that the maintainer knows about hoisting, closures, prototypal inheritance, and truthy/falsyness. Pandering about trying to make your code avoid these inherent qualities is a waste of time.</p>

<p>Even with that opinion I still hugely value expression through language. I love method chains that flow like spoken sentences:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">render<span class="br0">&#40;</span><span class="st0">'this'</span><span class="br0">&#41;</span>.<span class="me1">thenRun</span><span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span><span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>But at the same time I don&#8217;t like putting too much effort into making an API bend to this style.</p>

<p>It&#8217;s really tricky to pick a principle and stick to it. Some of us prefer hungarian notation. I say I hate it but I still use it quite often.</p>

<p>I think programming should have a barrier to understanding, and I think APIs should too. This sounds weird, even to me, but I think it makes sense nonetheless. Fundamentally, every API disguises complexity and, ideally, a very precise piece of functionality. Making the API dead-simple makes no sense if what it is disguising is actually quite complex and involved. An API or language should be crafted in such a way that by using it you&#8217;re not only learning how to use it but you&#8217;re learning how it works.</p>

<p>jQuery is a good example, because it neatly expresses the DOM. It doesn&#8217;t hide the DOM, believe it or not. You still need to append and prepend, bind event listeners and apply CSS classes. The great thing about jQuery is that it reduces the DOM down to it&#8217;s very essence, so that when you have gained an understanding of jQuery you have also gained an understanding of the core idea behind the DOM.</p>

<p>So, no, I guess APIs and languages shouldn&#8217;t be as simple as possible just for the sake of it. They should represent the functionality they seek to disguise.</p>

<p>I&#8217;m not happy with this conclusion though. I am sitting here thinking about that end-user-programmer-guy. I guess this holy API should seek to provide exactly what this guy wants. The trick is knowing what he wants. It would be lovely if we could create computers that just had one input device &#8212; a big green button, which, when pressed, made the computer do exactly the thing you want. We don&#8217;t have this (yet!), and our APIs can&#8217;t have this either. But maybe there&#8217;s a healthy compromise where we model the API based on how it&#8217;s going to be used, not how we want it to be used. We are meaningless in that our petty preferences make no difference. Our APIs must be predictive; modelled entirely on the potential use-cases presented by end-user-programmer-guy, not modelled on our preferences alone.</p>

<p>I still haven&#8217;t resolved this in my mind. It&#8217;s still hard to decide what to call some method that will only be used once in a blue moon. It&#8217;s not as easy as describing the method entirely in its name:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> namespaceContainingMethods <span class="sy0">=</span> <span class="br0">&#123;</span>
  methodThatTakesArgumentsAndJoinsWithSpecifiedString<span class="sy0">:</span> <span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="co1">//...</span>
  <span class="br0">&#125;</span>
<span class="br0">&#125;</span></pre></div></div>




<p>I&#8217;ve had to use stuff like this before and it sucks. It sucks so much. It was made for idiots. That&#8217;s another thing: APIs should not offend. Don&#8217;t patronise me with your &#8220;ur so stupid&#8221; naming. Make me feel good about using your API.</p>

<p>It&#8217;s not easy. It&#8217;s just not.</p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/general/making-apis-is-hard/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Beware of passion voids</title>
		<link>http://james.padolsey.com/general/beware-of-passion-voids/</link>
		<comments>http://james.padolsey.com/general/beware-of-passion-voids/#comments</comments>
		<pubDate>Tue, 22 Nov 2011 14:59:35 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=1973</guid>
		<description><![CDATA[This is a warning to young budding web developers going into the field of web development. The business of web development is never really talked about. We talk about the technology a lot, but the business itself is left alone for fear of&#8230; what? I&#8230;]]></description>
			<content:encoded><![CDATA[<p>This is a warning to young budding web developers going into the field of web development. The business of web development is never really talked about. We talk about the technology a lot, but the business itself is left alone for fear of&#8230; what? I don&#8217;t know really.</p>

<p>The first thing that took me by surprise upon my entry, three years ago, into the &#8220;Digital Agency&#8221; world was the fact that some people that work with the web don&#8217;t use it very much. There are quantities of web developers that don&#8217;t have websites, don&#8217;t maintain personal projects, and don&#8217;t partake in the vibrant community. </p>

<p>This was a massive shock to my system because I, being naive and passionate, thought that everyone else in this industry would have at least a spark of a passion for this stuff or at least an interest which materialises in more than doing it, begrudgingly, from 9 to 5.</p>

<p>This isn&#8217;t a universal truth, of course, but what I&#8217;ve discovered is that those lacking in passion tend to gravitate towards either agency or <em>non-web</em> corporate roles. These individuals tend to know their niche&#8217;s technologies but only as well as they absolutely have to. They&#8217;re fine copying and pasting as long as it makes the boss or client happy. There are no gurus in the passion voids.</p>

<p>The entire process is ugly to begin with. Getting hired. If you can, you must make every effort to avoid dealing with recruitment agencies. I won&#8217;t cast any judgement on the validity of the recruitment industry as a whole, but I will say this: their motive is to fill the role. They rarely give a damn about passion, fulfilment or your desire to have a positive effect on the world while leading a good life. They couldn&#8217;t give a shit. They want the commission. They want to sell you to the client. You&#8217;re their whore.</p>

<p>If you want to float between vacuous advertising projects, where the sole objective is to maximise market share and profit for the end-client regardless of ethical inclinations, then you&#8217;ll probably be fine. You should stop reading and ring a recruiter now! If, on the other hand, you care, then you will want to take the time to find a better role, where the employer&#8217;s passions are in-line with yours.</p>

<p>I am not trying to generalise here. There are some, no doubt, awesome digital agencies that care passionately about the technologies they work with. This is why this must all be judged on a case-by-case basis.</p>

<p>Just beware of the passion voids. If you&#8217;ve an ounce of interest in what you do, you&#8217;ll want to steer well clear of them, lest your soul be forsaken to the clutches of vapid monotony.</p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/general/beware-of-passion-voids/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>Rampant Callback Syndrome</title>
		<link>http://james.padolsey.com/javascript/rampant-callback-syndrome/</link>
		<comments>http://james.padolsey.com/javascript/rampant-callback-syndrome/#comments</comments>
		<pubDate>Sat, 19 Nov 2011 23:03:54 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[node]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=1951</guid>
		<description><![CDATA[One of the common critiques of <a href="http://nodejs.org/">node.js</a> is that its (events-based) asynchronous model requires a lot of nested callback functions and generally uglier flow control than a synchronous model would allow. An example:


<pre class="javascript" style="font-family:monospace;">fs.<span class="me1">readFile</span><span class="br0">&#40;</span>path.<span class="me1">join</span><span class="br0">&#40;</span>base<span class="sy0">,</span> <span class="st0">'config.json'</span><span class="br0">&#41;</span><span class="sy0">,</span> <span class="kw2">function</span><span class="br0">&#40;</span>err<span class="sy0">,</span> data<span class="br0">&#41;</span><span class="br0">&#123;</span>
    <span class="kw1">if</span> <span class="br0">&#40;</span>data<span class="br0">&#41;</span> <span class="br0">&#123;</span>
        data <span class="sy0">=</span> JSON.<span class="me1">parse</span><span class="br0">&#40;</span>data<span class="br0">&#41;</span><span class="sy0">;</span>
        data.<span class="me1">forEach</span><span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span>path<span class="br0">&#41;</span><span class="br0">&#123;</span>
            fs.<span class="me1">readFile</span><span class="br0">&#40;</span>path<span class="sy0">,</span> <span class="kw2">function</span><span class="br0">&#40;</span>err<span class="sy0">,</span> data<span class="br0">&#41;</span><span class="br0">&#123;</span>
                <span class="kw1">if</span> <span class="br0">&#40;</span>err<span class="br0">&#41;</span> <span class="br0">&#123;</span>
                    log<span class="br0">&#40;</span>err<span class="br0">&#41;</span>
                <span class="br0">&#125;</span> <span class="kw1">else</span> <span class="br0">&#123;</span>
                    data <span class="sy0">=</span> JSON.<span class="me1">parse</span><span class="br0">&#40;</span>data<span class="br0">&#41;</span><span class="sy0">;</span>
                    <span class="kw1">if</span> <span class="br0">&#40;</span>data.<span class="me1">url</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
                        http.<span class="me1">get</span><span class="br0">&#40;</span>url.<span class="me1">parse</span><span class="br0">&#40;</span>data.<span class="me1">url</span><span class="br0">&#41;</span><span class="sy0">,</span> <span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span>
                            <span class="co1">// ...absurdum ad infinitum</span>
                        <span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span>
                    <span class="br0">&#125;</span>
                <span class="br0">&#125;</span>
            <span class="br0">&#125;</span><span class="br0">&#41;</span>
        <span class="br0">&#125;</span><span class="br0">&#41;</span>
    <span class="br0">&#125;</span>
<span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre>




This isn't a trait unique to node.js though. Much&#8230;]]></description>
			<content:encoded><![CDATA[<p>One of the common critiques of <a href="http://nodejs.org/">node.js</a> is that its (events-based) asynchronous model requires a lot of nested callback functions and generally uglier flow control than a synchronous model would allow. An example:</pre>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">fs.<span class="me1">readFile</span><span class="br0">&#40;</span>path.<span class="me1">join</span><span class="br0">&#40;</span>base<span class="sy0">,</span> <span class="st0">'config.json'</span><span class="br0">&#41;</span><span class="sy0">,</span> <span class="kw2">function</span><span class="br0">&#40;</span>err<span class="sy0">,</span> data<span class="br0">&#41;</span><span class="br0">&#123;</span>
    <span class="kw1">if</span> <span class="br0">&#40;</span>data<span class="br0">&#41;</span> <span class="br0">&#123;</span>
        data <span class="sy0">=</span> JSON.<span class="me1">parse</span><span class="br0">&#40;</span>data<span class="br0">&#41;</span><span class="sy0">;</span>
        data.<span class="me1">forEach</span><span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span>path<span class="br0">&#41;</span><span class="br0">&#123;</span>
            fs.<span class="me1">readFile</span><span class="br0">&#40;</span>path<span class="sy0">,</span> <span class="kw2">function</span><span class="br0">&#40;</span>err<span class="sy0">,</span> data<span class="br0">&#41;</span><span class="br0">&#123;</span>
                <span class="kw1">if</span> <span class="br0">&#40;</span>err<span class="br0">&#41;</span> <span class="br0">&#123;</span>
                    log<span class="br0">&#40;</span>err<span class="br0">&#41;</span>
                <span class="br0">&#125;</span> <span class="kw1">else</span> <span class="br0">&#123;</span>
                    data <span class="sy0">=</span> JSON.<span class="me1">parse</span><span class="br0">&#40;</span>data<span class="br0">&#41;</span><span class="sy0">;</span>
                    <span class="kw1">if</span> <span class="br0">&#40;</span>data.<span class="me1">url</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
                        http.<span class="me1">get</span><span class="br0">&#40;</span>url.<span class="me1">parse</span><span class="br0">&#40;</span>data.<span class="me1">url</span><span class="br0">&#41;</span><span class="sy0">,</span> <span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span>
                            <span class="co1">// ...absurdum ad infinitum</span>
                        <span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span>
                    <span class="br0">&#125;</span>
                <span class="br0">&#125;</span>
            <span class="br0">&#125;</span><span class="br0">&#41;</span>
        <span class="br0">&#125;</span><span class="br0">&#41;</span>
    <span class="br0">&#125;</span>
<span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>This isn't a trait unique to node.js though. Much of JavaScript, since it is a language heavily bound to the client-side and therefore DOM and user-initiated events, is very liable to "Rampant Callback Syndrome".</p>

<h3>Rampant Callback Syndrome</h3>

<p>Rampant Callback Syndrome is a serious issue in the JavaScript arena and if left unchecked will continue to spread like a disease, poisoning our dreams with its ominous creep.</p>

<p>In all seriousness, it is rather annoying, and is definitely something that can be avoided with nothing more than a light dose of decent application design and thought.</p>

<p>One pattern that I've become fairly attached to is the simple premise of providing an API to begin with, and letting it appear to be a (<em>mostly</em>) synchronous interface, but behind the scenes throw around events to make it work properly.</p>

<p>Let's say, for example, that we want to expose a Model API, for interfacing with our database.</p>

<p>When the model is instantiated we go about opening the connection to the database:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">function</span> Model<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
&nbsp;
    <span class="co1">// (not shown) ... configuration stuff ...</span>
&nbsp;
    <span class="kw1">this</span>.<span class="me1">server</span> <span class="sy0">=</span> <span class="kw2">new</span> mongodb.<span class="me1">Server</span><span class="br0">&#40;</span>
        <span class="kw1">this</span>.<span class="me1">config</span>.<span class="me1">address</span><span class="sy0">,</span>
        <span class="kw1">this</span>.<span class="me1">config</span>.<span class="me1">port</span><span class="sy0">,</span>
        <span class="br0">&#123;</span><span class="br0">&#125;</span>
    <span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
    <span class="co1">// (not shown) ... error checking ...</span>
&nbsp;
    <span class="kw1">this</span>.<span class="me1">db</span> <span class="sy0">=</span> <span class="kw2">new</span> mongodb.<span class="me1">Db</span><span class="br0">&#40;</span><span class="kw1">this</span>.<span class="me1">config</span>.<span class="me1">dbName</span><span class="sy0">,</span> <span class="kw1">this</span>.<span class="me1">server</span><span class="sy0">,</span> <span class="br0">&#123;</span><span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
    <span class="kw1">this</span>.<span class="me1">db</span>.<span class="kw3">open</span><span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span>error<span class="sy0">,</span> client<span class="br0">&#41;</span><span class="br0">&#123;</span>
&nbsp;
        <span class="kw1">if</span> <span class="br0">&#40;</span>error<span class="br0">&#41;</span> <span class="br0">&#123;</span>
            <span class="kw1">this</span>.<span class="me1">error</span><span class="br0">&#40;</span><span class="st0">'DB: '</span> <span class="sy0">+</span> <span class="kw1">this</span>.<span class="me1">config</span>.<span class="me1">db</span> <span class="sy0">+</span> <span class="st0">' error: '</span><span class="sy0">,</span> error<span class="br0">&#41;</span><span class="sy0">;</span>
            <span class="kw1">return</span><span class="sy0">;</span>
        <span class="br0">&#125;</span>
&nbsp;
        <span class="kw1">this</span>.<span class="me1">collection</span> <span class="sy0">=</span> <span class="kw2">new</span> mongodb.<span class="me1">Collection</span><span class="br0">&#40;</span>client<span class="sy0">,</span> <span class="kw1">this</span>.<span class="me1">config</span>.<span class="me1">dbCollection</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
        <span class="kw1">this</span>._isOpen <span class="sy0">=</span> <span class="kw2">true</span><span class="sy0">;</span>
        <span class="kw1">this</span>.<span class="me1">emit</span><span class="br0">&#40;</span><span class="st0">'open'</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
    <span class="br0">&#125;</span>.<span class="me1">bind</span><span class="br0">&#40;</span><span class="kw1">this</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
    <span class="co1">// (not shown) ... other stuff ...</span>
&nbsp;
<span class="br0">&#125;</span></pre></div></div>




<p>The problem is that our <code>new Model</code> call will return before the connection to the database is open. Fortunately, as you can see above, in the callback to the <code>db.open</code> method we are setting a flag, <code>_isOpen</code>, to <code>true</code>, and we're emitting the <code>open</code> event. This Model happens to implement the <code>events.EventEmitter</code> interface which means we can fire and trigger on our object.</p>

<p>So, let's look at our calling-code:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> myModel <span class="sy0">=</span> <span class="kw2">new</span> Model<span class="br0">&#40;</span><span class="br0">&#123;</span> <span class="co2">/* config */</span> <span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
myModel.<span class="me1">find</span><span class="br0">&#40;</span><span class="br0">&#123;</span> username<span class="sy0">:</span> <span class="st0">'James'</span> <span class="br0">&#125;</span><span class="sy0">,</span> <span class="kw2">function</span><span class="br0">&#40;</span>data<span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="co1">// I can live with a single nested function. </span>
<span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>This is great! The code above shows none of the callback nonsense we saw earlier<sup>[1]</sup> -- we've abstracted it away. One <em>big</em> problem though is the <code>find</code> method is going to be called before our database connection is open. But, thanks to the events interface, we can hold off until our <code>open</code> event fires:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">Model.<span class="me1">prototype</span>.<span class="me1">find</span> <span class="sy0">=</span> <span class="kw2">function</span><span class="br0">&#40;</span>selector<span class="sy0">,</span> cb<span class="br0">&#41;</span><span class="br0">&#123;</span>
&nbsp;
    <span class="kw1">if</span> <span class="br0">&#40;</span><span class="kw1">this</span>._isOpen<span class="br0">&#41;</span> <span class="br0">&#123;</span>
&nbsp;
        <span class="co1">// If we're already open, let's go:</span>
&nbsp;
        <span class="kw1">this</span>.<span class="me1">collection</span>.<span class="me1">find</span><span class="br0">&#40;</span>selector<span class="br0">&#41;</span>.<span class="me1">toArray</span><span class="br0">&#40;</span>cb<span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
    <span class="br0">&#125;</span> <span class="kw1">else</span> <span class="br0">&#123;</span>
&nbsp;
        <span class="co1">// Otherwise, wait:</span>
&nbsp;
        <span class="kw2">var</span> args <span class="sy0">=</span> arguments<span class="sy0">;</span>
        <span class="kw1">this</span>.<span class="me1">on</span><span class="br0">&#40;</span><span class="st0">'open'</span><span class="sy0">,</span> <span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span>
            <span class="kw1">this</span>.<span class="me1">find</span>.<span class="me1">apply</span><span class="br0">&#40;</span><span class="kw1">this</span><span class="sy0">,</span> args<span class="br0">&#41;</span><span class="sy0">;</span>
            <span class="co1">// (added stability would be remove the event listener here)</span>
        <span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
    <span class="br0">&#125;</span>
&nbsp;
<span class="br0">&#125;</span><span class="sy0">;</span></pre></div></div>




<p>In the <code>else</code> block we register a new event listener, to listen for the <code>open</code> event, and when it fires, we're simply going to call the very same method (<code>find</code>) with the very same arguments. Obviously this is only possible if we're using callbacks (one of the arguments to <code>find()</code>). Obliterating all callbacks is not we're looking for; we're simply looking to minimise.</p>

<h3>Abstraction is the key</h3>

<p>We can cure 90% of Rampant Callback Syndrome by simply abstracting our code.</p>

<p>The great thing about the solution shown in this post is that you're able to provide the promised API immediately following instantiation -- you're not forcing the higher level of abstraction to fuss with what is a lower concern.</p>

<p><sup>[1]</sup><small>: Yes, I know they're doing completely different things. My point still stands.</small></p>
]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/rampant-callback-syndrome/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>JSAPI.info</title>
		<link>http://james.padolsey.com/javascript/jsapi-info/</link>
		<comments>http://james.padolsey.com/javascript/jsapi-info/#comments</comments>
		<pubDate>Tue, 01 Nov 2011 15:30:41 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[Cool Stuff]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Dojo]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Mootools]]></category>
		<category><![CDATA[Underscore]]></category>
		<category><![CDATA[YUI]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=1944</guid>
		<description><![CDATA[A while ago I made the &#8220;<a href="http://james.padolsey.com/jquery/">jQuery source viewer</a>&#8220;. It allows you to explore jQuery&#8217;s source and has a hackable URL pattern so you can get at what you need (e.g. <a href="james.padolsey.com/jquery/append">/jquery/append</a>).

I had been thinking about making a version 2 for sometime, and about&#8230;]]></description>
			<content:encoded><![CDATA[<p>A while ago I made the &#8220;<a href="http://james.padolsey.com/jquery/">jQuery source viewer</a>&#8220;. It allows you to explore jQuery&#8217;s source and has a hackable URL pattern so you can get at what you need (e.g. <a href="james.padolsey.com/jquery/append">/jquery/append</a>).</p>

<p>I had been thinking about making a version 2 for sometime, and about two weeks ago I started work on <a href="http://jsapi.info">JSAPI.info</a>. It&#8217;s built using node.js, and is more flexible than version 1 in that it enables you to explore the source of whatever library you want (as long as it&#8217;s <a href="https://github.com/padolsey/jsapi-info/blob/master/app/libs.json">specified</a>), not just jQuery.</p>

<h3>Demos</h3>

<ul>
  <li>jQuery (e.g. <a href="http://jsapi.info/jquery/css">/jquery/css</a>)</li>
  <li>Mootools (e.g. <a href="http://jsapi.info/mootools/flatten">/mootools/Array.prototype.flatten</a>)</li>

  <li>Dojo (e.g. <a href="http://jsapi.info/dojo/1/Color">/dojo/1/Color</a>)</li>
  <li>Underscore (e.g. <a href="http://jsapi.info/_/every">/_/every</a>)</li>
  <li>YUI (e.g. <a href="http://jsapi.info/yui/3/namespace">/yui/3/namespace</a>)</li>
</ul>

<p>As I said, the URLs are &#8220;hackable&#8221;, so you can specify the method and version you want. Each page has a link to the documentation for that method (if found), and a list of related links (methods under the same namespace) on the left hand side.</p>

<h3>How does it work?</h3>

<blockquote><p>It works by loading the library you specify into an instance of <a href="https://github.com/tmpvar/jsdom">jsdom</a>, and then evaluating the method you specify (in fully qualified form, e.g. jQuery.fn.css) within that instance. It then matches the <code>toString()</code> representation of that function (thanks V8!) against the source of the library, thus determining its location. It&#8217;s all operating under node.js, running via a beautiful configuration of nginx (primed to microcache!) on a linode box somewhere in London.</p></blockquote>

<h3>Yet to add&#8230;</h3>

<p>I&#8217;ve yet to add the following features, and plan on doing so in the near future. The <a href="https://github.com/padolsey/jsapi-info">source is up on Github</a> if anyone wants to help!</p>

<ul>
  <li><del datetime="2011-11-02T18:38:45+00:00">Links within source code leading to other parts of the API.</del> (<strong><a href="https://github.com/padolsey/jsapi-info/commit/50d4e50f8e86d594e5a7150696f1a6fa19cc3f61">DONE</a></strong>) The <a href="http://james.padolsey.com/jquery/">jQuery source viewer</a> already does this.</li>
  <li>Thinking about adding beautify-js &#8212; this&#8217;ll change the format of the code though, so it won&#8217;t be consistent with the source code, and thus the line numbers won&#8217;t match up.</li>
  <li>I was experimenting with full documentation support so the documentation for a specific method could appear alongside the source code, but I&#8217;m not sure if it would be a sensible addition, especially considering that it can just link to the documentation instead.</li>
  <li>Any other features you can think of?</li>
</ul>

<h3>Why?</h3>

<p>Have you ever tried to find the source of the <code>jQuery.fn.height</code> method? <a href="http://code.jquery.com/jquery-1.6.4.js">Try it now</a>. It&#8217;s tricky.</p>

<p>If you&#8217;re anything like me, you&#8217;ll hit CTRL-F and type the most popular function/method declaration patterns, including <code>function height...</code>, <code>height = funct...</code>, <code>height: function...</code>. None of these work for <code>jQuery.fn.height</code> because it&#8217;s defined differently. It&#8217;s not easy to find.</p>

<p>I very often need to find the source behind a method I&#8217;m using and there aren&#8217;t many easy ways to do so, and that&#8217;s why I originally created the jQuery source viewer. <a href="http://jsapi.info/">JSAPI.info</a> is a move in the right direction since it supports multiple libraries and, finally, has it&#8217;s own domain!</p>

<p>Please test it out and <a href="https://github.com/padolsey/jsapi-info/issues">let me know</a> if you catch any bugs.</p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/jsapi-info/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Terse JavaScript 101 – part 2</title>
		<link>http://james.padolsey.com/javascript/terse-javascript-101-part-2/</link>
		<comments>http://james.padolsey.com/javascript/terse-javascript-101-part-2/#comments</comments>
		<pubDate>Sat, 29 Oct 2011 11:05:57 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=1937</guid>
		<description><![CDATA[<a href="http://james.padolsey.com/javascript/terse-javascript-101-part-1/">Part one</a>, posted last week, explored a few different ways of de-cluttering your JavaScript, and, in the process, making it more readable.

Some developers don&#8217;t like the idea of using a language&#8217;s more idiosyncratic features because it does, potentially, make your code less readable in&#8230;]]></description>
			<content:encoded><![CDATA[<p><a href="http://james.padolsey.com/javascript/terse-javascript-101-part-1/">Part one</a>, posted last week, explored a few different ways of de-cluttering your JavaScript, and, in the process, making it more readable.</p>

<p>Some developers don&#8217;t like the idea of using a language&#8217;s more idiosyncratic features because it does, potentially, make your code less readable in the eyes of those who haven&#8217;t learned the language properly. I think it&#8217;s still up for debate. While you&#8217;re pondering that, part II awaits&#8230;</p>

<p>If you haven&#8217;t checked out the <a href="http://james.padolsey.com/javascript/truthy-falsey/">&#8220;Truthy &#038; Falsey&#8221; introduction</a> then please do so before continuing.</p>

<h3>Looping</h3>

<p>It&#8217;s something we barely think about but JavaScript&#8217;s expressive diversity allows us to invent new patterns for looping. First, there&#8217;s the standard:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw2">var</span> i <span class="sy0">=</span> <span class="nu0">0</span><span class="sy0">;</span> i <span class="sy0">&lt;</span> array.<span class="me1">length</span><span class="sy0">;</span> i<span class="sy0">++</span><span class="br0">&#41;</span> <span class="br0">&#123;</span><span class="br0">&#125;</span></pre></div></div>




<p>This is conventional and will be known to developers coming from any language. There&#8217;s nothing inherently wrong with it. That said, for me, it&#8217;s not ideal.</p>

<p>The first improvement I usually make is to cache the <code>length</code> property of the array:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw2">var</span> i <span class="sy0">=</span> <span class="nu0">0</span><span class="sy0">,</span> l <span class="sy0">=</span> array.<span class="me1">length</span><span class="sy0">;</span> i <span class="sy0">&lt;</span> l<span class="sy0">;</span> i<span class="sy0">++</span><span class="br0">&#41;</span> <span class="br0">&#123;</span><span class="br0">&#125;</span></pre></div></div>




<p>This doesn&#8217;t make it shorter, but it does make it more efficient, although marginally so&#8230;</p>

<p>Another change we can make is to combine the iteration expression (<code>i++</code>) and the conditional expression (<code>i &lt; l</code>), like so:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw2">var</span> i <span class="sy0">=</span> <span class="sy0">-</span><span class="nu0">1</span><span class="sy0">,</span> l <span class="sy0">=</span> array.<span class="me1">length</span><span class="sy0">;</span> <span class="sy0">++</span>i <span class="sy0">&lt;</span> l<span class="sy0">;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span><span class="br0">&#125;</span></pre></div></div>




<p>Notice that we&#8217;re starting with an index of <code>-1</code>, but won&#8217;t worry because before the loop&#8217;s body runs, the conditional expression is run, and in the above code, the conditional expression is iterating the index and testing it against the length all in one.</p>

<p>It&#8217;s important to note that the prefix increment/decrement operators (<code>++i</code>/<code>--i</code>) return the changed value, while the postfix increment/decrement operators (<code>i++</code>/<code>i--</code>) return the old value. To make this clearer:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> x <span class="sy0">=</span> <span class="nu0">5</span><span class="sy0">;</span>
<span class="kw3">alert</span><span class="br0">&#40;</span>x<span class="sy0">++</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// alerts 5 (old value)</span>
<span class="kw3">alert</span><span class="br0">&#40;</span>x<span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// alerts 6</span>
&nbsp;
<span class="kw2">var</span> y <span class="sy0">=</span> <span class="nu0">5</span><span class="sy0">;</span>
<span class="kw3">alert</span><span class="br0">&#40;</span><span class="sy0">++</span>y<span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// alerts 6 (new value)</span>
<span class="kw3">alert</span><span class="br0">&#40;</span>y<span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// alerts 6</span></pre></div></div>




<p>Another looping &#8220;pattern&#8221; in JavaScript is to assign and rely on what&#8217;s returned from that assignment for the conditional expression:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> elements <span class="sy0">=</span> document.<span class="me1">getElementsByTagName</span><span class="br0">&#40;</span><span class="st0">'a'</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
<span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw2">var</span> i <span class="sy0">=</span> <span class="sy0">-</span><span class="nu0">1</span><span class="sy0">,</span> el<span class="sy0">;</span> el <span class="sy0">=</span> elements<span class="br0">&#91;</span><span class="sy0">++</span>i<span class="br0">&#93;</span><span class="sy0">;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
  el<span class="sy0">;</span> <span class="co1">// =&gt; a single element</span>
<span class="br0">&#125;</span></pre></div></div>




<p>Yesterday&#8217;s post on truthy &#038; falsey bears some relevance here. The expression <code>el=elements[++i]</code> will return the value of <code>elements[++i]</code>. If this value is falsey the loop will not continue. An element list is full of truthy values (objects). We don&#8217;t need to be worried about falsey values. Note that in this approach, you may be sacrificing performance for terseness.</p>

<p>In many situations, we do want to iterate over falsey values too, e.g.</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> myArray <span class="sy0">=</span> <span class="br0">&#91;</span><span class="nu0">1</span><span class="sy0">,</span> <span class="nu0">2</span><span class="sy0">,</span> <span class="nu0">3</span><span class="sy0">,</span> <span class="kw2">null</span><span class="sy0">,</span> <span class="nu0">8</span><span class="sy0">,</span> <span class="nu0">54</span><span class="sy0">,</span> <span class="kw2">null</span><span class="sy0">,</span> <span class="nu0">0</span><span class="sy0">,</span> <span class="nu0">32</span><span class="br0">&#93;</span><span class="sy0">;</span></pre></div></div>




<p>With something like this it would be best to use the traditional <code>i&lt;length</code> conditional expression, but if you&#8217;re so inclined feel free to mix the conditional and iteration expressions together like shown further up (<code>++i&lt;l</code>).</p>

<p>If we were feeling a bit crazy, we could combine everything &#8212; iteration, conditional test, and assignment of indexed value &#8212; in a single expression:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> array <span class="sy0">=</span> <span class="br0">&#91;</span><span class="st0">'a'</span><span class="sy0">,</span><span class="st0">'b'</span><span class="sy0">,</span><span class="st0">'c'</span><span class="br0">&#93;</span><span class="sy0">;</span>
&nbsp;
<span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw2">var</span> i <span class="sy0">=</span> <span class="sy0">-</span><span class="nu0">1</span><span class="sy0">,</span> l <span class="sy0">=</span> array.<span class="me1">length</span><span class="sy0">,</span> <span class="kw1">item</span><span class="sy0">;</span> <span class="kw1">item</span> <span class="sy0">=</span> array<span class="br0">&#91;</span><span class="sy0">++</span>i<span class="br0">&#93;</span><span class="sy0">,</span> i <span class="sy0">&lt;</span> l<span class="sy0">;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
  <span class="kw3">alert</span><span class="br0">&#40;</span><span class="kw1">item</span><span class="br0">&#41;</span><span class="sy0">;</span>
<span class="br0">&#125;</span>
&nbsp;
<span class="co1">// alerts, a, b, c</span></pre></div></div>




<p>Here we used the useful comma operator which always returns its right-hand operand. In this example we used it to make sure that <code>i &lt; l</code> is what the condition expression returns. Before the comma we&#8217;re assigning the value at the iterated index within the array.</p>

<p>I don&#8217;t really suggest doing all of this in one line, and to be honest, there&#8217;s nothing wrong with conventional looping structures. What I am trying to put across is how much expressive diversity JavaScript provides.</p>

<h3>Assignments</h3>

<p>Assignments are expressions too, so you can slot them in wherever you want:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> a <span class="sy0">=</span> <span class="nu0">1</span><span class="sy0">;</span>
<span class="kw3">alert</span><span class="br0">&#40;</span>a <span class="sy0">=</span> <span class="nu0">2</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// alerts 2</span>
<span class="kw3">alert</span><span class="br0">&#40;</span>a<span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// alerts 2</span></pre></div></div>




<p>An assignment operator will always return whatever is on its right-hand side. Be careful with slotting in assignment expressions wherever you want though, because they can be misconstrued for equality operators. For example:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> match<span class="sy0">;</span>
&nbsp;
<span class="kw1">if</span> <span class="br0">&#40;</span>match <span class="sy0">=</span> <span class="st0">'1/2/3'</span>.<span class="me1">match</span><span class="br0">&#40;</span><span class="co2">/\d/</span><span class="br0">&#41;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
  <span class="co1">//...</span>
<span class="br0">&#125;</span></pre></div></div>




<p>To some, upon initial inspection, it may appear that we&#8217;re testing <code>match</code> for equality against <code>'1/2/3'.match(/\d/)</code> when in fact the latter is being assigned to the former, and the <code>if</code> statement will run if the assignment expression returns a truthy value (i.e. if its right-hand side operand is truthy).</p>

<h3>Casting to a number</h3>

<p>Quick and easy:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> str <span class="sy0">=</span> <span class="st0">'222'</span><span class="sy0">;</span>
<span class="kw2">var</span> num <span class="sy0">=</span> Number<span class="br0">&#40;</span>str<span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; 222</span>
&nbsp;
<span class="kw1">typeof</span> num<span class="sy0">;</span> <span class="co1">// =&gt; 'number'</span></pre></div></div>




<p>A shortcut is the unary plus (<code>+</code>) operator, used like so:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> str <span class="sy0">=</span> <span class="st0">'222'</span><span class="sy0">;</span>
<span class="kw2">var</span> num <span class="sy0">=</span> <span class="sy0">+</span>str<span class="sy0">;</span> <span class="co1">// =&gt; 222</span>
&nbsp;
<span class="kw1">typeof</span> num<span class="sy0">;</span> <span class="co1">// =&gt; 'number'</span></pre></div></div>




<p>It works in exactly the same way.</p>

<h3>Casting to a string</h3>

<p>Once again, quick and easy:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> arr <span class="sy0">=</span> <span class="br0">&#91;</span><span class="nu0">1</span><span class="sy0">,</span><span class="nu0">2</span><span class="sy0">,</span><span class="nu0">3</span><span class="br0">&#93;</span><span class="sy0">;</span>
<span class="kw2">var</span> str <span class="sy0">=</span> String<span class="br0">&#40;</span>arr<span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; '1,2,3'</span>
&nbsp;
<span class="kw1">typeof</span> str<span class="sy0">;</span> <span class="co1">// =&gt; 'string'</span></pre></div></div>




<p>The shortcut, this time, is to simply concatenate an empty string to the value that you&#8217;re casting:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> arr <span class="sy0">=</span> <span class="br0">&#91;</span><span class="nu0">1</span><span class="sy0">,</span><span class="nu0">2</span><span class="sy0">,</span><span class="nu0">3</span><span class="br0">&#93;</span><span class="sy0">;</span>
<span class="kw2">var</span> str <span class="sy0">=</span> <span class="st0">''</span> <span class="sy0">+</span> arr<span class="sy0">;</span> <span class="co1">// =&gt; '1,2,3'</span>
&nbsp;
<span class="kw1">typeof</span> str<span class="sy0">;</span> <span class="co1">// =&gt; 'string'</span></pre></div></div>




<h3>Saving references</h3>

<p>Property lookup can be verbose and inefficient. To save space and to benefit performance it&#8217;s common to save references and access those properties via the new reference instead of having to evaluate the entire expression every time you want the nested value:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="co1">// Original:</span>
document.<span class="me1">body</span>.<span class="me1">style</span>.<span class="me1">color</span><span class="sy0">;</span>
&nbsp;
<span class="co1">// &quot;Caching&quot;</span>
<span class="kw2">var</span> style <span class="sy0">=</span> document.<span class="me1">body</span>.<span class="me1">style</span><span class="sy0">;</span>
&nbsp;
<span class="co1">// Whenever I need to access the `color` value:</span>
style.<span class="me1">color</span><span class="sy0">;</span></pre></div></div>




<p>It&#8217;s often referred to as caching. Essentially, all that&#8217;s happening is that a new reference is being created for an object and being assigned to an identifier that you specify. Let&#8217;s start with this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> data <span class="sy0">=</span> <span class="br0">&#123;</span>
    config<span class="sy0">:</span> <span class="br0">&#123;</span>
        doSomething<span class="sy0">:</span> <span class="kw2">function</span><span class="br0">&#40;</span><span class="kw1">item</span><span class="br0">&#41;</span><span class="br0">&#123;</span>
            <span class="kw3">alert</span><span class="br0">&#40;</span><span class="kw1">item</span><span class="br0">&#41;</span><span class="sy0">;</span>
        <span class="br0">&#125;</span>
    <span class="br0">&#125;</span>
<span class="br0">&#125;</span><span class="sy0">;</span>
&nbsp;
<span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw2">var</span> i <span class="sy0">=</span> <span class="sy0">-</span><span class="nu0">1</span><span class="sy0">,</span> l <span class="sy0">=</span> someArray.<span class="me1">length</span><span class="sy0">;</span> <span class="sy0">++</span>i <span class="sy0">&lt;</span> l<span class="sy0">;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    data.<span class="me1">config</span>.<span class="me1">doSomething</span><span class="br0">&#40;</span>someArray<span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy0">;</span>
<span class="br0">&#125;</span></pre></div></div>




<p>It would make sense to minimise the amount of property access that needs to occur within the loop, and thus, potentially, anywhere else in our application that references <code>data.config</code> too:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> config <span class="sy0">=</span> data.<span class="me1">config</span><span class="sy0">;</span></pre></div></div>




<p>Now the loop can simply reference <code>config</code> instead of <code>data.config</code>:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw2">var</span> i <span class="sy0">=</span> <span class="sy0">-</span><span class="nu0">1</span><span class="sy0">,</span> l <span class="sy0">=</span> someArray.<span class="me1">length</span><span class="sy0">;</span> <span class="sy0">++</span>i <span class="sy0">&lt;</span> l<span class="sy0">;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    config.<span class="me1">doSomething</span><span class="br0">&#40;</span>someArray<span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy0">;</span>
<span class="br0">&#125;</span></pre></div></div>




<p>We could even &#8220;cache&#8221; the function itself:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> doSomething <span class="sy0">=</span> data.<span class="me1">config</span>.<span class="me1">doSomething</span><span class="sy0">;</span></pre></div></div>




<p>And then call it directly within the loop:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw2">var</span> i <span class="sy0">=</span> <span class="sy0">-</span><span class="nu0">1</span><span class="sy0">,</span> l <span class="sy0">=</span> someArray.<span class="me1">length</span><span class="sy0">;</span> <span class="sy0">++</span>i <span class="sy0">&lt;</span> l<span class="sy0">;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    doSomething<span class="br0">&#40;</span>someArray<span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy0">;</span>
<span class="br0">&#125;</span></pre></div></div>




<p><strong>IMPORTANT</strong>: It&#8217;s important to note that, when you assign a member function (that is, a function that is a property of an object) you are de-binding its <code>this</code> value, i.e. the context in which it runs. Here&#8217;s an example:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> obj <span class="sy0">=</span> <span class="br0">&#123;</span>
    value<span class="sy0">:</span> <span class="nu0">234</span><span class="sy0">,</span>
    fn<span class="sy0">:</span> <span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span> <span class="kw1">return</span> <span class="kw1">this</span>.<span class="me1">value</span><span class="sy0">;</span> <span class="br0">&#125;</span>
<span class="br0">&#125;</span><span class="sy0">;</span>
&nbsp;
obj.<span class="me1">fn</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; 234</span>
&nbsp;
<span class="kw2">var</span> fn <span class="sy0">=</span> obj.<span class="me1">fn</span><span class="sy0">;</span>
fn<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; undefined</span></pre></div></div>




<p>De-binding the <code>fn</code> method will make its context the global (window) object instead of the <code>obj</code> which we defined, so when our <code>fn</code> function looks for its `this.value` it won&#8217;t find it (because <code>this</code> is the <code>window</code>, which doesn&#8217;t have `value` defined).</p>

<h3>End of part 2</h3>

<p>Comment if you feel compelled.</p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/terse-javascript-101-part-2/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>Truthy &amp; Falsey</title>
		<link>http://james.padolsey.com/javascript/truthy-falsey/</link>
		<comments>http://james.padolsey.com/javascript/truthy-falsey/#comments</comments>
		<pubDate>Wed, 19 Oct 2011 21:36:33 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=1912</guid>
		<description><![CDATA[Before we continue with the &#8220;Terse JavaScript 101&#8243; series, we&#8217;re going to take a break and explore, in detail, <em>truthy</em> and <em>falsey</em>.

These are fundamental topics which I should have covered in more detail yesterday. There is copious information on this elsewhere online, so don&#8217;t feel&#8230;]]></description>
			<content:encoded><![CDATA[<p>Before we continue with the &#8220;Terse JavaScript 101&#8243; series, we&#8217;re going to take a break and explore, in detail, <em>truthy</em> and <em>falsey</em>.</p>

<p>These are fundamental topics which I should have covered in more detail yesterday. There is copious information on this elsewhere online, so don&#8217;t feel limited to this post in your study.</p>

<p>
<strong>Truthy</strong>: Something which evaluates to TRUE.<br/>
<strong>Falsey</strong>: Something which evaluates to FALSE.<br/>
</p>

<p>It&#8217;s mostly logical. One (1) is truthy, Zero (0) is falsey. An object of any kind (including functions, arrays, RegExp objects, etc.) is always truthy. The easiest way to determine if something is truthy is to determine that it&#8217;s <em>not</em> falsey. There are only five falsey values in JavaScript:</p>

<p><code>undefined</code>, <code>null</code>, <code>NaN</code>, <code>0</code>, <code>""</code> (<em>empty string</em>), and <code>false</code>, of course.</p>

<p><em><strong>Note</strong></em>: It is possible to explicitly wrap a primitive (string, number, null, undefined, boolean) in an object, which will make it truthy. For example, <code>0</code> (<em>zero</em>) is falsey, but <code>new Number(0)</code> is truthy. A scarier example is <code>new Boolean(false)</code> which is also truthy! Be careful. Only very rarely should you need to explicitly wrap primitives.</p>

<p>Why should you care what&#8217;s truthy and what&#8217;s falsey?</p>

<p>A value&#8217;s truthi&#8217;ness determines what it will evaluate to in logical expressions. For example:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">if</span> <span class="br0">&#40;</span><span class="nu0">0</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="kw3">alert</span><span class="br0">&#40;</span><span class="st0">'ALERT'</span><span class="br0">&#41;</span><span class="sy0">;</span>
<span class="br0">&#125;</span></pre></div></div>




<p>We know that the <code>alert()</code> call will never run, because <code>0</code>, being a falsey value, doesn&#8217;t satisfy the <code>if</code> statement&#8217;s condition &#8212; i.e. to run only if the passed expression is NOT falsey.</p>

<p><a href="http://bclary.com/2004/11/07/#a-12.5">From the spec</a>:</p>

<blockquote>
<p>The production IfStatement : if ( Expression ) Statement is evaluated as follows:</p>


<div class="wp_syntax"><div class="code"><pre class="txt" style="font-family:monospace;">1. Evaluate Expression.
2. Call GetValue(Result(1)).
&nbsp;
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
&nbsp;
3. Call ToBoolean(Result(2)).
&nbsp;
↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑
&nbsp;
4. If Result(3) is false, return (normal, empty, empty).
5. Evaluate Statement.
6. Return Result(5).</pre></div></div>



</blockquote>

<p><small>If you&#8217;re wondering, the phrase <em>return (normal, empty, empty)</em> essentially, means: continue with the program in a normal fashion. See <a href="http://bclary.com/2004/11/07/#a-8.9">8.9</a> for more.</small></p>

<p>As the subtle arrows point out, the bit we&#8217;re interested in is step 3, which calls ToBoolean with the result of step 2, which is essentially (<a href="http://bclary.com/2004/11/07/#a-8.7.1">*</a>) the value you passed in. But what is <em>ToBoolean</em>??</p>

<p><a href="http://bclary.com/2004/11/07/#a-9.2">ToBoolean</a> is simple:</p>

<table summary="Boolean Conversion">
<col width="150" />
<thead>
  <tr>
    <th>Input Type</th>

    <th>Result</th>
  </tr>
</thead>

<tbody>

  <tr>
    <td>Undefined</td>

    <td><b>false</b></td>
  </tr>

  <tr>
    <td>Null</td>

    <td><b>false</b></td>
  </tr>

  <tr>
    <td>Boolean</td>

    <td>The result equals the input argument (no conversion).</td>
  </tr>

  <tr>
    <td>Number</td>

    <td>The result is <b>false</b> if the argument is <b>+0,
    -0,</b> or NaN; otherwise the result is <b>true.</b></td>

  </tr>

  <tr>
    <td>String</td>

    <td>The result is <b>false</b> if the argument is the empty
    string (its length is zero); otherwise the result is
    <b>true.</b></td>
  </tr>

  <tr>
    <td>Object</td>

    <td><b>true</b></td>
  </tr>
</tbody>
</table>

<p>I hope this has made it clear enough.</p>

<h3>Enough of the spec!</h3>

<p>We now know what happens when we pass something as an <code>if</code> statement&#8217;s expression (<code>if(..this bit..){}</code>), but how much relevance does <em>truthy</em> and <em>falsey</em> have in other logical contexts? Well, a lot.</p>

<p>Let&#8217;s explore the basic <code>if</code> statement one last time though:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">if</span> <span class="br0">&#40;</span>X<span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="co1">// If this code runs, what have we proven about X?</span>
    <span class="kw3">alert</span><span class="br0">&#40;</span><span class="nu0">123</span><span class="br0">&#41;</span><span class="sy0">;</span>
<span class="br0">&#125;</span></pre></div></div>




<p>If <code>123</code> is alerted what can we say (for sure) about X? We can definitely say that it is NOT one of: <code>undefined</code>, <code>null</code>, <code>NaN</code>, <code>0</code>, <code>""</code> (<em>empty string</em>), or <code>false</code>. We can therefore say that <code>X</code> is truthy. It might be the literal value <code>true</code>, a number that&#8217;s not zero, an array, a function, etc.</p>

<p>Remember, everything in JavaScript that isn&#8217;t a primative value can be considered an object. Functions are objects. Arrays are objects. And all objects are truthy.</p>

<p>Since all objects are truthy, code like this is quite common:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> el <span class="sy0">=</span> document.<span class="me1">getElementById</span><span class="br0">&#40;</span><span class="st0">'foo'</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
<span class="kw1">if</span> <span class="br0">&#40;</span>el<span class="br0">&#41;</span> <span class="br0">&#123;</span>
    el.<span class="me1">style</span>.<span class="me1">color</span> <span class="sy0">=</span> <span class="st0">'red'</span><span class="sy0">;</span>
<span class="br0">&#125;</span></pre></div></div>




<p><code>el</code> is not a boolean, it&#8217;s just an object (in this case, a DOM Element object). The if block only executes if its expression is truthy. We could be more explicit though. The <code>getElementById</code> function returns <code>null</code> if it doesn&#8217;t find the element, so we could do:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> el <span class="sy0">=</span> document.<span class="me1">getElementById</span><span class="br0">&#40;</span><span class="st0">'foo'</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
<span class="kw1">if</span> <span class="br0">&#40;</span>el <span class="sy0">!==</span> <span class="kw2">null</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    el.<span class="me1">style</span>.<span class="me1">color</span> <span class="sy0">=</span> <span class="st0">'red'</span><span class="sy0">;</span>
<span class="br0">&#125;</span></pre></div></div>




<p>There&#8217;s usually little advantage in explicitly stating the falsey value that you&#8217;re looking for. Sometimes, you might want to guard against a <code>null</code> or an <code>undefined</code> but allow <code>false</code>, for example. In such circumstances, obviously, use the explicit syntax (strict equality and strict inequality operators &#8211; <code>===/!==</code>).</p>

<p>The <code>ToBoolean</code> thing that we referenced above happens in all logical contexts in JavaScript. For example, the <code>&#038;&#038;</code> (logical AND) operator:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="nu0">0</span> <span class="sy0">&amp;&amp;</span> <span class="kw3">alert</span><span class="br0">&#40;</span><span class="nu0">0</span><span class="br0">&#41;</span><span class="sy0">;</span>
<span class="nu0">1</span> <span class="sy0">&amp;&amp;</span> <span class="kw3">alert</span><span class="br0">&#40;</span><span class="nu0">1</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>In this case, only <code>1</code> will be alerted, since zero is falsey and therefore does not satisfy the <code>&#038;&#038;</code>&#8216;s desire for a left-hand truthy operand. The logical AND operator will only evaluate its right-hand operand if its left-hand operand is truthy.</p>

<p>Further up we checked that the return value of <code>getElementById</code> wasn&#8217;t null by simply checking if it was truthy. If <code>el</code> was truthy then we knew the element existed in the DOM and we could begin to interact with it programatically.</p>

<p>We use a similar concept with object access.</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw3">alert</span><span class="br0">&#40;</span>foo.<span class="me1">bar</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// Alerting the value of the 'bar' property of 'foo'</span></pre></div></div>




<p>The only values that will throw an error when you try to access a property are <code>null</code> and <code>undefined</code>. So, if <code>foo</code> is truthy then we can safely attempt to access it&#8217;s <code>bar</code> property without worrying about exceptions being thrown.</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">if</span> <span class="br0">&#40;</span>foo<span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="kw3">alert</span><span class="br0">&#40;</span>foo.<span class="me1">bar</span><span class="br0">&#41;</span><span class="sy0">;</span>
<span class="br0">&#125;</span></pre></div></div>




<h3>Assume carefully</h3>

<p>With our if statement we have only proven that <code>foo</code> is truthy. It still might not be the object we expect. This is something to consider. Normally though, it&#8217;s safe enough to suppose that if some obscurely named value is not falsey, it&#8217;ll be the truthy value you desire and not something you don&#8217;t want.</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">element.<span class="me1">addEventListener</span> <span class="sy0">?</span>
    element.<span class="me1">addEventListener</span><span class="br0">&#40;</span><span class="st0">'click'</span><span class="sy0">,</span> func<span class="sy0">,</span> <span class="kw2">false</span><span class="br0">&#41;</span> <span class="sy0">:</span>
    element.<span class="me1">attachEvent</span><span class="br0">&#40;</span><span class="st0">'onclick'</span><span class="sy0">,</span> func<span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>Here we make some assumptions:</p>

<ol>
    <li>If element has a property <code>addEventListener</code> and its value is something truthy, it must be a function, so we&#8217;ll call it.</li>
    <li>If it doesn&#8217;t exist then <code>attachEvent</code> must exist and must be a function.</li>
</ol>

<p>The code above happens to be working around old IE versions that don&#8217;t have the W3C DOM Event method, <code>addEventListener</code>. The assumptions I&#8217;m making are considered safe in the environments that I intend my web app to operate in, but they may not be safe assumptions in other environments, so it&#8217;s important to be wary of the fact that: just because something is truthy doesn&#8217;t mean it&#8217;s the truthy value you happen to be looking for (the same goes for falsi&#8217;ness).</p>

<p>It&#8217;s common to attempt deep object access using the following structure:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">a <span class="sy0">&amp;&amp;</span> a.<span class="me1">b</span> <span class="sy0">&amp;&amp;</span> a.<span class="me1">b</span>.<span class="me1">c</span> <span class="sy0">&amp;&amp;</span> a.<span class="me1">b</span>.<span class="me1">c</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<ol>
    <li>Make sure <code>a</code> is truthy.</li>
    <li>Make sure <code>a.b</code> is truthy (and thus exists).</li>
    <li>Make sure <code>a.b.c</code> is truthy (and thus exists).</li>
    <li>Call <code>a.b.c</code>.</li>
</ol>

<p>Again, we&#8217;re making assumptions, but we already knew that. This structure is very useful, although too much of it can make your code bloated, so maybe consider other options. For one: consider what you CAN safely assume. In some instances, you may be able to do this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">a <span class="sy0">&amp;&amp;</span> a.<span class="me1">b</span>.<span class="me1">c</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<ol>
    <li>Make sure <code>a</code> is truthy.</li>
    <li>Call <code>a.b.c</code>.</li>
</ol>

<p>In this example, we&#8217;ve determined that it is safe to assume that if <code>a</code> is truthy, it is the very object that we&#8217;re looking for, and therefore must have a minimum structure of: <code>a={b:{c:function(){...}}}</code>. We&#8217;re aware of our own data structure so can make this assumption.</p>

<h3>Explicit booleans</h3>

<p>You might be left wondering why we even bother having proper boolean values in JavaScript if we can get around quite easily with our other truthy and falsey values. And it&#8217;s true, we could manage without these booleans, and we rarely check for them explicitly. We usually just do something like:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">if</span> <span class="br0">&#40;</span>foo.<span class="me1">isAFoo</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="co1">// ...</span>
<span class="br0">&#125;</span></pre></div></div>




<p><code>foo.isAFoo()</code> could return any truthy value (not necessarily the boolean of <code>true</code>) and it would make no difference to the code execution.</p>

<p>But, it is important, in many situations, to be explicit in our intentions. So we should insist on using real booleans when there is a binary decision to make (two possible values).</p>

<p>To cast a value to its boolean representation, we can just use <code>ToBoolean</code>. We can indirectly use this internal method by calling the <code>Boolean</code> constructor as a function:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">Boolean<span class="br0">&#40;</span><span class="nu0">0</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; false</span></pre></div></div>




<p>It will return a boolean value &#8212; either true or false, and is a really quick way of finding out whether a value is truthy of falsey:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">Boolean<span class="br0">&#40;</span>undefined<span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; false</span>
Boolean<span class="br0">&#40;</span><span class="kw2">null</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; false</span>
Boolean<span class="br0">&#40;</span><span class="kw2">false</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; false</span>
Boolean<span class="br0">&#40;</span><span class="nu0">0</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; false</span>
Boolean<span class="br0">&#40;</span><span class="st0">&quot;&quot;</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; false</span>
Boolean<span class="br0">&#40;</span>NaN<span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; false</span>
&nbsp;
Boolean<span class="br0">&#40;</span><span class="nu0">1</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; true</span>
Boolean<span class="br0">&#40;</span><span class="br0">&#91;</span><span class="nu0">1</span><span class="sy0">,</span><span class="nu0">2</span><span class="sy0">,</span><span class="nu0">3</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; true</span>
Boolean<span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span><span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; true</span></pre></div></div>




<p>A well-known and widely used shortcut is to use the logical-NOT operator twice, like so:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="sy0">!!</span><span class="kw2">null</span><span class="sy0">;</span> <span class="co1">// =&gt; false</span>
<span class="sy0">!!</span><span class="nu0">0</span><span class="sy0">;</span> <span class="co1">// =&gt; false</span>
<span class="sy0">!!</span><span class="nu0">123</span><span class="sy0">;</span> <span class="co1">// =&gt; true</span>
<span class="sy0">!!</span><span class="st0">'foo'</span><span class="sy0">;</span> <span class="co1">// =&gt; true</span></pre></div></div>




<p>I&#8217;ll leave that up to you to figure out <img src='http://james.padolsey.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>

<h3>[complete!]</h3>

<p>That&#8217;s it for today. Hopefully this has served as, at least, a minimal introduction to truthy &#038; falsey.</p>
]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/truthy-falsey/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Terse JavaScript 101 – part 1</title>
		<link>http://james.padolsey.com/javascript/terse-javascript-101-part-1/</link>
		<comments>http://james.padolsey.com/javascript/terse-javascript-101-part-1/#comments</comments>
		<pubDate>Tue, 18 Oct 2011 21:23:00 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Expressions]]></category>
		<category><![CDATA[Readability]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=1896</guid>
		<description><![CDATA[While some folk will argue that verbose code aids readability, I think almost the opposite, and in this post I&#8217;m going to list some basic tips for minimising redundant clutter in your code. JavaScript is a fun language at its core &#8212; it&#8217;s worth learning&#8230;]]></description>
			<content:encoded><![CDATA[<p>While some folk will argue that verbose code aids readability, I think almost the opposite, and in this post I&#8217;m going to list some basic tips for minimising redundant clutter in your code. JavaScript is a fun language at its core &#8212; it&#8217;s worth learning the tiny details.</p>

<p>I hope this post is useful to someone. I wrote it <strong>not</strong> for beginners (although it will be helpful to them), but for all those people writing JavaScript on a daily basis yet haven&#8217;t been afforded the time/motivation to get to know the language properly.</p>

<h3>new Object()</h3>

<p>Nope, don&#8217;t do this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> o <span class="sy0">=</span> <span class="kw2">new</span> Object<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>Or any of this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> a <span class="sy0">=</span> <span class="kw2">new</span> Array<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span>
<span class="kw2">var</span> b <span class="sy0">=</span> <span class="kw2">new</span> Object<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span>
<span class="kw2">var</span> c <span class="sy0">=</span> <span class="kw2">new</span> RegExp<span class="br0">&#40;</span><span class="st0">&quot;1(.)3&quot;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>Do this instead:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> a <span class="sy0">=</span> <span class="br0">&#91;</span><span class="br0">&#93;</span><span class="sy0">;</span>
<span class="kw2">var</span> b <span class="sy0">=</span> <span class="br0">&#123;</span><span class="br0">&#125;</span><span class="sy0">;</span>
<span class="kw2">var</span> c <span class="sy0">=</span> <span class="co2">/1(.)3/</span><span class="sy0">;</span></pre></div></div>




<p>Array literal, object literal, regular expression literal. They rock. There&#8217;s usually no need to use the constructor functions when literals are available (please see the note below though).</p>

<p><em>Note</em>: There are situations when calling <code>Array</code> or <code>RegExp</code> directly can be useful. In such situations, you needn&#8217;t bother with the <code>new</code> operator. <code>Array(1,2,3)</code> will produce the same as <code>new Array(1,2,3)</code>. Calling <code>RegExp</code> directly can be useful for dynamically building a regular expression from various strings.</p>

<h3>Calling a constructor</h3>

<p>If you&#8217;re <em>not</em> passing any arguments then the parenthesis are not required. E.g.</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> a <span class="sy0">=</span> <span class="kw2">new</span> Animal<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>&#8230; and this becomes:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> a <span class="sy0">=</span> <span class="kw2">new</span> Animal<span class="sy0">;</span></pre></div></div>




<p>Petty, perhaps. Still worth knowing though.</p>

<h3>var;var;var</h3>

<p>Quick and easy. Less of this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> fun <span class="sy0">=</span> <span class="nu0">123</span><span class="sy0">;</span>
<span class="kw2">var</span> tun <span class="sy0">=</span> <span class="nu0">456</span><span class="sy0">;</span>
<span class="kw2">var</span> run <span class="sy0">=</span> <span class="nu0">789</span><span class="sy0">;</span></pre></div></div>




<p>And more of this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> fun <span class="sy0">=</span> <span class="nu0">123</span><span class="sy0">,</span>
    tun <span class="sy0">=</span> <span class="nu0">456</span><span class="sy0">,</span>
    run <span class="sy0">=</span> <span class="nu0">789</span><span class="sy0">;</span></pre></div></div>




<p><em>This is why you should use a tab width of FOUR (or 4 spaces).</em></p>

<h3>Undefined &#038; Null</h3>

<p>The following is universally true in JavaScript (assuming <code>undefined</code> hasn&#8217;t been mutilated):</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">undefined <span class="sy0">==</span> <span class="kw2">null</span></pre></div></div>




<p>&#8220;So what?&#8221;, you say? Well, it means you can replace this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">if</span> <span class="br0">&#40;</span>foo <span class="sy0">===</span> undefined <span class="sy0">||</span> foo <span class="sy0">===</span> <span class="kw2">null</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="co1">//...</span>
<span class="br0">&#125;</span></pre></div></div>




<p>&#8230; With this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">if</span> <span class="br0">&#40;</span>foo <span class="sy0">==</span> <span class="kw2">null</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="co1">//...</span>
<span class="br0">&#125;</span></pre></div></div>




<p>If something is <code>==</code> to <code>null</code> then it is either <code>null</code> or <code>undefined</code>. Those are the only possible values.</p>

<h3>Returning undefined</h3>

<p>Not returning something from a function is the same as returning undefined, so you may as well not bother explicitly returning undefined:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">function</span> a<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span><span class="br0">&#125;</span>
<span class="kw2">function</span> b<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span> <span class="kw1">return</span><span class="sy0">;</span> <span class="br0">&#125;</span>
<span class="kw2">function</span> c<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span> <span class="kw1">return</span> undefined<span class="sy0">;</span> <span class="br0">&#125;</span>
&nbsp;
a<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="sy0">===</span> b<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// true</span>
b<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="sy0">===</span> c<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// true</span></pre></div></div>




<p><em>Note</em>: you should be careful with the <code>undefined</code> value as it can be changed. E.g. You can do <code>undefined = true</code> beforehand. <strong>The universe would shatter if you did that though, <em>so please don&#8217;t</em></strong>. Many libraries declare an empty (undefined) variable in an enclosed scope, which provides a real <code>undefined</code>:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span>
&nbsp;
    <span class="co1">// My private scope. They can't see me in here.</span>
&nbsp;
    <span class="kw2">var</span> undef<span class="sy0">;</span>
&nbsp;
    undef<span class="sy0">;</span> <span class="co1">// =&gt; definitely undefined</span>
&nbsp;
<span class="br0">&#125;</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>Or, more succinctly:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span>undef<span class="br0">&#41;</span><span class="br0">&#123;</span>
&nbsp;
    undef<span class="sy0">;</span> <span class="co1">// =&gt; definitely undefined</span>
&nbsp;
<span class="br0">&#125;</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// &lt;- not passing anything in!</span></pre></div></div>




<h3>Empty array values</h3>

<p>This is entirely legal in JavaScript:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> a <span class="sy0">=</span> <span class="br0">&#91;</span><span class="sy0">,,,</span><span class="st0">'foo'</span><span class="br0">&#93;</span><span class="sy0">;</span>
a<span class="br0">&#91;</span><span class="nu0">3</span><span class="br0">&#93;</span><span class="sy0">;</span> <span class="co1">// =&gt; &quot;foo&quot;</span></pre></div></div>




<p>One potential use-case of this was discussed in my recent post, <a href="http://james.padolsey.com/javascript/match-trick/">`match.()` trick</a>.</p>

<h3>Less blocks, more expressions</h3>

<p>I&#8217;m sure we&#8217;ve all seen something like this before:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">function</span> validateFoo<span class="br0">&#40;</span>foo<span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="kw2">var</span> regexResult <span class="sy0">=</span> <span class="co2">/^foo+$/</span>.<span class="me1">test</span><span class="br0">&#40;</span>foo<span class="br0">&#41;</span><span class="sy0">;</span>
    <span class="kw1">if</span> <span class="br0">&#40;</span>regexResult<span class="br0">&#41;</span> <span class="br0">&#123;</span>
        <span class="kw1">return</span> <span class="kw2">true</span><span class="sy0">;</span>
    <span class="br0">&#125;</span>
    <span class="kw1">return</span> <span class="kw2">false</span><span class="sy0">;</span>
<span class="br0">&#125;</span></pre></div></div>




<p>A cleaner and more sensible solution is this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">function</span> validateFoo<span class="br0">&#40;</span>foo<span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="kw1">return</span> <span class="co2">/^foo+$/</span>.<span class="me1">test</span><span class="br0">&#40;</span>foo<span class="br0">&#41;</span><span class="sy0">;</span>
<span class="br0">&#125;</span></pre></div></div>




<p>No fussing with <code>if</code> statements and multiple returns. You can do everything within a single return statement.</p>

<p>Another example. We want to create a function that logs a name, specified by the arguments <code>forename</code> and <code>surname</code>, but if these arguments aren&#8217;t passed then the function should use the default values, &#8220;Bob&#8221; and &#8220;Smith&#8221;, respectively:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">function</span> printName<span class="br0">&#40;</span>forename<span class="sy0">,</span> surname<span class="br0">&#41;</span> <span class="br0">&#123;</span>
&nbsp;
    <span class="kw1">if</span> <span class="br0">&#40;</span>forename <span class="sy0">==</span> <span class="kw2">null</span> <span class="sy0">||</span> forename <span class="sy0">==</span> <span class="st0">&quot;&quot;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
        forename <span class="sy0">=</span> <span class="st0">'Bob'</span><span class="sy0">;</span>
    <span class="br0">&#125;</span>
&nbsp;
    <span class="kw1">if</span> <span class="br0">&#40;</span>surname <span class="sy0">==</span> <span class="kw2">null</span> <span class="sy0">||</span> surname <span class="sy0">==</span> <span class="st0">&quot;&quot;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
        surname <span class="sy0">=</span> <span class="st0">'Smith'</span><span class="sy0">;</span>
    <span class="br0">&#125;</span>
&nbsp;
    console.<span class="me1">log</span><span class="br0">&#40;</span>forename <span class="sy0">+</span> <span class="st0">' '</span> <span class="sy0">+</span> surname<span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
<span class="br0">&#125;</span></pre></div></div>




<p>This can be condensed to:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">function</span> printName<span class="br0">&#40;</span>forename<span class="sy0">,</span> surname<span class="br0">&#41;</span> <span class="br0">&#123;</span>
&nbsp;
    forename <span class="sy0">=</span> forename <span class="sy0">||</span> <span class="st0">'Bob'</span><span class="sy0">;</span>
    surname <span class="sy0">=</span> surname <span class="sy0">||</span> <span class="st0">'Smith'</span><span class="sy0">;</span>
&nbsp;
    console.<span class="me1">log</span><span class="br0">&#40;</span>forename <span class="sy0">+</span> <span class="st0">' '</span> <span class="sy0">+</span> surname<span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
<span class="br0">&#125;</span></pre></div></div>




<p>Here, we&#8217;re using the logical OR operator (<code>||</code>) to provide a default value (right hand side) if the left hand side evaluates to false. Values that evaluate to false (i.e. &#8220;falsey&#8221;) are: An empty string (<code>""</code>), <code>null</code>, <code>undefined</code>, <code>0</code> and <code>false</code>.</p>

<p>So, this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">forename <span class="sy0">=</span> forename <span class="sy0">||</span> <span class="st0">'Bob'</span></pre></div></div>




<p>&#8230; is essentially saying: if <code>forename</code> is a truthy value, then assign <code>forename</code> to <code>forename</code> (in other words: don&#8217;t do anything), but if it is a falsey value (e.g. an empty string), then assign the string <code>"Bob"</code> to <code>forename</code>.</p>

<p>So, our new <code>printName</code> function will behave like so:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="co1">//                            -- Logged --</span>
printName<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span>                  <span class="co1">// Bob Smith</span>
printName<span class="br0">&#40;</span><span class="nu0">0</span><span class="sy0">,</span> <span class="nu0">0</span><span class="br0">&#41;</span><span class="sy0">;</span>              <span class="co1">// Bob Smith</span>
printName<span class="br0">&#40;</span><span class="kw2">false</span><span class="sy0">,</span> <span class="kw2">null</span><span class="br0">&#41;</span><span class="sy0">;</span>       <span class="co1">// Bob Smith</span>
printName<span class="br0">&#40;</span><span class="st0">'James'</span><span class="br0">&#41;</span><span class="sy0">;</span>           <span class="co1">// James Smith</span>
printName<span class="br0">&#40;</span><span class="st0">''</span><span class="sy0">,</span> <span class="st0">'Jones'</span><span class="br0">&#41;</span><span class="sy0">;</span>       <span class="co1">// Bob Jones</span>
printName<span class="br0">&#40;</span><span class="st0">'Bill'</span><span class="sy0">,</span> <span class="st0">'Jones'</span><span class="br0">&#41;</span><span class="sy0">;</span>   <span class="co1">// Bill Jones</span></pre></div></div>




<h3>Part 1 [OVER]</h3>

<p>That&#8217;s it for today. There may be a part two soon enough, depending on how useful this is to readers. I know many of you have surpassed this stage of learning, so sorry for boring you.</p>

<h3>Recommended viewing/reading</h3>

<p>Seriously, if you&#8217;re writing JavaScript as part of your job then you definitely owe it to future maintainers of your code to learning JS properly.</p>

<p><strong>EDIT</strong>: Crockford links don&#8217;t work. The <a href="http://www.youtube.com/watch?v=v2ifWcnQs6M">entire video can be seen on youtube</a> instead.

<ul>
<li><a href="http://video.yahoo.com/watch/111593/1710507">Douglas Crockford: &#8220;The JavaScript Programming Language&#8221;/1 of 4</a></li>
<li><a href="http://video.yahoo.com/watch/111594/1710553">Douglas Crockford: &#8220;The JavaScript Programming Language&#8221;/2 of 4</a></li>
<li><a href="http://video.yahoo.com/watch/111595/1710607">Douglas Crockford: &#8220;The JavaScript Programming Language&#8221;/3 of 4</a></li>
<li><a href="http://video.yahoo.com/watch/111596/1710658">Douglas Crockford: &#8220;The JavaScript Programming Language&#8221;/4 of 4</a></li>
<li><a href="http://net.tutsplus.com/tutorials/javascript-ajax/javascript-and-the-dom-series-lesson-1/">Bonus: Intro to JS &#038; the DOM</a></li>
</ul>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/terse-javascript-101-part-1/feed/</wfw:commentRss>
		<slash:comments>64</slash:comments>
		</item>
		<item>
		<title>The Absolute Silence</title>
		<link>http://james.padolsey.com/general/the-absolute-silence/</link>
		<comments>http://james.padolsey.com/general/the-absolute-silence/#comments</comments>
		<pubDate>Sun, 16 Oct 2011 08:43:46 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[My Life]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=1893</guid>
		<description><![CDATA[This isn&#8217;t for you or against you, whoever you are. This is for me, and for <a href="http://blogactionday.org/">Blog Action Day 2011</a>.

I hate to pester people in their happy bubbles of existence but sometimes it&#8217;s necessary to remind oneself how lucky one is to have access&#8230;]]></description>
			<content:encoded><![CDATA[<p>This isn&#8217;t for you or against you, whoever you are. This is for me, and for <a href="http://blogactionday.org/">Blog Action Day 2011</a>.</p>

<p>I hate to pester people in their happy bubbles of existence but sometimes it&#8217;s necessary to remind oneself how lucky one is to have access to the most rudimentary of things: shelter, food and water. There is no doubt that we take these things for granted.</p>

<p>It&#8217;s easy to find scary statistics to put a point across, but often they lack accuracy or are taken out of context. Well, these aren&#8217;t such statistics &#8212; they&#8217;re from the UN&#8217;s World Food Programme, and they&#8217;re both accurate and shocking:</p>

<ul>
    <li>One out of four children &#8211; roughly 146 million &#8211; in developing countries is <strong>underweight</strong><br/>
        <em>(Source: <a target="_blank" href="http://www.unicef.org/sowc/">The State of the World&#8217;s Children</a>, UNICEF,&nbsp;2007)</em>
    </li>
    <li>Every <strong>day</strong>, 16,000 children die of starvation (most of them under five). This equates to 1 child every 5 seconds.<br/>
        <em>(Source: <a target="_blank" href="http://www.fao.org/docrep/008/a0200e/a0200e00.htm">Food Insecurity in the World</a>, FAO,&nbsp;2005)</em>
    </li>
</ul>

<p>These numbers are beyond comprehension, to a degree, because of their enormity. It&#8217;s difficult to fathom. But it&#8217;s happening, and you should <em>take it in</em>. This is the world you live in. Face it, accept it, and if, in these facts, you find the impetus to make a change, then great! Even a small change is a great change.</p>

<p>When one thinks of a child, in Western society, she has parents, and they love her, and they would die for her at an instant. They sacrifice years of freedom and financial security to bring her up in this world. This one child will receive so much love and devotion. To think of the absolute devastation this child&#8217;s death would bring an entire community is almost laughable in comparison to <strong><em>the absolute silence</em></strong> with which a child perishes in other parts of the world. It means nothing.</p>

<p>Don&#8217;t be a coward about it. It&#8217;s not too depressing to think about. If you can&#8217;t handle the reality of life and insist on living in a bubble of make-believe then fine, but know that the joy and pain that you&#8217;ll feel is probably nothing in comparison to both the suffering, ecstasy and bliss that can be felt if you leave the bubble.</p>

<p>Graham Nash said:</p>

<blockquote><p>
Life is not perfect, and it never will be, you just have to make the best of it and open your heart to what the world can show you. Sometimes it&#8217;s terrifying and sometimes it&#8217;s incredibly beautiful, and I&#8217;ll take both &#8212; thanks.
</p></blockquote>

<p>Don&#8217;t shy away from the world. It&#8217;s the real thing. Experience it. Love it. Improve it.</p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/general/the-absolute-silence/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss><!-- Dynamic Page Served (once) in 1.210 seconds --><!-- Cached page generated by WP-Super-Cache on 2012-02-06 07:29:47 -->

