<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	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/"
	>

<channel>
	<title>I does Javascript! &#187; Javascript basics</title>
	<atom:link href="http://blog.stchur.com/category/javascript-basics/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.stchur.com</link>
	<description>If you don&#039;t expect too much from me, you might not be let down.</description>
	<lastBuildDate>Tue, 03 Jan 2012 16:01:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Palindromes</title>
		<link>http://blog.stchur.com/2008/06/14/palindromes/</link>
		<comments>http://blog.stchur.com/2008/06/14/palindromes/#comments</comments>
		<pubDate>Sat, 14 Jun 2008 19:06:11 +0000</pubDate>
		<dc:creator>sstchur</dc:creator>
				<category><![CDATA[Computing]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Javascript basics]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Useful Functions]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[palindrome]]></category>

		<guid isPermaLink="false">http://blog.stchur.com/2008/06/14/palindromes/</guid>
		<description><![CDATA[The other evening while I was watching TV, I happened to have my laptop out, so I started dabbling around in Firebug just for the heck of it. I'll often just start writing functions for no particular reason, other than to refresh my skills or perhaps discover something about Javascript that I hadn't previously known. [...]]]></description>
			<content:encoded><![CDATA[	<p>The other evening while I was watching TV, I happened to have my laptop out, so I started dabbling around in Firebug just for the heck of it.  I'll often just start writing functions for no particular reason, other than to refresh my skills or perhaps discover something about Javascript that I hadn't previously known.</p>
	<p>So I was monkeying around, and I decided to write a function to determine if a string were a <a href = "http://en.wikipedia.org/wiki/Palindrome" title = "Wikipedia: Palindrome">palindrome</a>.  This is not a very difficult problem, but it might make for a descent introductory interview question (one of those questions you'd ask to rule out the truly inept).</p>
	<p>With problems like this, I'm mostly interested in two things:</p>
	<ol>
	<li>Writing the function in a clever way, so as to achieve the least amount of code possible</li>
	<li>Writing the function in the most efficient way possible</li>
	</ol>
	<p>Now, if it were Ruby, writing the clever solution (which might also happen to be the most efficient solution in that language -- not sure) would be ridiculously easy:</p>
	<div class="dean_ch" style="white-space: nowrap;"><span class="kw1">def</span> pal<span class="br0">&#40;</span>s<span class="br0">&#41;</span><br />
&nbsp; &nbsp;s == s.<span class="me1">reverse</span><br />
<span class="kw1">end</span></div>
	<p>That's so trivial, it's probably not even worth writing.</p>
	<p>But Javascript doesn't have a .reverse() method on strings, so you have to take an extra step (still pretty easy though):</p>
	<div class="dean_ch" style="white-space: nowrap;"><span class="kw2">function</span> pal<span class="br0">&#40;</span>s<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp;<span class="kw1">return</span> s === s.<span class="me1">split</span><span class="br0">&#40;</span><span class="st0">''</span><span class="br0">&#41;</span>.<span class="me1">reverse</span><span class="br0">&#40;</span><span class="br0">&#41;</span>.<span class="me1">join</span><span class="br0">&#40;</span><span class="st0">''</span><span class="br0">&#41;</span>;<br />
<span class="br0">&#125;</span></div>
	<p>Split the string into an array, reverse the array, and then join it back together.  Since this is all native Javascript stuff, it turns out to be reasonably fast, though one might expect you could do better.</p>
	<p>For grins and giggles, I decided to see how a manual solution, where I compare characters starting at each end of the string and work towards the middle, would compare:</p>
	<div class="dean_ch" style="white-space: nowrap;"><span class="kw2">function</span> pal<span class="br0">&#40;</span>s<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp;<span class="kw2">var</span> i, j,<br />
&nbsp; &nbsp;len = s.<span class="me1">length</span>,<br />
&nbsp; &nbsp;mid = Math.<span class="me1">floor</span><span class="br0">&#40;</span>len / <span class="nu0">2</span><span class="br0">&#41;</span>;</p>
	<p>&nbsp; &nbsp;<span class="kw1">for</span> <span class="br0">&#40;</span>i = <span class="nu0">0</span>, j = len - <span class="nu0">1</span>; i &lt; mid; i++, j--<span class="br0">&#41;</span><br />
&nbsp; &nbsp;<span class="br0">&#123;</span><br />
&nbsp; &nbsp;&nbsp; &nbsp;<span class="kw1">if</span> <span class="br0">&#40;</span>s.<span class="me1">charAt</span><span class="br0">&#40;</span>i<span class="br0">&#41;</span> !== s.<span class="me1">charAt</span><span class="br0">&#40;</span>j<span class="br0">&#41;</span><span class="br0">&#41;</span> <span class="kw1">return</span> <span class="kw2">false</span>;<br />
&nbsp; &nbsp;<span class="br0">&#125;</span><br />
&nbsp; &nbsp;<span class="kw1">return</span> <span class="kw2">true</span>;<br />
<span class="br0">&#125;</span></div>
	<p>This function will probably fail quickly, so that's good, but it also turns out to be generally faster than the split/reverse/join version.  It makes sense, since you're going through the string only one time and twice as fast as normal since you're traversing from both ends at the same time.</p>
	<p>Can you do even better though?  Maybe.  At least in Firefox you can, and quick tests seemed to confirm across other browsers too (but I didn't test extensively).</p>
	<p>What if we split the string in half, and only reverse half of it.  Then we can compare the first half with the original half:</p>
	<div class="dean_ch" style="white-space: nowrap;"><span class="kw2">function</span> pal<span class="br0">&#40;</span>s<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp;<span class="kw2">var</span> len = s.<span class="me1">length</span>,<br />
&nbsp; &nbsp;x = len / <span class="nu0">2</span>,<br />
&nbsp; &nbsp;y = x === Math.<span class="me1">floor</span><span class="br0">&#40;</span>x<span class="br0">&#41;</span> ? x : <span class="br0">&#40;</span>x = Math.<span class="me1">floor</span><span class="br0">&#40;</span>x<span class="br0">&#41;</span><span class="br0">&#41;</span> + <span class="nu0">1</span>;</p>
	<p>&nbsp; &nbsp;<span class="kw1">return</span> s.<span class="me1">substr</span><span class="br0">&#40;</span><span class="nu0">0</span>, x<span class="br0">&#41;</span>.<span class="me1">split</span><span class="br0">&#40;</span><span class="st0">''</span><span class="br0">&#41;</span>.<span class="me1">reverse</span><span class="br0">&#40;</span><span class="br0">&#41;</span>.<span class="me1">join</span><span class="br0">&#40;</span><span class="st0">''</span><span class="br0">&#41;</span> === s.<span class="me1">substr</span><span class="br0">&#40;</span>y,len<span class="br0">&#41;</span>;<br />
<span class="br0">&#125;</span></div>
	<p>The idea here is just split the string in half, reverse one of the two pieces and compare them.  For example:</p>
	<p>TOOT: splits into "TO" and "OT."  Reverse one of them, say the second part ("OT") and compare.</p>
	<p>If you've got a odd number of characters, you can ignore the middle most character:</p>
	<p>RACECAR: splits into "RAC" and "CAR" (ignore the "E" in the middle).  Reverse the second part ("CAR") and compare.</p>
	<p>As it turned out, this seemed to be faster than the other two methods.  Not by orders of magnitude, but not insignificantly either.  Here are the number from Firefox, running each function 10,000 time on the string "gohangasalamiimalasagnahog" (go hang a salami, i'm a lasagna hog).</p>
	<ul>
	<li>(Traverse from both ends): 797ms</li>
	<li>(Split/Reverse/Join): 969ms</li>
	<li>(Compare halves): 640ms</li>
	</ul>
	<p>Of course, numbers varied slightly during each run, but overall the they were consistent relative to each other.</p>
	<p>So there ya go.  Nothing in particular I wanted to point out here; just found it interesting and thought you might too.</p>
	<p>Think my code sucks?  Got a better solution?  Say so in the comments (you won't hurt my feelings).</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.stchur.com/2008/06/14/palindromes/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>IE quirk with onload event for &lt;img&gt; elements</title>
		<link>http://blog.stchur.com/2008/02/26/ie-quirk-with-onload-event-for-img-elements/</link>
		<comments>http://blog.stchur.com/2008/02/26/ie-quirk-with-onload-event-for-img-elements/#comments</comments>
		<pubDate>Tue, 26 Feb 2008 17:50:26 +0000</pubDate>
		<dc:creator>sstchur</dc:creator>
				<category><![CDATA[Beating IE into submission]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Gimme]]></category>
		<category><![CDATA[Javascript basics]]></category>

		<guid isPermaLink="false">http://blog.stchur.com/2008/02/26/ie-quirk-with-onload-event-for-img-elements/</guid>
		<description><![CDATA[I rediscovered something yesterday that I know I've come across in the past. Still, it was driving me crazy until I finally did a little web searching and found what I needed. It was one of those "oh right! I've encountered that before" moments. I was writing a script that dealt with images and I [...]]]></description>
			<content:encoded><![CDATA[	<p>I rediscovered something yesterday that I know I've come across in the past.  Still, it was driving me crazy until I finally did a little web searching and found what I needed.  It was one of those "oh right! I've encountered that before" moments.</p>
	<p>I was writing a script that dealt with images and I needed to know when an image had finished loading.  Simple enough.  Using Gimme (or your favorite addEvent(..)) equalizer the code looks something like:</p>
	<div class="dean_ch" style="white-space: nowrap;"><span class="kw2">var</span> myImage = document.<span class="me1">createElement</span><span class="br0">&#40;</span><span class="st0">'img'</span><span class="br0">&#41;</span>;<br />
myImage.<span class="me1">src</span> = <span class="st0">'http://source.to.image/image.jpg'</span>;<br />
g<span class="br0">&#40;</span>myImage<span class="br0">&#41;</span>.<span class="me1">addEvent</span><span class="br0">&#40;</span><span class="st0">'load'</span>, <span class="kw2">function</span><span class="br0">&#40;</span>e<span class="br0">&#41;</span> <span class="br0">&#123;</span> <span class="kw3">alert</span><span class="br0">&#40;</span><span class="st0">'Image is done loading!'</span><span class="br0">&#41;</span>; <span class="br0">&#125;</span><span class="br0">&#41;</span>;</div>
	<p>It turns out that my load handler wasn't always firing in IE (in Firefox it worked consistently). The solution though is super simple.</p>
	<p>You just need to make sure that you wire up the load handler <em>before</em> setting the image element's <code>.src</code> property.  Why?  Because if the image is being loaded from cache, IE (and Opera too) will load the image instantly.  In fact, it will have finished loading the image before your load event handler is even wired up, which means, it won't fire!</p>
	<p>Just change the code to something like this:</p>
	<div class="dean_ch" style="white-space: nowrap;"><span class="kw2">var</span> myImage = document.<span class="me1">createElement</span><span class="br0">&#40;</span><span class="st0">'img'</span><span class="br0">&#41;</span>;<br />
myImage.<span class="me1">addEvent</span><span class="br0">&#40;</span><span class="st0">'load'</span>, <span class="kw2">function</span><span class="br0">&#40;</span>e<span class="br0">&#41;</span> <span class="br0">&#123;</span> <span class="kw3">alert</span><span class="br0">&#40;</span><span class="st0">'Image is done loading!'</span><span class="br0">&#41;</span>; <span class="br0">&#125;</span><span class="br0">&#41;</span>;<br />
myImage.<span class="me1">src</span> = <span class="st0">'http://source.to.image/image.jpg'</span>;</div>
	<p>And there you have it.</p>
	<p>Nothing earth-shattering and probably common knowledge for a lot of scripters, but a little refresher never hurts.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.stchur.com/2008/02/26/ie-quirk-with-onload-event-for-img-elements/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Clean up after your event listeners</title>
		<link>http://blog.stchur.com/2007/09/06/clean-up-after-your-event-listeners/</link>
		<comments>http://blog.stchur.com/2007/09/06/clean-up-after-your-event-listeners/#comments</comments>
		<pubDate>Thu, 06 Sep 2007 06:01:02 +0000</pubDate>
		<dc:creator>sstchur</dc:creator>
				<category><![CDATA[Beating IE into submission]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Javascript basics]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://stchur.com/blog2/2007/09/06/clean-up-after-your-event-listeners/</guid>
		<description><![CDATA[Memory leaks in Javascript are, unfortunately, a very real problem. Of course, it seems to be a problem mostly in IE (try disabling all add-ons if you think you're seeing them in Firefox). While there are a number of ways that memory can be leaked, I find that one of the most significant (and most [...]]]></description>
			<content:encoded><![CDATA[	<p>Memory leaks in Javascript are, unfortunately, a very real problem. Of course, it seems to be a problem mostly in IE (try disabling all add-ons if you think you're seeing them in Firefox).  While there are a number of ways that memory can be leaked, I find that one of the most significant (and most frequent) causes is failing to remove event handlers.</p>
	<div class = "note">
	<p><em>Important Update:</em>  I failed to mention when I originally wrote this post, that you should use caution with this 'unload' technique.  If you are manually unhooking events throughout the life of your web-app (or taking care to manually unhook them on 'unload'), then you might potentially be adding multiple (and unnecessary) 'unload' handlers to the browser.</p>
	<p>This might not seem like a big deal, but in a large and complex app it can actually <em>increase</em> memory consumption dramatically, thereby negating any gain you'd have gotten from the technique!</p>
	</div>
	<h3>Auto Detach with 'unload'</h3>
	<p>In IE, if you wire up an event listener and fail to remove that listener when your page unloads, you're probably asking for a leak. One effective technique to ensure that listeners get removed is to wire up an 'unload' event to the window which detaches the listener for you.  For example:</p>
	<div class="dean_ch" style="white-space: nowrap;"><span class="kw2">var</span> elem = document.<span class="me1">getElementById</span><span class="br0">&#40;</span><span class="st0">'someElem'</span><span class="br0">&#41;</span>;<br />
elem.<span class="me1">attachEvent</span><span class="br0">&#40;</span><span class="st0">'onclick'</span>, elemClick<span class="br0">&#41;</span>;<br />
window.<span class="me1">attachEvent</span><span class="br0">&#40;</span><span class="st0">'onunload'</span>, <span class="kw2">function</span><span class="br0">&#40;</span>e<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp;elem.<span class="me1">detachEvent</span><span class="br0">&#40;</span><span class="st0">'onclick'</span>, elemClick<span class="br0">&#41;</span>;<br />
<span class="br0">&#125;</span><span class="br0">&#41;</span>;</div>
	<p>Keen readers might have noticed that I solved one problem (removing the 'click' listener from <code>elem</code>) by creating another one (attaching a new, anonymous listener to the windows's 'unload' event).</p>
	<h3>Why is this a problem?</h3>
	<p>In a <a href = "http://ecmascript.stchur.com/2007/01/02/anonymous-function-quick-tips/">previous blog entry</a>, I mentioned that it wasn't possible to remove an event listener if that listener were anonymous, as in:</p>
	<div class="dean_ch" style="white-space: nowrap;"><span class="co1">// IE specific code</span><br />
<span class="kw2">var</span> elem = document.<span class="me1">getElementById</span><span class="br0">&#40;</span><span class="st0">'someElem'</span><span class="br0">&#41;</span>;<br />
elem.<span class="me1">attachEvent</span><span class="br0">&#40;</span><span class="st0">'onclick'</span>, <span class="kw2">function</span><span class="br0">&#40;</span>e<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp;<span class="kw3">alert</span><span class="br0">&#40;</span><span class="st0">'you clicked it!'</span><span class="br0">&#41;</span>;<br />
<span class="br0">&#125;</span><span class="br0">&#41;</span>;</p>
	<p>elem.<span class="me1">detachEvent</span><span class="br0">&#40;</span><span class="st0">'onclick'</span>, <span class="kw2">function</span><span class="br0">&#40;</span>e<span class="br0">&#41;</span>&nbsp; &nbsp;&nbsp; &nbsp;<span class="co1">// WON'T WORK!</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp;<span class="kw3">alert</span><span class="br0">&#40;</span><span class="st0">'you clicked it!'</span><span class="br0">&#41;</span>;<br />
<span class="br0">&#125;</span><span class="br0">&#41;</span>;</div>
	<p>While it's true that the above code won't work, it's not <em>entirely</em> true to say that it's impossible to remove an anonymous listener. Why?  Because every function actually has a reference to itself through its own <code>arguments</code> object.  Specifically, through the <code>.callee</code> property of the <code>arguments</code> object.</p>
	<p>We can use this to our advantage to detach the anonymous 'unload' listener from <em>within</em> the listener itself.</p>
	<div class="dean_ch" style="white-space: nowrap;"><span class="kw2">var</span> elem = document.<span class="me1">getElementById</span><span class="br0">&#40;</span><span class="st0">'someElem'</span><span class="br0">&#41;</span>;<br />
elem.<span class="me1">attachEvent</span><span class="br0">&#40;</span><span class="st0">'onclick'</span>, elemClick<span class="br0">&#41;</span>;<br />
window.<span class="me1">attachEvent</span><span class="br0">&#40;</span><span class="st0">'onunload'</span>, <span class="kw2">function</span><span class="br0">&#40;</span>e<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp;elem.<span class="me1">detachEvent</span><span class="br0">&#40;</span><span class="st0">'onclick'</span>, elemClick<span class="br0">&#41;</span>;<br />
&nbsp; &nbsp;window.<span class="me1">detachEvent</span><span class="br0">&#40;</span><span class="st0">'onunload'</span>, arguments.<span class="me1">callee</span><span class="br0">&#41;</span>;&nbsp; &nbsp; &nbsp;<span class="co1">// detach this anonymous listener</span><br />
<span class="br0">&#125;</span><span class="br0">&#41;</span>;</div>
	<h3>Why not just un-anonymize?</h3>
	<p>You certainly could just name all of your functions and then refer to them by name, but sometimes anonymous functions are very useful since they allow to create closures and do other nifty Javascript tricks.  In those cases where it's desirable to use an anonymous function, this technique might be just the ticket!</p>
	<h3>Conclusion</h3>
	<p>I've conveniently (for me anyway) left out any non IE-specific code in this post.  It's worth nothing that I don't generally use this technique except in IE, which means a little cross browser code is in order to ensure that this 'onunload' technique is only used for that browser.</p>
	<p>Of course, it isn't going to hurt anything for other browsers (and it might even help) so there'd be no harm is using it across the board, bu you'll still need to write some cross-browser code (obviously).  I'll leave that as an exercise for the reader though.</p>
	<p>Happy scripting.</p>
	<p>Comments welcome.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.stchur.com/2007/09/06/clean-up-after-your-event-listeners/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>IE innerHTML Memory Leak</title>
		<link>http://blog.stchur.com/2007/05/16/ie-innerhtml-memory-leak/</link>
		<comments>http://blog.stchur.com/2007/05/16/ie-innerhtml-memory-leak/#comments</comments>
		<pubDate>Wed, 16 May 2007 16:04:11 +0000</pubDate>
		<dc:creator>sstchur</dc:creator>
				<category><![CDATA[Beating IE into submission]]></category>
		<category><![CDATA[Javascript basics]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://stchur.com/blog2/2007/05/16/ie-innerhtml-memory-leak/</guid>
		<description><![CDATA[Kristoffer Henriksson has got to be one of the most intelligent people I know. His ability to write, test, and debug code is second the none. Heck, I wouldn't be surprised if the guy can read and write machine code as if it were English. Recently, Kristoffer did a significant amount of investigation to track [...]]]></description>
			<content:encoded><![CDATA[	<p><a href = "http://blogs.msdn.com/Kristoffer">Kristoffer Henriksson</a> has got to be one of <em>the</em> most intelligent people I know.  His ability to write, test, and debug code is second the none.  Heck, I wouldn't be surprised if the guy can read and write machine code as if it were English.</p>
	<p>Recently, Kristoffer did a significant amount of investigation to track down a nasty IE memory leak issue.  IE's problems with memory leaks are well known, but most of the time, you'll hear people saying things like "closures are the cause of memory leaks," or "failing to detach events is what causes memory leaks," and (probably the most common), "circular references are the culprit -- they cause memory leaks."</p>
	<p>To some degree, all of these things are true.  Closures can sometimes lead to memory leaks, failing to detach events can also lead to memory leaks, and yes, circular references to DOM elements can also be the cause of memory leaks.</p>
	<p>One kind of leak that seems to get a little less attention though, is the one involving <code>.innerHTML</code>.  Fortunately (thanks to Kristoffer's investigation) this one is pretty easy to deal with.</p>
	<p>Before we can deal with the leak, we need to understand what causes it.  Three conditions are required:</p>
	<ol>
	<li>A orphaned DOM element must exist in memory.</li>
	<li>That element's innerHTML must be set to a string of markup the creates an element with some DOM 0 event wired up.</li>
	<li>The aforementioned innerHTML property must be set <em>before</em> the orphaned DOM element is "unorphaned" (added to the page).</li>
	</ol>
	<p>If these conditions are met, get ready to call the (Javascript) plumber, because you've got a leak!</p>
	<p>To make things a little less abstract, I'll write some code and explain piece by piece, how it fits the conditions above:</p>
	<div class="dean_ch" style="white-space: nowrap;">
<span class="co1">// 1. &nbsp;An orphaned DOM element must exist in memory.</span><br />
<span class="kw2">var</span> elem = document.<span class="me1">createElement</span><span class="br0">&#40;</span><span class="st0">'div'</span><span class="br0">&#41;</span>;<br />
<span class="co1">// poor elem is just floating around in the page's memory without a parentNode</span></p>
	<p><span class="co1">// 2. &nbsp;elem's innerHTML must be set to a string of markup that creates an element with some DOM 0 event wired up.</span><br />
elem.<span class="me1">innerHTML</span> = <span class="st0">'&lt;a onclick = &quot;testFn()&quot;&gt;Test Link&lt;/a&gt;'</span>;<br />
<span class="co1">// elem contains an &lt;a&gt; tag with an onclick event</span></p>
	<p><span class="co1">// 3. &nbsp;elem is now added to the page, &lt;em&gt;after&lt;/em&gt; innerHTML has already been set.</span><br />
document.<span class="me1">body</span>.<span class="me1">appendChild</span><span class="br0">&#40;</span>elem<span class="br0">&#41;</span><br />
<span class="co1">// elem (and its child &lt;a&gt; tag) is now part of the page (remember, that innerHTML has already been set)</span></div>
	<p>As you can see, the code above is not at all an uncommon scenario.  Chances are though, if that's all you've got, you won't notice much of leak.  This issue really only manifests itself when multiplied, that is, when you set <code>.innerHTML</code> in the above manner over and over and over again on the same page.</p>
	<p>Why would ever do this?  Think Web 2.0, think AJAX, think dynamic page updates and you probably won't have to search too hard to find a situation where someone might do this.  Maybe you already know of (or helped write) a Web 2.0 app that does this.</p>
	<h3>Memory Leak Demo Page</h3>
	<p>Anyway, when above pattern <em>is</em> multiplied (whatever the reason) memory leaking chaos will ensue.  To illustrate the problem, I've put together a sample page  with a script that creates a orphaned &lt;div&gt; element, whose <code>.innerHTML</code> is set to a string of 2000 &lt;a&gt; tags with onclick events.  When you click the "Start Leak" button, the script executes repeatedly, until you click the "Stop Leak" button.  This give you a chance to use Perfmon to monitor memory consumption and see the results of the leak. The memory leak demo page can be found <a href = "http://ecmascript.stchur.com/blogcode/ie_innerhtml_memleak/leak.html">here</a>.</p>
	<h3>The solution</h3>
	<p>It turns out, the solution is actually pretty easy:  simply make sure to set <code>.innerHTML</code> <em>after</em> appending the DOM element to the page.  That's it!</p>
	<div class="dean_ch" style="white-space: nowrap;">
<span class="co1">// create the element in memory</span><br />
<span class="kw2">var</span> elem = document.<span class="me1">createElement</span><span class="br0">&#40;</span><span class="st0">'div'</span><span class="br0">&#41;</span>;</p>
	<p><span class="co1">// add it to the page before setting .innerHTML</span><br />
document.<span class="me1">body</span>.<span class="me1">appendChild</span><span class="br0">&#40;</span>elem<span class="br0">&#41;</span></p>
	<p><span class="co1">// now it's safe to set .innerHTML</span><br />
elem.<span class="me1">innerHTML</span> = <span class="st0">'&lt;a onclick = &quot;testFn()&quot;&gt;Test Link&lt;/a&gt;'</span>;</div>
	<div class = "note">
Of course there are other solutions, one of which is to avoid using <code>.innerHTML</code> at all.  As a general best practice, I encourage this (for a number of reasons that I don't have time to get into here), but I recognize that that suggestion may not also be desirable, or practical.
</div>
	<p>To see that this really does take care of the issue, I've put together another <a href = "http://ecmascript.stchur.com/blogcode/ie_innerhtml_memleak/noleak.html">test page</a>.  In this one, the <code>.innerHTML</code> property is only set <em>after</em> the DOM element has been added to the page.</p>
	<p>If you click the "Start Leak" button on each page and let it run for about 60 seconds or so, you should notice that the first page continues to consume more and more memory as time goes on, whereas the second page's memory consumptions remains relatively constant.</p>
	<h3>Demo Links</h3>
	<p>In case you're the kind of person who doesn't like to read paragraphs to find embedded links (I'm like that), here are the links to the two demo pages, for your convenicne:</p>
	<ul>
	<li><a href = "http://ecmascript.stchur.com/blogcode/ie_innerhtml_memleak/leak.html">Leak Demo</a></li>
	<li><a href = "http://ecmascript.stchur.com/blogcode/ie_innerhtml_memleak/noleak.html">No Leak Demo</a></li>
	</ul>
	<p>So there ya go: a nasty bug, but thanks to Kristoffer's work tracking tracking down the exact causes of this leak, a fairly easy one to handle.</p>
	<p>Comments welcome.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.stchur.com/2007/05/16/ie-innerhtml-memory-leak/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>null &#8211; 15 = -15?  Apparently, yes.</title>
		<link>http://blog.stchur.com/2007/05/09/null-15-15-apparently-yes/</link>
		<comments>http://blog.stchur.com/2007/05/09/null-15-15-apparently-yes/#comments</comments>
		<pubDate>Wed, 09 May 2007 18:46:05 +0000</pubDate>
		<dc:creator>sstchur</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Javascript basics]]></category>

		<guid isPermaLink="false">http://stchur.com/blog2/2007/05/09/null-15-15-apparently-yes/</guid>
		<description><![CDATA[So I discovered that null isn't not a number. Interestingly, it's also not of type "number" (its type is "object"). But it sure acts like a number when used in numerical expressions, which is why it's not not a number, even though it's not actually a number. Honestly. I'm not just writing gibberish here. See [...]]]></description>
			<content:encoded><![CDATA[	<p>So I discovered that <code>null</code> isn't not a number.  Interestingly, it's also not of type "number" (its type is "object").  But it sure acts like a number when used in numerical expressions, which is why it's not not a number, even though it's not actually a number.  Honestly.  I'm not just writing gibberish here.  See for yourself:</p>
	<div class="dean_ch" style="white-space: nowrap;">
<span class="kw3">alert</span><span class="br0">&#40;</span><span class="kw1">typeof</span> <span class="kw2">null</span><span class="br0">&#41;</span>; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="co1">// object</span><br />
<span class="kw3">alert</span><span class="br0">&#40;</span><span class="kw1">typeof</span> <span class="kw2">null</span> === <span class="st0">'number'</span><span class="br0">&#41;</span>; &nbsp; &nbsp; &nbsp; &nbsp;<span class="co1">// false</span><br />
<span class="kw3">alert</span><span class="br0">&#40;</span>isNaN<span class="br0">&#40;</span><span class="kw2">null</span><span class="br0">&#41;</span><span class="br0">&#41;</span>; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="co1">// false</span></p>
	<p><span class="kw2">var</span> x = <span class="kw2">null</span> - <span class="nu0">15</span>;<br />
<span class="kw3">alert</span><span class="br0">&#40;</span>x<span class="br0">&#41;</span>; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="co1">// -15</span></div>
	<p><span id="more-43"></span></p>
	<p>It appears then, that <code>null</code> is interpreted as zero when used in mathematical expressions, which I guess isn't totally illogical (but certainly not what I expected).</p>
	<div class="dean_ch" style="white-space: nowrap;">
<span class="kw2">var</span> y = <span class="kw2">null</span> + <span class="nu0">25</span> * <span class="nu0">4</span>;<br />
<span class="kw3">alert</span><span class="br0">&#40;</span>y<span class="br0">&#41;</span>; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="co1">// 100</span></div>
	<p>A tad more digging and I found (not surprisingly) that this phenomenon is not limited to <code>null</code>.  Turns out that many (but not all) "false-like" values are interpreted as zero in mathematical expressions (<code>NaN</code> and <code>undefined</code> being the two exceptions that I noticed):</p>
	<div class="dean_ch" style="white-space: nowrap;">
<span class="kw3">alert</span><span class="br0">&#40;</span><span class="kw2">null</span> * <span class="nu0">50</span><span class="br0">&#41;</span>; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="co1">// 0</span><br />
<span class="kw3">alert</span><span class="br0">&#40;</span><span class="st0">&quot;&quot;</span> + <span class="nu0">25</span> * <span class="nu0">4</span><span class="br0">&#41;</span>; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="co1">// 100</span><br />
<span class="kw3">alert</span><span class="br0">&#40;</span><span class="kw2">false</span> - <span class="nu0">10</span> * <span class="nu0">2</span><span class="br0">&#41;</span>; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span class="co1">// -20</span><br />
<span class="kw3">alert</span><span class="br0">&#40;</span>undefined - <span class="nu0">100</span><span class="br0">&#41;</span>; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="co1">// NaN</span><br />
<span class="kw3">alert</span><span class="br0">&#40;</span>NaN + <span class="nu0">25</span><span class="br0">&#41;</span>; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span class="co1">// NaN</span></div>
	<p>It's also good to be aware that <code>NaN</code> is "toxic", meaning that the result of a mathematical expression will gravitate towards <code>NaN</code> if it shows up <em>anywhere</em> in the expression, directly (as in the last example above) or indirectly (as in the last two examples shown below):</p>
	<div class="dean_ch" style="white-space: nowrap;">
<span class="kw3">alert</span><span class="br0">&#40;</span><span class="kw2">null</span> + <span class="nu0">50</span><span class="br0">&#41;</span>; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="co1">// 50, no problem</span><br />
<span class="kw3">alert</span><span class="br0">&#40;</span><span class="nu0">50</span> - <span class="st0">'steve'</span><span class="br0">&#41;</span>; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span class="co1">// NaN</span><br />
<span class="kw3">alert</span><span class="br0">&#40;</span><span class="kw2">null</span> + <span class="nu0">50</span> - <span class="st0">'steve'</span><span class="br0">&#41;</span>; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span class="co1">// NaN</span></div>
	<h2>What it means for you</h2>
	<p>Nothing earth-shattering really -- just that you should be careful if you're using <code>isNaN(..)</code> to find out if something is numeric or not.  One thing you can do that (I think) is fool proof is first call <code>parseInt(..)</code> on the value in question and <em>then</em> call <code>isNaN(..)</code> as in:</p>
	<div class="dean_ch" style="white-space: nowrap;">
<span class="kw3">alert</span><span class="br0">&#40;</span>isNaN<span class="br0">&#40;</span>parseInt<span class="br0">&#40;</span><span class="kw2">null</span><span class="br0">&#41;</span><span class="br0">&#41;</span>; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span class="co1">// true</span></div>
	<p>This works because <code>parseInt(..)</code> of <code>null</code> is <code>NaN</code>, which of course, will return true when using with <code>isNaN(..)</code>.</p>
	<p>That's it.  Nothing ground-breaking; just something good to keep in the back of your mind so that you spend a few less minutes scratching your head next time your run into it.</p>
	<p>Comment welcome.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.stchur.com/2007/05/09/null-15-15-apparently-yes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Optimize your Javascript cross-browser code through branching</title>
		<link>http://blog.stchur.com/2007/04/26/optimize-your-javascript-cross-browser-code-through-branching/</link>
		<comments>http://blog.stchur.com/2007/04/26/optimize-your-javascript-cross-browser-code-through-branching/#comments</comments>
		<pubDate>Thu, 26 Apr 2007 17:24:20 +0000</pubDate>
		<dc:creator>sstchur</dc:creator>
				<category><![CDATA[Cross-Browser]]></category>
		<category><![CDATA[Javascript basics]]></category>

		<guid isPermaLink="false">http://stchur.com/blog2/2007/04/26/optimize-your-javascript-cross-browser-code-through-branching/</guid>
		<description><![CDATA[Dustin Diaz recently published an article outlining seven Javascript techniques that you'd be wise to start using in your scripts. It's a well written article and you should definitely give it read if you haven't already. Whether you're just beginning with Javascript or you consider yourself an expert, Dustin's article surely has something for you. [...]]]></description>
			<content:encoded><![CDATA[	<p><a href = "http://www.dustindiaz.com">Dustin Diaz</a> recently published <a href = "http://www.digital-web.com/articles/seven_javascript_techniques/">an article</a> outlining seven Javascript techniques that you'd be wise to start using in your scripts.  It's a well written article and you should definitely give it read if you haven't already.  Whether you're just beginning with Javascript or you consider yourself an expert, Dustin's article surely has something for you.</p>
	<p>One concept he writes about that I particularly like is that of "branching."  I've never actually heard it called that before, but it's a very sound concept and one that I doubt is being utilized often enough by today's Javascripters.</p>
	<p><span id="more-42"></span></p>
	<h3>What is branching?</h3>
	<p>Put simply, branching (in Javascript) is the use of closures to get the browser to interpret a block of code only one time, when otherwise, it would interpret that block over and over and over again (presumably, each time you call your function).</p>
	<p>Why would you want to do this?  Because, when it comes to cross-browser code, chances are you have a lot object detection code whose primary purpose is to determine if the browser supports a particular feature/property, like this:</p>
	<div class="dean_ch" style="white-space: nowrap;">
<span class="kw2">function</span> addEvent<span class="br0">&#40;</span>el, evt, fn<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp;<span class="kw1">if</span> <span class="br0">&#40;</span><span class="kw1">typeof</span> elem.<span class="me1">addEventListener</span> !== <span class="st0">'undefined'</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp;<span class="br0">&#123;</span><br />
&nbsp; &nbsp;&nbsp; &nbsp;<span class="co1">// w3c event wire up here</span><br />
&nbsp; &nbsp;<span class="br0">&#125;</span><br />
&nbsp; &nbsp;<span class="kw1">else</span> <span class="kw1">if</span> <span class="br0">&#40;</span><span class="kw1">typeof</span> elem.<span class="me1">attachEvent</span> !== <span class="st0">'undefined'</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp;<span class="br0">&#123;</span><br />
&nbsp;&nbsp; &nbsp; &nbsp;<span class="co1">// ie event wire up here...</span><br />
&nbsp; &nbsp;<span class="br0">&#125;</span><br />
<span class="br0">&#125;</span></div>
	<p>The above is a very simplified version of a cross-browser <code>addEvent(..)</code> function that takes care of (some of) the differences in event models between IE and W3C browsers.  This is all well and good, but consider what happens when I do the following:</p>
	<div class="dean_ch" style="white-space: nowrap;">
<span class="kw2">var</span> elems = document.<span class="me1">getElementsByTagName</span><span class="br0">&#40;</span><span class="st0">'div'</span><span class="br0">&#41;</span>; &nbsp; &nbsp; <span class="co1">// assume 5000 &lt;div&gt; elements returned</span><br />
<span class="kw2">var</span> i, len = elems.<span class="me1">length</span>;<br />
<span class="kw1">for</span> <span class="br0">&#40;</span>i = <span class="nu0">0</span>; i &lt; len; i++<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp;addEvent<span class="br0">&#40;</span>elems<span class="br0">&#91;</span>i<span class="br0">&#93;</span>, <span class="st0">'click'</span>, <span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span> <span class="kw3">alert</span><span class="br0">&#40;</span><span class="st0">'Hi there!'</span><span class="br0">&#41;</span>; <span class="br0">&#125;</span><span class="br0">&#41;</span>;<br />
<span class="br0">&#125;</span></div>
	<p>Five thousand times the browser is checking: <code>if (typeof elem.addEventListener !== 'undefined')...</code> -- once for each element in the <code>elems</code> array!  Gosh, that feels like a waste, doesn't it?  Wouldn't it be good if we could somehow tell the browser: <q class = "shout">Hey browser, once you've figured out that .addEventListener(..) is supported, don't bother checking again for the next 4999 iterations!</q>?</p>
	<p>It turns out you <em>can</em> achieve something like this, through the use of branching.</p>
	<h3>Branching in action</h3>
	<p>In a sense, branching is a lot like conditional compilation.  Similarly to the way you can use #ifdef directives to instruct your C-style programs to conditionally compile certain blocks of code into your executable, branching allows you to conditionally "compile" (as it were) certain blocks of code into your Javascript.</p>
	<p>This is accomplished by creating separate functions that contain your cross-browser logic and then wrapping them up inside of another function, which will return the appropriate function when executed.  The nifty part though, is that this outer function will only be executed <em>one time</em> (that's the sort of "conditional compilation" part).</p>
	<p>An example should help illustrate this:</p>
	<div class="dean_ch" style="white-space: nowrap;">
<span class="kw2">var</span> addEvent = <span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp;<span class="kw2">function</span> ie_addEvent<span class="br0">&#40;</span>el, evt, fn<span class="br0">&#41;</span><br />
&nbsp; &nbsp;<span class="br0">&#123;</span><br />
&nbsp; &nbsp;&nbsp; &nbsp;el.<span class="me1">attachEvent</span><span class="br0">&#40;</span><span class="st0">'on'</span> + evt, fn<span class="br0">&#41;</span>;<br />
&nbsp; &nbsp;<span class="br0">&#125;</span></p>
	<p>&nbsp; &nbsp;<span class="kw2">function</span> w3c_addEvent<span class="br0">&#40;</span>el, evt, fn, useCap<span class="br0">&#41;</span><br />
&nbsp; &nbsp;<span class="br0">&#123;</span><br />
&nbsp; &nbsp;&nbsp; &nbsp;el.<span class="me1">addEventListener</span><span class="br0">&#40;</span>evt, fn, useCap<span class="br0">&#41;</span>;<br />
&nbsp; &nbsp;<span class="br0">&#125;</span></p>
	<p>&nbsp; &nbsp;<span class="kw1">if</span> <span class="br0">&#40;</span><span class="kw1">typeof</span> window.<span class="me1">addEventListener</span> !== <span class="st0">'undefined'</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp;<span class="br0">&#123;</span><br />
&nbsp; &nbsp;&nbsp; &nbsp;<span class="kw1">return</span> w3c_addEvent;<br />
&nbsp; &nbsp;<span class="br0">&#125;</span><br />
&nbsp; &nbsp;<span class="kw1">else</span> <span class="kw1">if</span> <span class="br0">&#40;</span><span class="kw1">typeof</span> window.<span class="me1">attachEvent</span> !== <span class="st0">'undefined'</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp;<span class="br0">&#123;</span><br />
&nbsp; &nbsp;&nbsp; &nbsp;<span class="kw1">return</span> ie_addEvent;<br />
&nbsp; &nbsp;<span class="br0">&#125;</span><br />
<span class="br0">&#125;</span><span class="br0">&#40;</span><span class="br0">&#41;</span>; &nbsp; <span class="co1">// &lt;= This is the critical part!</span></div>
	<p>In the preceding example, I've separated out the logic for IE and W3C browsers into two separate functions.  Those functions have been declared within the scope of the <code>addEvent()</code>, so they're not accessible from outside.</p>
	<p>The most critical thing to notice though, is the use of <code>}();</code> at the very end of the code.  It's important to realize what's happening here.  We're declaring a function, <code>addEvent</code>, with the code: <code>var addEvent = function() {</code>, and then we're immediately executing that function at the end of its declaration with <code>}();</code>.</p>
	<h3>What it means for you</h3>
	<p>This means that as the Javascript interpreter is parsing your code, it will execute the <code>addEvent()</code> function right away, whose logic instructs the browser return one of two functions (but not both)!</p>
	<p>The net effect of this is that <code>addEvent</code> will be equal to <code>ie_addEvent</code> when IE is being used, and it will be equal to <code>w3c_addEvent</code> when W3C browsers are being used.  In either case, the browser only needed to execute the if-conditional one time.  Beautiful!</p>
	<p>You can prove to yourself that this works, but simply executing: <code>alert(addEvent.toString())</code> in both IE and in a W3C browser.  Notice that you'll get the proper function for each browser, but that neither function includes any <code>if (typeof blah_blah_blah)...</code> checks.</p>
	<h3>Conclusion</h3>
	<p>It's no surprise that this is going to be <em>much</em> more efficient than the original <code>addEvent(..)</code> function, which did not utilize branching.  After all, it's 4,999 fewer <code>if (typeof ...)</code> checks for the browser to execute!</p>
	<p>This concept isn't necessarily limited to cross-browser code either.  Branching can be useful in lots of situations.  As always, I'd recommend analyzing <em>your particular</em> situation and determining if branching is going to beneficial for you (chances are, it will).</p>
	<p>If you haven't already, be sure to check out <a href = "http://www.digital-web.com/articles/seven_javascript_techniques/">Dustin's article</a>.  Besides branching, he covers six other useful techniques that every Javascripter should be aware of.</p>
	<p>Comments welcome.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.stchur.com/2007/04/26/optimize-your-javascript-cross-browser-code-through-branching/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>.split(..) broken in IE</title>
		<link>http://blog.stchur.com/2007/03/28/split-broken-in-ie/</link>
		<comments>http://blog.stchur.com/2007/03/28/split-broken-in-ie/#comments</comments>
		<pubDate>Wed, 28 Mar 2007 03:40:40 +0000</pubDate>
		<dc:creator>sstchur</dc:creator>
				<category><![CDATA[Beating IE into submission]]></category>
		<category><![CDATA[Cross-Browser]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Javascript basics]]></category>
		<category><![CDATA[Useful Functions]]></category>

		<guid isPermaLink="false">http://stchur.com/blog2/2007/03/28/split-broken-in-ie/</guid>
		<description><![CDATA[I discovered last weekend, something about IE which I had previously never known (probably because I use Firefox/Firebug to write and test most of my Javascript). It turns out that the implementation of .split(..) is broken in IE (for more complex cases). If you stick with the simpler cases when using this function, then you [...]]]></description>
			<content:encoded><![CDATA[	<p>I discovered last weekend, something about IE which I had previously never known (probably because I use Firefox/Firebug to write and test most of my Javascript).  It turns out that the implementation of <code>.split(..)</code> is broken in IE (for more complex cases).  If you stick with the simpler cases when using this function, then you probably won't have ever noticed this.  For example, the following works just fine:</p>
	<div class="dean_ch" style="white-space: nowrap;"><span class="kw2">var</span> s = <span class="st0">'This-is-a-hyphen-delimited-string'</span>;<br />
<span class="kw2">var</span> split = s.<span class="me1">split</span><span class="br0">&#40;</span><span class="st0">'-'</span><span class="br0">&#41;</span>;&nbsp; <span class="co1">// returns &nbsp;['This', 'is', 'a', 'hyphen', 'delimited', 'string']</span></div>
	<p>The above code will work in just about every browser under the sun, including IE, but of course, it's the simplest case scenario for the <code>.split(..)</code> function.  Many programmers will probably be aware that you're not limited to passing in a string; you can also pass in a regular expression, which IE (mostly) supports, but this is where things can start to fall apart on you (in IE anyway).</p>
	<p>Read on to learn more.</p>
	<p><span id="more-33"></span></p>
	<p>The <code>.split(..)</code> function is pretty robust.  You can pass in a simple string, which indicates what character (or characters) you want to use use as a delimiter, or you can pass in a regular expression instead of a string.  Take the following example:</p>
	<div class="dean_ch" style="white-space: nowrap;">
<span class="kw2">var</span> s = <span class="st0">'My~Silly.Test-String'</span>;<br />
<span class="kw2">var</span> split = s.<span class="me1">split</span><span class="br0">&#40;</span><span class="re0">/~|\.|-/</span><span class="br0">&#41;</span>;&nbsp; &nbsp;<span class="co1">// returns [ 'My', 'Silly', 'Test', 'String' ]</span></div>
	<p>In the above example, the string, <code>s</code> will be split by any of the characters: <code>"~", ".", or "-"</code>.  The regular expression makes this really easy to do.  But one thing you'll notice is that the delimiters themselves are not captured.  This might not be a problem for you; in fact, you might not <em>want</em> the delimiters captured, in which case no problem.  But suppose you do.  Suppose you want the result of your split to be:</p>
	<div class="dean_ch" style="white-space: nowrap;"><span class="br0">&#91;</span> <span class="st0">'My'</span>, <span class="st0">'~'</span>, <span class="st0">'Silly'</span>, <span class="st0">'.'</span>, <span class="st0">'Test'</span>, <span class="st0">'-'</span>, <span class="st0">'String'</span> <span class="br0">&#93;</span></div>
	<p>In that case, you need to modify your regular expression, and unfortunatly, the needed modification isn't going to work in IE.  Here's how's you'd accomplish it in most other browsers (it's remarkably easy).</p>
	<div class="dean_ch" style="white-space: nowrap;">
<span class="kw2">var</span> s = <span class="st0">'My~Silly.Test-String'</span>;<br />
<span class="kw2">var</span> split = s.<span class="me1">split</span><span class="br0">&#40;</span><span class="re0">/<span class="br0">&#40;</span>~|\.|-/</span><span class="br0">&#41;</span><span class="br0">&#41;</span>;&nbsp;<span class="co1">// returns ['My', '~', 'Silly', '.', 'Test', '-', 'String']</span></div>
	<p>You'll notice (or maybe not, since the change was so minor) that I didn't have to do much to get the desired result.  All that was needed was wrapping the contents of my regular expression in parenthesis, thus indicating a <a href = "http://en.wikipedia.org/wiki/Regular_expression">regular expression grouping</a>.</p>
	<p>Unfortunately, in IE's implementation of <code>.split(..)</code>, it completely ignores the grouping request.  So while your result will still be an array split by the requested delimiters, those delimiters won't be included in the array!</p>
	<p>So, what do we do when IE won't cooperate with with us?  Why, we beat it into submission of course, and here's how.</p>
	<h3>The .xSplit(..) function</h3>
	<p>I call it <code>xSplit(..)</code> because it's a sort of "eXtended" version of the native <code>.split(..)</code> function.  Anytime I'm writing/enhancing a version of a function that already exists, I like to use the "x" to help my eyes quickly distinguish between the preferred native function and my own custom implementation (actually, I don't really do that; I just made that up now, but it seems like a reasonable idea, so maybe I'll start!).</p>
	<p>The <code>xSplit(..)</code> function will work more or less like the native function, with just one small difference:  it will only accept regular expressions.  Strings won't be accepted; the native <code>.split(..)</code> function for that.</p>
	<p>Here is the full code, with an explanation to follow.</p>
	<div class="dean_ch" style="white-space: nowrap;">
String.<span class="me1">prototype</span>.<span class="me1">xSplit</span> = <span class="kw2">function</span><span class="br0">&#40;</span>_regEx<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp;<span class="co1">// Most browsers can do this properly, so let them -- they'll do it faster</span><br />
&nbsp; &nbsp;<span class="kw1">if</span> <span class="br0">&#40;</span><span class="st0">'a~b'</span>.<span class="me1">split</span><span class="br0">&#40;</span><span class="re0">/<span class="br0">&#40;</span>~<span class="br0">&#41;</span>/</span><span class="br0">&#41;</span>.<span class="me1">length</span> === <span class="nu0">3</span><span class="br0">&#41;</span> <span class="br0">&#123;</span> <span class="kw1">return</span> <span class="kw1">this</span>.<span class="me1">split</span><span class="br0">&#40;</span>_regEx<span class="br0">&#41;</span>; <span class="br0">&#125;</span></p>
	<p>&nbsp; &nbsp;<span class="kw1">if</span> <span class="br0">&#40;</span>!_regEx.<span class="me1">global</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp;&nbsp; &nbsp;<span class="br0">&#123;</span> _regEx = <span class="kw2">new</span> RegExp<span class="br0">&#40;</span>_regEx.<span class="me1">source</span>, <span class="st0">'g'</span> + <span class="br0">&#40;</span>_regEx.<span class="me1">ignoreCase</span> ? <span class="st0">'i'</span> : <span class="st0">''</span><span class="br0">&#41;</span><span class="br0">&#41;</span>; <span class="br0">&#125;</span></p>
	<p>&nbsp; &nbsp;<span class="co1">// IE (and any other browser that can't capture the delimiter)</span><br />
&nbsp; &nbsp;<span class="co1">// will, unfortunately, have to be slowed down</span><br />
&nbsp; &nbsp;<span class="kw2">var</span> m, str = <span class="st0">''</span>, arr = <span class="br0">&#91;</span><span class="br0">&#93;</span>;<br />
&nbsp; &nbsp;<span class="kw2">var</span> i, len = <span class="kw1">this</span>.<span class="me1">length</span>;<br />
&nbsp; &nbsp;<span class="kw1">for</span> <span class="br0">&#40;</span>i = <span class="nu0">0</span>; i &lt; len; i++<span class="br0">&#41;</span><br />
&nbsp; &nbsp;<span class="br0">&#123;</span><br />
&nbsp; &nbsp;&nbsp; &nbsp;str += <span class="kw1">this</span>.<span class="me1">charAt</span><span class="br0">&#40;</span>i<span class="br0">&#41;</span>;<br />
&nbsp; &nbsp;&nbsp; &nbsp;m = str.<span class="me1">match</span><span class="br0">&#40;</span>_regEx<span class="br0">&#41;</span>;<br />
&nbsp; &nbsp;&nbsp; &nbsp;<span class="kw1">if</span> <span class="br0">&#40;</span>m<span class="br0">&#41;</span><br />
&nbsp; &nbsp;&nbsp; &nbsp;<span class="br0">&#123;</span><br />
&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;arr.<span class="me1">push</span><span class="br0">&#40;</span>str.<span class="me1">replace</span><span class="br0">&#40;</span>m<span class="br0">&#91;</span><span class="nu0">0</span><span class="br0">&#93;</span>, <span class="st0">''</span><span class="br0">&#41;</span><span class="br0">&#41;</span>;<br />
&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;arr.<span class="me1">push</span><span class="br0">&#40;</span>m<span class="br0">&#91;</span><span class="nu0">0</span><span class="br0">&#93;</span><span class="br0">&#41;</span>;<br />
&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;str = <span class="st0">''</span>;<br />
&nbsp; &nbsp;&nbsp; &nbsp;<span class="br0">&#125;</span><br />
&nbsp; &nbsp;<span class="br0">&#125;</span></p>
	<p>&nbsp; &nbsp;<span class="kw1">if</span> <span class="br0">&#40;</span>str != <span class="st0">''</span><span class="br0">&#41;</span> arr.<span class="me1">push</span><span class="br0">&#40;</span>str<span class="br0">&#41;</span>;</p>
	<p>&nbsp; &nbsp;<span class="kw1">return</span> arr;<br />
<span class="br0">&#125;</span></div>
	<h3>Explanation:</h3>
	<p>The code isn't too hard, but it's worth pointing out a few specific points.</p>
	<p>First, I'm extending the native <code>String</code> object using <code>.prototype</code>.  I know some people aren't comfortable with this, and if you're one of them, feel free to write a stand-alone function where you pass in a string variable, as well as the regex.</p>
	<p>Second, Most browsers actually will capture the delimiter when you use regular expression grouping, so if the client happens to be using a browser that can do it, we'll want to use the native implementation, as it will be <em>much</em> faster.  We do it like this:</p>
	<div class="dean_ch" style="white-space: nowrap;"><span class="kw1">if</span> <span class="br0">&#40;</span><span class="st0">'a~b'</span>.<span class="me1">split</span><span class="br0">&#40;</span><span class="re0">/<span class="br0">&#40;</span>~<span class="br0">&#41;</span>/</span><span class="br0">&#41;</span>.<span class="me1">length</span> === <span class="nu0">3</span><span class="br0">&#41;</span> <span class="br0">&#123;</span> <span class="kw1">return</span> <span class="kw1">this</span>.<span class="me1">split</span><span class="br0">&#40;</span>_regEx<span class="br0">&#41;</span>; <span class="br0">&#125;</span></div>
	<p>The above code does a very simple test in which we check to see if the split of "a~b" on the character "~" returns an array of length 3.  If so, we assume support for regular expression grouping with the <code>.split(..)</code> function.  Otherwise, we're forced to do this manually.</p>
	<p>Now, if we <em>do</em> need to do this manually, the regular expression had better have its global (/g) flag set.  Why?  Because we're executing a <code>.match(..)</code> on the <code>_regEx</code> later on in the code, and in order for that to match more than just the first delimiter it finds, that global flag needs to be set.</p>
	<div class="dean_ch" style="white-space: nowrap;">
<span class="kw1">if</span> <span class="br0">&#40;</span>!_regEx.<span class="me1">global</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp;<span class="br0">&#123;</span> _regEx = <span class="kw2">new</span> RegExp<span class="br0">&#40;</span>_regEx.<span class="me1">source</span>, <span class="st0">'g'</span> + <span class="br0">&#40;</span>_regEx.<span class="me1">ignoreCase</span> ? <span class="st0">'i'</span> : <span class="st0">''</span><span class="br0">&#41;</span><span class="br0">&#41;</span>; <span class="br0">&#125;</span></div>
	<p>This code first checks to see if the global flag is already set.  If so, we're good shape; no need to make any alterations.  If not, we'll need to set it.  Problem is, the <code>.global</code> property of any regular expression object is read-only, so we must construct a new <code>RegExp</code> using the <code>.source</code> of the original <code>_regEx</code> and manually specify the global flag (by passing in a 'g').  Additionally, we need to make sure we maintain any request in the original regular expression to ignore case, which is accomplished with: <code>(_regEx.ignoreCase ? 'i' : '')</code>.</p>
	<p>The rest of the logic is pretty straight-forward.  We loop through the given string, building, character by character, the strings that will make up the individual string elements in the array to be returned.  At each iteration through the loop, we'll test (using <code>.match(..)</code>) to see if the string we've built so far, contains any of the delimiters specified by the passed in <code>_regEx</code>.  If so, we need to push that string into the array, <em>but</em> we need to strip the delimiter out of the string before we do (hence the code: <code>arr.push(str.replace(m[0], ''));</code>).</p>
	<p>We also need to push the delimiter itself into the array and then reset the <code>str</code> variable back to an empty string.</p>
	<div class = "note">
It should be safe to access <code>m[0]</code> (and not bother with other indices).  Since we're testing the match on each iteration, we can expect to receive, at most, one match returned in the <code>m</code> array (even if that match is more than one character).
</div>
	<h3>Final thoughts:</h3>
	<p>It's worth pointing out that compared to the native <code>.split(..)</code>, my implementation is <strong>slow!</strong>  So, whenever you don't need to capture regular expression groupings, stick with the native function.  Of course, for browsers that support the feature natively, we'll be using the native <code>.split(..)</code> under the hood anyway, but regardless... if you know you won't need groupings, don't bother with <code>.xSplit(..)</code>.</p>
	<p>Comments welcome.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.stchur.com/2007/03/28/split-broken-in-ie/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>The Javascript goto statement</title>
		<link>http://blog.stchur.com/2007/03/09/the-javascript-goto-statement/</link>
		<comments>http://blog.stchur.com/2007/03/09/the-javascript-goto-statement/#comments</comments>
		<pubDate>Fri, 09 Mar 2007 05:32:51 +0000</pubDate>
		<dc:creator>sstchur</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Javascript basics]]></category>

		<guid isPermaLink="false">http://stchur.com/blog2/2007/03/09/the-javascript-goto-statement/</guid>
		<description><![CDATA[There isn't one (in case you're scratching your head at the title of this post.) Some would say this is a good thing because "goto is evil." I don't have a problem with the fact that there is no goto statement in Javascript. I do, however, have a problem with people who unconditionally think "goto [...]]]></description>
			<content:encoded><![CDATA[	<p>There isn't one (in case you're scratching your head at the title of this post.)</p>
	<p>Some would say this is a good thing because "goto is evil."  I don't have a problem with the fact that there is no <code>goto</code> statement in Javascript.  I do, however, have a problem with people who unconditionally think "goto is evil."</p>
	<p>I for one, do <em>not</em> think <code>goto</code> is (always) evil.  Oh it can be, don't get me wrong.  But it doesn't have to be, and you shouldn't automatically assume that it is.</p>
	<blockquote><p>Donald Knuth's <cite>Structured Programming with go to Statements</cite> ... analyzes many common programming tasks and finds that in some of them GOTO is the most optimal language construct to use.</p></blockquote>
	<p>Still, as <a href = "http://en.wikipedia.org/wiki/Joey_Tribbiani">Joey Tribbiani</a> says, "it's a moo point (like a cow's opinion; it doesn't matter)," because there is no <code>goto</code> statement in Javascript.</p>
	<p>Why all this talk in a Javscript blog about something that doesn't exist in the language?  Because Javascript provides an alternative.  One that, if you're me, your coworkers will criticize you for using (even though it made perfect sense and actually <em>enhanced</em> the readability of the code!)</p>
	<p>Read on to learn more.</p>
	<p><span id="more-31"></span></p>
	<h3>The labeled continue</h3>
	<p>Labeled continue is a perfectly valid language construct in ECMAScript-262 (Edition 3), and yet, I caught hell and had to fight a bitter battle in order to be able to use it.</p>
	<p>The scenario?  I was dealing with a nested loop.  The outer loop was iterating an array of objects.  Those objects happened to be arrays themselves which also needed to be traversed.</p>
	<p>To make the example a little more concrete, let's pretend the outer array was an array of "Pastures."  Each Pasture contains many "Cows."  The idea was to loop through the array of Pastures checking to see if all the Cows in that Pasture were done eating (work with me here).  If so, we'd fire a callback function to let Farmer Ned know that all the Cows in Pasture X were done eating.</p>
	<p>Simple enough right?  All we need to do is loop through the Pastures, check each cow in the given pasture to see if it's done eating, and only if <em>all</em> cows are done eating do we fire the callback function.</p>
	<p>For efficiency, I decided to test the cows to see if any one cow <em>was</em> eating.  If so, I could abort the remaining checks.</p>
	<p>Here was my take:</p>
	<div class="dean_ch" style="white-space: nowrap;">
<span class="kw2">var</span> pastures = getPastures<span class="br0">&#40;</span><span class="br0">&#41;</span>;<br />
<span class="kw2">var</span> i, pastureLen = pastures.<span class="me1">length</span>;</p>
	<p>pastureLoop:<br />
<span class="kw1">for</span> <span class="br0">&#40;</span>i = <span class="nu0">0</span>; i &lt; pastureLen; i++<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp;<span class="kw2">var</span> pasture = pastures<span class="br0">&#91;</span>i<span class="br0">&#93;</span>;<br />
&nbsp; &nbsp;<span class="kw2">var</span> cows = pasture.<span class="me1">getCows</span><span class="br0">&#40;</span><span class="br0">&#41;</span>;</p>
	<p>&nbsp; &nbsp;<span class="kw2">var</span> j, numCows = cows.<span class="me1">length</span>;<br />
&nbsp; &nbsp;<span class="kw1">for</span> <span class="br0">&#40;</span>j = <span class="nu0">0</span>; j &lt; numCows; j++<span class="br0">&#41;</span><br />
&nbsp; &nbsp;<span class="br0">&#123;</span><br />
&nbsp; &nbsp;&nbsp; &nbsp;<span class="kw2">var</span> cow = cows<span class="br0">&#91;</span>j<span class="br0">&#93;</span>;<br />
&nbsp; &nbsp;&nbsp; &nbsp;<span class="kw1">if</span> <span class="br0">&#40;</span>cow.<span class="me1">isEating</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;<span class="br0">&#123;</span> <span class="kw1">continue</span> pastureLoop; <span class="br0">&#125;</span><br />
&nbsp; &nbsp;<span class="br0">&#125;</span></p>
	<p>&nbsp; &nbsp;<span class="co1">// No cows were eating, so fire the callback for pasture[i]</span><br />
&nbsp; &nbsp;pasture.<span class="me1">executeCallback</span><span class="br0">&#40;</span><span class="br0">&#41;</span>;&nbsp;&nbsp; &nbsp;<span class="co1">// or whatever</span><br />
<span class="br0">&#125;</span></div>
	<p>Of course, as soon as the code-review process started, I got one developer and two PMs (PMs no less!) criticizing my use of "goto."</p>
	<p>What bothered me wasn't so much the criticism of my code (heck, that happens all the time).  What bothered me was that they <em>automatically</em> rejected it when they saw the labeled continue (without stopping to think if this might not actually make some sense!)</p>
	<p>Now, I'm well aware that you could accomplish the same thing by creating a boolean variable, <code>allDoneEating</code>, which is initially <code>true</code> and which only gets set to <code>false</code> if some <code>cow.isEating()</code> statement returns <code>true</code>.  Then you'd have to add an additional check <em>outside</em> of the inner for-loop, but <em>inside</em> the outer for-loop to see if the <code>allDoneEating</code> boolean were <code>true</code>, and if so, you could fire the callback function.</p>
	<p>Phew! It was hardly worth typing that out.</p>
	<p>Why in the world would I want to go through all that extra effort when a simple little <code>continue pastureLoop;</code> will do just fine?</p>
	<p>Furthermore, what could be <em>more</em> readable than <code>continue pastureLoop</code>?  It very clearly and very succinctly describes the fact that, if any cow is eating, we want to continue with the pasture loop!</p>
	<p>I dunno, maybe it's just my own crazy brain that works this way, but I think the labeled continue is a clean and elegant solution in this particular case, and I don't see any reason why it should be shunned in favor of creating an extra boolean and requiring an extra if-conditional.<br />
	<h3>The labeled break:</h3>
	<p>I've done a lot of ranting and very little coding in this blog post, so to end, I'll offer a quick example of a similar construct to labeled continue: labeled break.</p>
	<p>For this code snippet, I'll return to the cow example, but with slightly different requirements.  This time, we want to know how healthy our cows are.  We're going to loop through each pasture counting the number of healthy cows we can find <em>until</em> we find a sick cow, at which time we want to abort the entire process.  A labeled break makes this really easy</p>
	<div class="dean_ch" style="white-space: nowrap;">
	<p><span class="kw2">var</span> healthyCows = <span class="nu0">0</span>;<br />
<span class="kw2">var</span> pastures = getPastures<span class="br0">&#40;</span><span class="br0">&#41;</span>;<br />
<span class="kw2">var</span> i, pastureLen = pastures.<span class="me1">length</span>;</p>
	<p>pastureLoop:<br />
<span class="kw1">for</span> <span class="br0">&#40;</span>i = <span class="nu0">0</span>; i &lt; pastureLen; i++<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp;<span class="kw2">var</span> pasture = pastures<span class="br0">&#91;</span>i<span class="br0">&#93;</span>;<br />
&nbsp; &nbsp;<span class="kw2">var</span> cows = pasture.<span class="me1">getCows</span><span class="br0">&#40;</span><span class="br0">&#41;</span>;</p>
	<p>&nbsp; &nbsp;<span class="kw2">var</span> j, numCows = cows.<span class="me1">length</span>;<br />
&nbsp; &nbsp;<span class="kw1">for</span> <span class="br0">&#40;</span>j = <span class="nu0">0</span>; j &lt; numCows; j++<span class="br0">&#41;</span><br />
&nbsp; &nbsp;<span class="br0">&#123;</span><br />
&nbsp; &nbsp;&nbsp; &nbsp;<span class="kw2">var</span> cow = cows<span class="br0">&#91;</span>j<span class="br0">&#93;</span>;<br />
&nbsp; &nbsp;&nbsp; &nbsp;<span class="kw1">if</span> <span class="br0">&#40;</span>cow.<span class="me1">isSick</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;<span class="br0">&#123;</span> <span class="kw1">break</span> pastureLoop; <span class="br0">&#125;</span></p>
	<p>&nbsp; &nbsp;&nbsp; &nbsp;healthyCows++;<br />
&nbsp; &nbsp;<span class="br0">&#125;</span><br />
<span class="br0">&#125;</span></p>
	<p><span class="kw3">alert</span><span class="br0">&#40;</span>healthyCows + <span class="st0">' healty cows were found before a sick cow was found'</span><span class="br0">&#41;</span>;</div>
	<p>And again, you could of course accomplish this without a labeled break.  Depending on the complexity of your situation, might want to avoid the labeled break, but then again, it might be just the thing!</p>
	<p>If there's anything I hope this post conveys, it's that you shouldn't <em>unconditionally</em> rule out any valid language construct just because a few naysayers claim that it's "evil."  Analyze your situation, think about what you're trying to accomplish, and make a decision that's appropriate for your situation.</p>
	<p>Happy ECMAScripting <img src='http://blog.stchur.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.stchur.com/2007/03/09/the-javascript-goto-statement/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Logical AND (&amp;&amp;) and Logical OR (&#124;&#124;) in Javascript</title>
		<link>http://blog.stchur.com/2007/02/14/logical-and-and-logical-or-in-javascript/</link>
		<comments>http://blog.stchur.com/2007/02/14/logical-and-and-logical-or-in-javascript/#comments</comments>
		<pubDate>Wed, 14 Feb 2007 05:05:49 +0000</pubDate>
		<dc:creator>sstchur</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Javascript basics]]></category>

		<guid isPermaLink="false">http://stchur.com/blog2/2007/02/14/logical-and-and-logical-or-in-javascript/</guid>
		<description><![CDATA[Logical AND (represented as &#038;&#038;) and logical OR (represented as &#124;&#124;) are interesting critters in Javascript. You can get along for weeks, months, or even years without ever knowing the subtle nuance I'm going to discuss in this post. If your background is... well, pretty much any other language on the planet (and especially a [...]]]></description>
			<content:encoded><![CDATA[	<p>Logical AND (represented as <code>&#038;&</code>) and logical OR (represented as <code>||</code>) are interesting critters in Javascript.  You can get along for weeks, months, or even years without ever knowing the subtle nuance I'm going to discuss in this post.  If your background is... well, pretty much any other language on the planet (and especially a compiled one), then chances are you've used Logical AND/OR like this:</p>
	<div class="dean_ch" style="white-space: nowrap;">
<span class="kw1">if</span> <span class="br0">&#40;</span>x &gt; <span class="nu0">5</span> &amp;&amp; x &lt; <span class="nu0">10</span><span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp;<span class="co1">// x is greater than 5 and less than 10</span><br />
<span class="br0">&#125;</span></div>
	<p>But I'm guessing you probably <em>haven't</em> ever used it like this:</p>
	<div class="dean_ch" style="white-space: nowrap;">
<span class="kw2">function</span> sayHi<span class="br0">&#40;</span><span class="kw3">name</span><span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp;<span class="kw3">name</span> = <span class="kw3">name</span> || <span class="st0">'Whoever you are'</span>;<br />
&nbsp; &nbsp;<span class="kw3">alert</span><span class="br0">&#40;</span><span class="st0">'Hi there '</span> + <span class="kw3">name</span><span class="br0">&#41;</span>;<br />
<span class="br0">&#125;</span></div>
	<p>What's going on here?  Isn't the result of a Logical AND/OR a boolean value?</p>
	<p>Read on to learn more.</p>
	<p><span id="more-28"></span></p>
	<p>In Javascript, Logical AND/OR don't always return <code>true</code> or <code>false</code>.  In fact, it wouldn't be inaccurate to say that they never <em>intrinsically</em> return <code>true</code> or <code>false</code>.</p>
  Instead, when evaluating Logical AND/OR, Javascript will return one of the <em>operands</em> as the result of the operation.  Weird huh?  Maybe, but super useful too!</p>
	<p>Here are the two basic rules:</p>
	<ul>
	<li>For Logical AND (&#038;&):  Javascript returns the first value that is <em>"false-like"</em>, or the last value, if no values are "false-like".</li>
	<li>For Logical OR (||):  Javascript returns the first value that is <em>"truth-like"</em>, or the last value, if no values are "truth-like".</li>
	</ul>
	<p>What is "truth-like"?  It's any value in Javascript that, while not explicitly <code>true</code>, evaluates to true when used in an expression.  This would be essentially anything that <em>isn't</em> "false-like" (more on that in a moment).  Examples include:</p>
	<ul>
	<li>5</li>
	<li>'Steve'
<li>
	<li>new Object()</li>
	<li>{}</li>
	</ul>
	<p>The list goes on infinitely.</p>
	<p>A "false-like" value is any value that evaluates to false in an expression.  I think most people are pretty familiar with this one.  It's precisely because of this that statements like:</p>
	<div class="dean_ch" style="white-space: nowrap;"><span class="kw1">if</span> <span class="br0">&#40;</span>myDiv.<span class="me1">addEventListener</span><span class="br0">&#41;</span> <span class="br0">&#123;</span> <span class="coMULTI">/* add some event listener */</span> <span class="br0">&#125;</span></div>
	<p>actually work.  The value of <code>myDiv.addEventListener</code> is neither <code>true</code> nor <code>false</code>, but it will treated as a "truth-like" or a "false-like" value, depending on whether or not the browser in question supports it.</p>
	<p>"False-like" values include:</p>
	<ul>
	<li>null</li>
	<li>undefined</li>
	<li>''</li>
	<li>""</li>
	<li>0</li>
	<li>NaN</li>
	</ul>
	<div class = "note">
If you're familiar with Douglass Crockford, he uses the terms "truthy" and "falsey" instead of "truth-like" and "false-like."  That's fine I guess, but I don't like the term "truthy" because it sounds a lot like toothy, which makes me think of a lion, which then makes me think of Aslan in the Chronicles of Narnia.  I then start picturing Peter, Susan, Edmund, and Lucy on one of their adventures in Narnia, and then the programming part of my brain gets all thrown out of whack!
</div>
	<p>Now, you can get along (presumably forever) without actually ever understanding the subtlety with which Javascript treats Logical AND/OR.  Chances are you're going to end up with just the results you expect (especially if you restrict your use to if-conditionals).  <em>But</em>, if you happen to know Javascript's unique handling of Logical AND/OR (and now you do), you can leverage it to slim down your code and, in some cases, make it more elegant.</p>
	<p>We've already seen on example of this back at the beginning of this post.  We leveraged Logical OR to provide a default value for a function parameter.  This is definitely one of my favorite techniques.  Not only does it cut down on the amount of code you need to write, but it reads really well to.  When I see something like this:</p>
	<div class="dean_ch" style="white-space: nowrap;"><span class="kw2">var</span> x = n || <span class="nu0">100</span>;</div>
	<p>I read that as: "x will be equal to n (if n is a valid value) or 100 (if n isn't valid)."</p>
	<p>The real-world use for leveraging Logical AND in this way is probably a lot less.  I can't think of too many scenarios in which you'd want the value of some variable to be the first "false-like" value in a list of values.  I suppose you could use it to control program flow as in:</p>
	<div class="dean_ch" style="white-space: nowrap;">
<span class="kw2">function</span> foo<span class="br0">&#40;</span><span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp;<span class="kw3">alert</span><span class="br0">&#40;</span><span class="st0">'Aluminum Monkeys Festering!'</span><span class="br0">&#41;</span>;<br />
<span class="br0">&#125;</span></p>
	<p><span class="kw2">var</span> x = <span class="nu0">5</span>;<br />
x &amp;&amp; foo<span class="br0">&#40;</span><span class="br0">&#41;</span>;</div>
	<p>In the above example, the <code>foo()</code> function will execute, if <code>x</code> is "truth-like" (which it is in this case).  The problem is, you generally want to execute a function conditionally, based on some much more specific proposition (i.e.  x > 0).  You can't get anything that specific from Logical AND.  In this example, <code>foo()</code> would execute if <code>x</code> were any of: <code>'Steve', {}, -1, 0.04</code> (and of course, any other "truth-like" value).</p>
	<p>My recommendation would be to simply <em>understand</em> how Javascript treats Logical AND, but I wouldn't recommend trying to leverage it as a "short cut" -- it'll probably just make things more confusing.  When it comes to short cuts, stick with using Logical OR to provide default values for function parameters.</p>
	<p>Of course, if anyone <em>does</em> know of a way to leverage Logical AND to do something creative and/or elegant, I'd love to hear it.  Feel free to send me your comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.stchur.com/2007/02/14/logical-and-and-logical-or-in-javascript/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Javascript variable scope confusion</title>
		<link>http://blog.stchur.com/2007/01/31/javascript-variable-scope-confusion/</link>
		<comments>http://blog.stchur.com/2007/01/31/javascript-variable-scope-confusion/#comments</comments>
		<pubDate>Wed, 31 Jan 2007 18:15:10 +0000</pubDate>
		<dc:creator>sstchur</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Javascript basics]]></category>

		<guid isPermaLink="false">http://stchur.com/blog2/2007/01/31/javascript-variable-scope-confusion/</guid>
		<description><![CDATA[Since Javascript has a very C/Java-like syntax, it's easy to make assumptions about the language that turn out to be rather wrong. Take variable scoping for instance. It would seem natural that a variable defined within a loop or within an if conditional, would go out of scope when that loop (or if block) came [...]]]></description>
			<content:encoded><![CDATA[	<p>Since Javascript has a very C/Java-like syntax, it's easy to make assumptions about the language that turn out to be rather wrong.  Take variable scoping for instance.  It would seem natural that a variable defined within a loop or within an if conditional, would go out of scope when that loop (or if block) came to an end:</p>
	<div class="dean_ch" style="white-space: nowrap;">
<span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw2">var</span> i = <span class="nu0">0</span>; i &lt; <span class="nu0">100</span>; i++<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp;<span class="kw2">var</span> s = <span class="st0">'steve_'</span> + i;<br />
<span class="br0">&#125;</span><br />
<span class="kw3">alert</span><span class="br0">&#40;</span>s<span class="br0">&#41;</span>;&nbsp; &nbsp;<span class="co1">// steve_99 or undefined?</span></div>
	<p>Run the above code snippet, and you'll get an alert that says 'steve_99'.  It sort of feels like the variable <code>s</code> should be undefined, but it's not.  I'm sure there are lots of Javascripters who already know this, but I'm also pretty sure there's also a few who've never noticed this.</p>
	<p>Is this <em>always</em> the case?  Do all variables created with <code>var</code> end up being essentially global variables?  Not exactly.</p>
	<p><span id="more-27"></span></p>
	<p>So in what scenario does variable scoping act that way you'd think it would in Javascript?  It's pretty simple actually.  All variables created with <code>var</code> are global variables (within their scoped context).  Only functions (which in Javascript are objects) and the global object (which in web browsers maps to <code>window</code>) have variable scope.  An example will help illustrate:</p>
	<div class="dean_ch" style="white-space: nowrap;">
<span class="kw2">function</span> foo<span class="br0">&#40;</span><span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp;<span class="kw2">var</span> x = <span class="st0">'llama are so great!'</span>;<br />
&nbsp; &nbsp;<span class="kw3">alert</span><span class="br0">&#40;</span>x<span class="br0">&#41;</span>;<br />
<span class="br0">&#125;</span><br />
foo<span class="br0">&#40;</span><span class="br0">&#41;</span>;<br />
<span class="kw3">alert</span><span class="br0">&#40;</span>x<span class="br0">&#41;</span>;&nbsp; &nbsp;<span class="co1">// error: x is undefined</span></div>
	<p>This is much more natural and (I think) what most programmers expect.  We can combine first example and the second and it should be pretty easy to see what's going to happen.</p>
	<div class="dean_ch" style="white-space: nowrap;">
<span class="kw2">function</span> foo<span class="br0">&#40;</span><span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp;<span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw2">var</span> i = <span class="nu0">0</span>; i &lt; <span class="nu0">100</span>; i++<span class="br0">&#41;</span><br />
&nbsp; &nbsp;<span class="br0">&#123;</span><br />
&nbsp; &nbsp;&nbsp; &nbsp;<span class="kw2">var</span> s = <span class="st0">'steve_'</span> + i;<br />
&nbsp; &nbsp;<span class="br0">&#125;</span><br />
&nbsp; &nbsp;<span class="kw3">alert</span><span class="br0">&#40;</span>s<span class="br0">&#41;</span>;&nbsp; &nbsp;<span class="co1">// alerts 'steve_99'</span><br />
&nbsp; &nbsp;<span class="kw2">var</span> x = <span class="st0">'llama are so great!'</span>;<br />
&nbsp; &nbsp;<span class="kw3">alert</span><span class="br0">&#40;</span>x<span class="br0">&#41;</span>;<br />
<span class="br0">&#125;</span><br />
foo<span class="br0">&#40;</span><span class="br0">&#41;</span>;&nbsp; &nbsp;&nbsp; &nbsp;<span class="co1">// alerts 'steve_99' followed by 'llamas are so great!';</span><br />
<span class="kw3">alert</span><span class="br0">&#40;</span>x<span class="br0">&#41;</span>;&nbsp; &nbsp;<span class="co1">// error: x is undefined</span></div>
	<p>So, as expected, <code>x</code> is still undefined (outside of the function <code>foo()</code>).  And <code>s</code>, having been created with <code>var</code> is still "global".  Global, that is, in the scope context of the <code>foo()</code> function.</p>
	<p>What does this mean for the average Javascipter?  Well, it just means you should be careful.  Don't be fooled into thinking a variable has gone out of scope, when in fact, it has done no such thing.</p>
	<p>Given Javsscript's (somewhat peculiar) handling of variables, you might suggest then, that there is no point in following the typical programming style of declaring variables as close to where they're first used as possible.  I know Douglass Crockford believes you shouldn't do this in Javascript.  A part of me agrees, but I still tend to do it, just because it helps me, personally, with readability.  I can certainly understand the argument though, to do as Mr. Crockford suggests and declare all of your variables at the beginning of your functions.</p>
	<p>What's interesting, is that while I haven't really gotten in the habit of doing this, I have gotten into the habit of <em>not</em> declaring looping variables inside of for loops (though admittedly, this is contrary to my above examples).  But in most real-world scenarios, I tend to do this:</p>
	<div class="dean_ch" style="white-space: nowrap;">
<span class="kw2">var</span> i, len = someArray.<span class="me1">length</span>;<br />
<span class="kw1">for</span> <span class="br0">&#40;</span>i = <span class="nu0">0</span>; i &lt; len; i++<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp;<span class="coMULTI">/* my code here */</span><br />
<span class="br0">&#125;</span></div>
	<p>And not this:</p>
	<div class="dean_ch" style="white-space: nowrap;">
<span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw2">var</span> i = <span class="nu0">0</span>; i &lt; someArray.<span class="me1">length</span>; i++<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp;<span class="coMULTI">/* my code here */</span><br />
<span class="br0">&#125;</span></div>
	<p>I declare the <code>i</code> variable outside of the for loop for just the reasons we've been considering in this post.  Since, after the above code executes, <code>i</code> will still be a valid variable with global scope, I prefer to write my code so that it <em>looks</em> that way.  It's just too easy to look at the above code snippet and think that <code>i</code> is confined to the scope of the for loop (it's not).</p>
	<div class = "note">
If you don't believe me on this, try running the above code snippet (substitute 100 for <code>someArray.length</code>) and then, outside of the for loop, put the statement <code>alert(i);</code>.  You know what you'll get don't you?  No, it's not 99.  It's 100, which makes perfect sense!
</div>
	<p>I'm curious to know what other people think about this.  I generally don't ask questions in my blog posts (and this probably more to do with the fact that i don't get a <em>ton</em> of traffic (yet) than anything else, but I figure... what the heck, I'll break my normal rules this one time.</p>
	<p>What does everyone else prefer and why?  What advantages and disadvantages do you see, and what programming notations/styles do you use to help keep variable scoping easily understood and readable in your code?</p>
	<p>If you have thoughts on this, I'd love to hear them.</p>
	<p>Comments welcome.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.stchur.com/2007/01/31/javascript-variable-scope-confusion/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

