<?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>Meatball&#039;s Guide to .NET &#187; JavaScript</title>
	<atom:link href="http://rogerpence.com/blog/index.php/archives/tag/javascript/feed" rel="self" type="application/rss+xml" />
	<link>http://rogerpence.com/blog</link>
	<description>A dogma-free guide to making real-world sense of .NET</description>
	<lastBuildDate>Wed, 23 Jun 2010 16:15:35 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Avoid non-FireFox browser issues with Firebug&#8217;s console object</title>
		<link>http://rogerpence.com/blog/index.php/archives/319</link>
		<comments>http://rogerpence.com/blog/index.php/archives/319#comments</comments>
		<pubDate>Thu, 21 Jan 2010 15:57:34 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Firebug]]></category>
		<category><![CDATA[qUnit]]></category>

		<guid isPermaLink="false">http://rogerpence.com/blog/?p=319</guid>
		<description><![CDATA[The Firefox Firebug add-in is a superb JavaScript debugger. If you’re writing, learning, or debugging JavaScript (and if you’re doing the first two, you’re certainly doing the third!), Firebug should be in the top drawer of your JavaScript toolbox. 
One of the Firebug features I use a lot is its console object. The console object [...]]]></description>
			<content:encoded><![CDATA[<p>The Firefox <a href="http://getfirebug.com/index.html">Firebug</a> add-in is a superb JavaScript debugger. If you’re writing, learning, or debugging JavaScript (and if you’re doing the first two, you’re certainly doing the third!), Firebug should be in the top drawer of your JavaScript toolbox. </p>
<p>One of the Firebug features I use a lot is its <a href="http://getfirebug.com/console.html">console object</a>. The console object lets you emit messages from your code to Firebug’s console. For example, <em>console.log( n );</em> emits informational message <em>n</em> to the Firebug console while <em>console.error(n);</em> emits error message <em>n</em> to the Firebug console. This console is very handy, especially in your JavaScript unit testing code. While Firebug doesn’t have a steep learning curve, some of its features can sneak up on you. If you haven’t yet dug into Firebug’s console, do so soon! </p>
<p>A challenge that the Firebug console presents is that to use it requires that you pepper your code with Firebug-specific code that will cause the code to break in other non-Firefox browsers. For production work, you’ll probably want to comment out or remove <em>console</em> lines.&#160; However, I want to run my JavaScript unit tests in several browsers and don’t want to have to change the test code to do so. </p>
<p>Firebug’s creator, <a href="http://www.joehewitt.com/about.php">Joe Hewitt</a>, posted a nice little <a href="http://code.google.com/p/fbug/source/browse/branches/firebug1.2/lite/firebugx.js?r=964">chunk of code</a> (shown below) that maps Firebug’s various console methods to no-ops for non-FIreFox browsers. With Joe’s code in place, JavaScript tests can run in any browser. For <a href="http://docs.jquery.com/QUnit">qUnit</a> JavaScript unit testing code, add Joe’s code to the module’s setup method (more on qUnit in an upcoming post). </p>
<div class="sourceCodeHeading">Joe Hewitt’s prophylactic Firebug console code</div>
<div id="Id1009557102SourceCode" class="sourceCode">
<pre class="even"><span class="ln">  1</span><span class="code">if (!window.console || !console.firebug)</span></pre>
<pre class="odd"><span class="ln">  2</span><span class="code">{</span></pre>
<pre class="even"><span class="ln">  3</span><span class="code">    var names = [&quot;log&quot;, &quot;debug&quot;, &quot;info&quot;, &quot;warn&quot;, &quot;error&quot;, &quot;assert&quot;, &quot;dir&quot;, &quot;dirxml&quot;,</span></pre>
<pre class="odd"><span class="ln">  4</span><span class="code">    &quot;group&quot;, &quot;groupEnd&quot;, &quot;time&quot;, &quot;timeEnd&quot;, &quot;count&quot;, &quot;trace&quot;, &quot;profile&quot;, &quot;profileEnd&quot;];</span></pre>
<pre class="even"><span class="ln">  5</span><span class="code"></span></pre>
<pre class="odd"><span class="ln">  6</span><span class="code">    window.console = {};</span></pre>
<pre class="even"><span class="ln">  7</span><span class="code">    for (var i = 0; i &lt; names.length; ++i)</span></pre>
<pre class="odd"><span class="ln">  8</span><span class="code">        window.console[names[i]] = function() {}</span></pre>
<pre class="even"><span class="ln">  9</span><span class="code">}</span></pre>
</div>
<div class="sourceCodeFooter"><a id="Id1009557102SourceCodeToClipboard" class="copyLink" href="javascript:toggleLineNumbers( 'Id1009557102SourceCode' );">Show copy-friendly code</a></div>
<p><em>One final note: </em>I occasionally teach JavaScript. Joe’s graceful little solution to the awkward cross-browser problem posed by using Firebug’s <em>console </em>object makes a great little quiz for JavaScript beginners. It’s not a lot of code, but what little code there is is interesting code. When someone can explain Joe’s code clearly, I know they are ready for the next notch in their JavaScript programming belt. </p>
]]></content:encoded>
			<wfw:commentRss>http://rogerpence.com/blog/index.php/archives/319/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using jQuery to work with ASP.NET-munged HTML elements</title>
		<link>http://rogerpence.com/blog/index.php/archives/263</link>
		<comments>http://rogerpence.com/blog/index.php/archives/263#comments</comments>
		<pubDate>Tue, 06 Oct 2009 21:13:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://rogerpence.com/blog/?p=263</guid>
		<description><![CDATA[ASP.NET (pre-ASP.NET 4.0, that is) makes it a point of munging control IDs by forcing a fully-qualified naming scheme on both the resulting HTML element’s ID and Name attributes. For example, a TextBox named textboxName, when placed in a user control used on a content page with a master page gets rendered like this at [...]]]></description>
			<content:encoded><![CDATA[<p>ASP.NET (pre-ASP.NET 4.0, that is) makes it a point of munging control IDs by forcing a fully-qualified naming scheme on both the resulting HTML element’s ID and Name attributes. For example, a TextBox named textboxName, when placed in a user control used on a content page with a master page gets rendered like this at runtime:</p>
<div class="sourceCodeHeading">Figure 1. HTML element with munged ID and Name attributes.</div>
<div id="Id0417589035SourceCode" class="sourceCode">
<pre class="even"><span class="ln">  1</span><span class="code">&lt;input name=&quot;ctl00$ContentPlaceHolder1$ctl00$textboxName&quot; </span></pre>
<pre class="odd"><span class="ln">  2</span><span class="code">       id=&quot;ctl00_ContentPlaceHolder1_ctl00_textboxName&quot; </span></pre>
<pre class="even"><span class="ln">  3</span><span class="code">	      type=&quot;text&quot; /&gt;</span></pre>
</div>
<div class="sourceCodeFooter"><a id="Id0417589035SourceCodeToClipboard" class="copyLink" href="javascript:toggleLineNumbers( 'Id0417589035SourceCode' );">Show copy-friendly code</a></div>
<p>It’s often desirable to dynamically associate either behaviors or cosmetic styling to these elements, but because of the munged ID, locating these elements, especially with bare-naked CSS selected is challenging (unless you hard-code special case CSS class names).</p>
<p>jQuery makes the selection of such elements quite easy. Because the munged IDs always end with the control’s base name, you know that the resulting HTML ID will end with that control name. Here’s how to use jQuery to select these elements based on the ending value of their ID.</p>
<p>First, add a reference to jQuery in the master page’s &lt;head&gt; section. (In this example, I’m pulling jQuery from the <a href="http://weblogs.asp.net/scottgu/archive/2009/09/15/announcing-the-microsoft-ajax-cdn.aspx">Microsoft Ajax Content Delivery Network</a>.)</p>
<div class="sourceCodeHeading">Figure 2. Add a reference to jQuery in the section of the master page.</div>
<div id="Id0416540130SourceCode" class="sourceCode">
<pre class="even"><span class="ln">  1</span><span class="code">&lt;script src=&quot;http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.min.js&quot; </span></pre>
<pre class="odd"><span class="ln">  2</span><span class="code">        type=&quot;text/javascript&quot;&gt;&lt;/script&gt;     </span></pre>
</div>
<div class="sourceCodeFooter"><a id="Id0416540130SourceCodeToClipboard" class="copyLink" href="javascript:toggleLineNumbers( 'Id0416540130SourceCode' );">Show copy-friendly code</a></div>
<p>To locate an HTML element with a munged ID, use the jQuery <a href="http://docs.jquery.com/Selectors/attributeEndsWith#attributevalue">AttributeEndsWith</a> selector. This selector finds all elements where the given ID ends with a specific value.</p>
<div class="sourceCodeHeading">Figure 3. Add this JavaScript to the content page.</div>
<div id="Id0402404966SourceCode" class="sourceCode">
<pre class="even"><span class="ln">  1</span><span class="code">&lt;script type=&quot;text/javascript&quot;&gt;</span></pre>
<pre class="odd"><span class="ln">  2</span><span class="code">    $( function() {</span></pre>
<pre class="even"><span class="ln">  3</span><span class="code">        $( &quot;input[ id$='textboxName']&quot; ).val( &quot;prove this.&quot; );</span></pre>
<pre class="odd"><span class="ln">  4</span><span class="code">    });</span></pre>
<pre class="even"><span class="ln">  5</span><span class="code">&lt;/script&gt;</span></pre>
</div>
<div class="sourceCodeFooter"><a id="Id0402404966SourceCodeToClipboard" class="copyLink" href="javascript:toggleLineNumbers( 'Id0402404966SourceCode' );">Show copy-friendly code</a></div>
</p>
<p>The example above selects the input element that ends with “textboxName” and sets its value to &#8216;”prove this.”</p>
<p>jQuery’s AttributeEndsWith performs a brute-force traversal of all of the tags specified (and applies a regular expression against the ending value provided) so this technique may have some potential performance issues, but my experience with it hasn’t shown any glaring degradation.</p>
<p>rp</p>
]]></content:encoded>
			<wfw:commentRss>http://rogerpence.com/blog/index.php/archives/263/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JavaScript: The Joe Walsh of programming languages</title>
		<link>http://rogerpence.com/blog/index.php/archives/97</link>
		<comments>http://rogerpence.com/blog/index.php/archives/97#comments</comments>
		<pubDate>Tue, 14 Jul 2009 16:21:11 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://rogerpence.com/blog/index.php/archives/97</guid>
		<description><![CDATA[When ASP.NET debuted one of the improvements it brought to Web development was the way in which it hid away lots of painful, aggravating JavaScript. For a long time we thought that was a virtue. None of us liked JavaScript back then. It was fiddly, hard-to-debug, and required (or at least seemed to require) black [...]]]></description>
			<content:encoded><![CDATA[<p>When ASP.NET debuted one of the improvements it brought to Web development was the way in which it hid away lots of painful, aggravating JavaScript. For a long time we thought that was a virtue. None of us liked JavaScript back then. It was fiddly, hard-to-debug, and required (or at least seemed to require) black magic incantations to work correctly.</p>
<p>Then along comes Ajax and does for JavaScript what the Eagles did for Joe Walsh. The promise of rich (or at least richer) user interfaces was quite alluring and that and better JavaScript-centric tools and books quickly made us reconsider JavaScript. While JavaScript still has warts and hairs, its singular role as the ubiquitous browser programming language trumps those problems. JavaScript is clearly with us for the long haul. Understand this:<em>If you don’t know JavaScript, you aren’t a Web developer!</em> There is no avoiding the importance and impact of JavaScript. It is very important to at least achieve an intermediate level of JavaScript if you intend to write browser-based applications.</p>
<p>As ubiquitous as JavaScript is, I often bump into very bright VB and C# coders who don’t know much about JavaScript. This is the first is a series of articles that explains JavaScript for VB and C# programmers. I’m not going to try to provide the definitive JavaScript tutorial; the Internet doesn’t need another one of those. There tons of great JavaScript resources available (see the reference links at the end of this post). What I am going to present in this series a few JavaScript basics that have helped me. I’ll also introduce you to some JavaScript tools and techniques that work well for me.</p>
<h3>Elusive language</h3>
<p>For a VB or C# coder, JavaScript is a sneaky, elusive language. Syntactically, it grows from the same curly-brace, semi-coloned roots that C#, C, and even Java does. However, to master JavaScript you quickly need to learn that JavaScript is very much a different language than either C# or VB. The differences are subtle because JavaScript, especially the JavaScript written by rookie JavaScript coders, can indeed behave very much like imperative C# or VB. But, as we’ll see, behind the JavaScript curtain lurks some functional aspects that are very powerful, but easy to overlook. We’ll get to those later; let’s first focus on a few basics.</p>
<p>For the purposes of these posts, I’m going to assume at least a passing syntactical knowledge of C#. If you’re a VB coder with minimal or no C# knowledge, the examples I’ll provide here should be short enough that you’ll be able to intuitively grok the syntax.</p>
<h3>Dynamic typing</h3>
<p>Let’s start first with a simple JavaScript example. Figure 1 below shows a simple JavaScript function that apparently returns the sum of two numeric values. And indeed it does if both arguments passed to it are numeric values. With this code, you can quickly see the initial syntactical similarity that JavaScript has to C# and Java.</p>
<div class="sourceCodeHeading">Figure 1. A simple JavaScript example</div>
<div id="Id1046408029SourceCode" class="sourceCode">
<pre class="even"><span class="ln">  1</span><span class="code">var z = sum( 4, 8 );</span></pre>
<pre class="odd"><span class="ln">  2</span><span class="code"></span></pre>
<pre class="even"><span class="ln">  3</span><span class="code">function sum( value1, value2 )</span></pre>
<pre class="odd"><span class="ln">  4</span><span class="code">{</span></pre>
<pre class="even"><span class="ln">  5</span><span class="code">    return value1 + value2;</span></pre>
<pre class="odd"><span class="ln">  6</span><span class="code">}</span></pre>
</div>
<div class="sourceCodeFooter"><a id="Id1046408029SourceCodeToClipboard" class="copyLink" href="javascript:toggleLineNumbers( 'Id1046408029SourceCode' );">Show copy-friendly code</a></div>
<p>However, unlike VB and C#, JavaScript is dynamically typed. As such, notice that in the code in Figure 1 JavaScript types aren’t explicitly declared for any variables or functions. Neither <em>z</em>, nor <em>value1</em>, <em>value2 </em>nor even the type that is returned by <em>sum() </em>are, or can be, declared. Note that .NET 3.5’s C# and VB’s <em>var</em> keyword, despite its looks, <em>does</em> statically type a variable. JavaScript is doing no such thing with its <em>var</em>. JavaScript’s <em>var</em> is truly dynamically. Given JavaScript’s dynamic typing, <em>z</em> can be a numeric value but then later be a string, as shown below in Figure 2:</p>
<div class="sourceCodeHeading">Figure 2. JavaScript is dynamically typed</div>
<div id="Id0119172187SourceCode" class="sourceCode">
<pre class="even"><span class="ln">  1</span><span class="code"> z = sum( 4, 8 );</span></pre>
<pre class="odd"><span class="ln">  2</span><span class="code"></span></pre>
<pre class="even"><span class="ln">  3</span><span class="code"> z = “Neil” </span></pre>
</div>
<div class="sourceCodeFooter"><a id="Id0119172187SourceCodeToClipboard" class="copyLink" href="javascript:toggleLineNumbers( 'Id0119172187SourceCode' );">Show copy-friendly code</a></div>
<p>Give this dynamic typing, it’s possible to call <em>sum()</em> with arguments of types other than numeric as shown below in Figure 3:</p>
<div class="sourceCodeHeading">Figure 3. Sum()&#8217;s arguments aren&#8217;t explicitly typed</div>
<div id="Id0120190468SourceCode" class="sourceCode">
<pre class="even"><span class="ln">  1</span><span class="code">var z = sum( “Neil”, “Young” );</span></pre>
</div>
<div class="sourceCodeFooter"><a id="Id0120190468SourceCodeToClipboard" class="copyLink" href="javascript:toggleLineNumbers( 'Id0120190468SourceCode' );">Show copy-friendly code</a></div>
<p>The call in Figure 3 returns the concatenated result “NeilYoung.” JavaScript would even let you call sum() as shown below in Figure 4:</p>
<div class="sourceCodeHeading">Figure 4. Dynamic typing in action again</div>
<div id="Id0121055000SourceCode" class="sourceCode">
<pre class="even"><span class="ln">  1</span><span class="code">var z = sum( “Neil”, 8 ); </span></pre>
</div>
<div class="sourceCodeFooter"><a id="Id0121055000SourceCodeToClipboard" class="copyLink" href="javascript:toggleLineNumbers( 'Id0121055000SourceCode' );">Show copy-friendly code</a></div>
<p>where the result would be “Neil8.” Interesting, huh? JavaScript has the innate ability to dynamically coerce types when necessary. In the case of Figure 4 above, the numeric value 8 is coerced to string to produce the concatenated string result. But wait, it gets more interesting. Guess the result of Figure 5 below:</p>
<div class="sourceCodeHeading">Figure 5. Dynamic typing in action</div>
<div id="Id0122117812SourceCode" class="sourceCode">
<pre class="even"><span class="ln">  1</span><span class="code">var z = sum( “6”, 8 );</span></pre>
</div>
<div class="sourceCodeFooter"><a id="Id0122117812SourceCodeToClipboard" class="copyLink" href="javascript:toggleLineNumbers( 'Id0122117812SourceCode' );">Show copy-friendly code</a></div>
<p>That’s right, it’s “68.” Now, guess the result of Figure 6 below; it’s a little trickier:</p>
<div class="sourceCodeHeading">Figure 6. Attempting explicit casting</div>
<div id="Id0123095625SourceCode" class="sourceCode">
<pre class="even"><span class="ln">  1</span><span class="code">var z = sum( 0 + “6”, 8 );</span></pre>
</div>
<div class="sourceCodeFooter"><a id="Id0123095625SourceCodeToClipboard" class="copyLink" href="javascript:toggleLineNumbers( 'Id0123095625SourceCode' );">Show copy-friendly code</a></div>
<p>In this case, the result is “068.” As I was learning this, I would have bet you a paycheck that the 0 + “6” would have resulted in a coerced numeric value of 6, but that isn’t the case. Like VB and C#, the + sign means either arithmetic addition or string concatenation. If there is a string somewhere in the expression, JavaScript always assumes the + sign means string concentration. Getting sneakier, consider the output of Figure 5 below:</p>
<div class="sourceCodeHeading">Figure 7. A way to explicitly cast a string to numeric value</div>
<div id="Id0123503593SourceCode" class="sourceCode">
<pre class="even"><span class="ln">  1</span><span class="code">var z = sum( 1 * “6”, 8 );</span></pre>
</div>
<div class="sourceCodeFooter"><a id="Id0123503593SourceCodeToClipboard" class="copyLink" href="javascript:toggleLineNumbers( 'Id0123503593SourceCode' );">Show copy-friendly code</a></div>
<p>In this case, because the * sign has only one meaning, arithmetic multiplication, the 1 * “6” does indeed get coerced to the numeric value 6 and the result of calling <em>sum() </em>as shown in Figure 7 is the numeric value 14. If you try an arithmetic operation against the wrong type (eg, 1 * “A”) then JavaScript returns a special value named <em>“NaN”</em> indicating that the operation couldn’t be performed on non-numeric values. I’ll discuss <em>NaN</em> later in a post about JavaScript error handling.</p>
<p>We’ll see later that JavaScript has a few other explicit type conversion options available to it. We’ll also see that JavaScript has the ability to test the types of variables so that you can build in a little type-safe protection when it’s needed. Note though, the impact that JavaScript’s dynamic typing has on function naming. The name sum() for the function above (at least as it is currently written) is a poor name for that function because it can do more than just the numeric operation implied by the name “sum().”</p>
<h3>Unusual variable scoping</h3>
<p>Variable scoping in JavaScript has two levels to it: an easy, pretty obvious level and another richer but more complex level. This second level has to do with JavaScript closures. Closures are beyond the scope of this post, but will be covered in another later. For now let’s consider the basic implementation of JavaScript variable scoping.</p>
<p>When you declare a variable with JavaScript, the var keyword is optional (although is should be required!). For example, Figure 8 below declares variable x</p>
<div class="sourceCodeHeading">Figure 8. Declaring a variable with the var keyword</div>
<div id="Id0155151849SourceCode" class="sourceCode">
<pre class="even"><span class="ln">  1</span><span class="code">var x = 89;</span></pre>
</div>
<div class="sourceCodeFooter"><a id="Id0155151849SourceCodeToClipboard" class="copyLink" href="javascript:toggleLineNumbers( 'Id0155151849SourceCode' );">Show copy-friendly code</a></div>
<p>as does the line below in Figure 9:</p>
<div class="sourceCodeHeading">Figure 9. Declaring a variable without the var keyword</div>
<div id="Id0155368888SourceCode" class="sourceCode">
<pre class="even"><span class="ln">  1</span><span class="code">x = 89;</span></pre>
</div>
<div class="sourceCodeFooter"><a id="Id0155368888SourceCodeToClipboard" class="copyLink" href="javascript:toggleLineNumbers( 'Id0155368888SourceCode' );">Show copy-friendly code</a></div>
<p>Both lines declare a variable x, but there is a difference. When you use var to declare a variable, that variable is scoped either globally to all functions (if it’s declared outside of any functions) or scoped to the function in which it’s declared. Let’s look at a few more examples. If you omit the var keyword, you are implicitly creating a global variable—regardless of where the declaration takes place. I’ll get back to this in a minute—but let it register now that declaring a variable in JavaScript without var is generally a very bad thing to do! </p>
<p>Figure 10 below shows a global variable x being declared. Because x isn’t owned by a function, its value is available anywhere. Remember, too, that global Javascript variables are available to all other JavaScript files used by any one page. Global truly means global in this case.</p>
<p>The example below shows x being assigned to the scopeTest()’s variable y which, because the var keyword is used, is available only inside scopeTest().</p>
<div class="sourceCodeHeading">Figure 10. Declaring a variable outside the bounds of functions</div>
<div id="Id0156254532SourceCode" class="sourceCode">
<pre class="even"><span class="ln">  1</span><span class="code">var x = 89;</span></pre>
<pre class="odd"><span class="ln">  2</span><span class="code"></span></pre>
<pre class="even"><span class="ln">  3</span><span class="code">function scopeTest()</span></pre>
<pre class="odd"><span class="ln">  4</span><span class="code">{</span></pre>
<pre class="even"><span class="ln">  5</span><span class="code">    var y = x;</span></pre>
<pre class="odd"><span class="ln">  6</span><span class="code">}</span></pre>
</div>
<div class="sourceCodeFooter"><a id="Id0156254532SourceCodeToClipboard" class="copyLink" href="javascript:toggleLineNumbers( 'Id0156254532SourceCode' );">Show copy-friendly code</a></div>
<p>Because x is global by virtual of not being declared inside a function, the use of var in line 1 in Figure 10 above is option. Had line 1 omitted the var keyword, the behavior in Figure 10 would not have changed. Having said that, the var keyword doesn’t change the global behavior (because x is declared outside the bounds of any functions); you should <em>always</em> use the var keyword.</p>
<p>If the code in Figure 10 were written as shown below in Figure 11, the variable y declared in scopeTest() is global (because it isn’t declared with the var keyword). The interesting thing about the y variable is that it isn’t available to the rest of the program until scopeTest() has been called once. Therefore, the code below will fail at line 3 (where writeLine() is a diagnostic function to display a variable we’ll discuss later) because testScope() hasn’t yet been called.</p>
<div class="sourceCodeHeading">Figure 11. declaring a global variable in a function</div>
<div id="Id0158084415SourceCode" class="sourceCode">
<pre class="even"><span class="ln">  1</span><span class="code">var x = 89;</span></pre>
<pre class="odd"><span class="ln">  2</span><span class="code"></span></pre>
<pre class="even"><span class="ln">  3</span><span class="code">writeLine( y ) </span></pre>
<pre class="odd"><span class="ln">  4</span><span class="code"></span></pre>
<pre class="even"><span class="ln">  5</span><span class="code">function scopeTest()</span></pre>
<pre class="odd"><span class="ln">  6</span><span class="code">{</span></pre>
<pre class="even"><span class="ln">  7</span><span class="code">    y = x;</span></pre>
<pre class="odd"><span class="ln">  8</span><span class="code">}</span></pre>
</div>
<div class="sourceCodeFooter"><a id="Id0158084415SourceCodeToClipboard" class="copyLink" href="javascript:toggleLineNumbers( 'Id0158084415SourceCode' );">Show copy-friendly code</a></div>
<p>However, anytime after a call is made to testScope(), then the global variable y it declared is available to the rest of the JavaScript program. Figure 12 below will now correctly display the value of the global variable y.</p>
<div class="sourceCodeHeading">Figure 12.Referencing y</div>
<div id="Id0159212408SourceCode" class="sourceCode">
<pre class="even"><span class="ln">  1</span><span class="code">var x = 89;</span></pre>
<pre class="odd"><span class="ln">  2</span><span class="code"></span></pre>
<pre class="even"><span class="ln">  3</span><span class="code">scopeTest();</span></pre>
<pre class="odd"><span class="ln">  4</span><span class="code"></span></pre>
<pre class="even"><span class="ln">  5</span><span class="code">writeLine( y );</span></pre>
<pre class="odd"><span class="ln">  6</span><span class="code"></span></pre>
<pre class="even"><span class="ln">  7</span><span class="code">function scopeTest()</span></pre>
<pre class="odd"><span class="ln">  8</span><span class="code">{</span></pre>
<pre class="even"><span class="ln">  9</span><span class="code">    y = x;</span></pre>
<pre class="odd"><span class="ln"> 10</span><span class="code">}</span></pre>
</div>
<div class="sourceCodeFooter"><a id="Id0159212408SourceCodeToClipboard" class="copyLink" href="javascript:toggleLineNumbers( 'Id0159212408SourceCode' );">Show copy-friendly code</a></div>
<h3>JavaScript variables are not block-scoped</h3>
<p>Remember that variables are<em> not</em> blocked scoped in JavaScript like they are in C# or Java; rather in JavaScript variables declared in a function are scoped to all of the code in that function. Therefore, what appears as though it should be a variable private to the if block below is really available from where it’s declared on down in the function. Figure 12 below shows this.</p>
<div class="sourceCodeHeading">Figure 12. JavaScript local variables are block-scoped</div>
<div id="Id0201152757SourceCode" class="sourceCode">
<pre class="even"><span class="ln">  1</span><span class="code">function scopeTest()</span></pre>
<pre class="even"><span class="ln">  2</span><span class="code">{</span></pre>
<pre class="odd"><span class="ln">  3</span><span class="code">    // Variable x is undefined here.</span></pre>
<pre class="even"><span class="ln">  4</span><span class="code">    if ( condition )</span></pre>
<pre class="odd"><span class="ln">  5</span><span class="code">    {</span></pre>
<pre class="even"><span class="ln">  6</span><span class="code">        // Variable x is available beyond the </span></pre>
<pre class="odd"><span class="ln">  7</span><span class="code">        // if block’s scope. </span></pre>
<pre class="even"><span class="ln">  8</span><span class="code">        var x = 89;</span></pre>
<pre class="odd"><span class="ln">  9</span><span class="code">    }</span></pre>
<pre class="even"><span class="ln"> 10</span><span class="code">    // Variable x is available here!</span></pre>
<pre class="odd"><span class="ln"> 11</span><span class="code">}</span></pre>
</div>
<div class="sourceCodeFooter"><a id="Id0201152757SourceCodeToClipboard" class="copyLink" href="javascript:toggleLineNumbers( 'Id0201152757SourceCode' );">Show copy-friendly code</a></div>
<p>As you can imagine, bad things can happen when you omit the var keyword. The general rule of this is don’t ever omit it! If a variable needs to be global, don’t declare it inside a function, declare as an inline variable. Note also that the dynamic nature of JavaScript can get you in big trouble quickly if you aren’t vigilant. Consider the code below in Figure 13:</p>
<div class="sourceCodeHeading">Figure 13. JavaScript doesn&#8217;t have Option Explicit!</div>
<div id="Id0202000427SourceCode" class="sourceCode">
<pre class="even"><span class="ln">  1</span><span class="code">Function scopeTest()</span></pre>
<pre class="odd"><span class="ln">  2</span><span class="code">{</span></pre>
<pre class="even"><span class="ln">  3</span><span class="code">    var myRate = 89;</span></pre>
<pre class="odd"><span class="ln">  4</span><span class="code">    Myrate = myRate + 100;</span></pre>
<pre class="even"><span class="ln">  5</span><span class="code">}</span></pre>
</div>
<div class="sourceCodeFooter"><a id="Id0202000427SourceCodeToClipboard" class="copyLink" href="javascript:toggleLineNumbers( 'Id0202000427SourceCode' );">Show copy-friendly code</a></div>
<p>In this case, I meant to increment the value of myRate by 100. However, I got the case wrong on line 2 spelling Myrate instead of myRate. So, without any fanfare, JavaScript sees that not as an error, but rather as my desire to declare a second global variable named Myrate. Not only was myRate not incremented as needed but I also got a free global variable out of the mistake. And, this is important, myRate has an incorrect value with JavaScript providing no clues as to anything being amiss.</p>
<p>For my money, the ease with which a coder can make such a simple, profound mistake is why JavaScript got a bad name in the first place. You must always be aware of case. If JavaScript had an option explicit-like setting like VB does (disallowing variable declarations without the var keyword), we’d be protected against such boneheaded, but certainly possible, errors.</p>
<p>While there isn’t anything built into JavaScript to help you avoid these errors, there is a superb online JavaScript utility called <a href="http://jslint.com">JSLint</a> you can use to screen your code for such errors. JSLint investigates your JavaScript and reports lots of information about it. One of the things it reports is the sloppy use of variables as shown in Figure 13. For JavaScript work of any real merit, the use of JSLint is highly recommended.</p>
<p>The lesson learned: take great care with your JavaScript variable scope and naming and watch your case.</p>
]]></content:encoded>
			<wfw:commentRss>http://rogerpence.com/blog/index.php/archives/97/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Great resources to help you learn JavaScript</title>
		<link>http://rogerpence.com/blog/index.php/archives/116</link>
		<comments>http://rogerpence.com/blog/index.php/archives/116#comments</comments>
		<pubDate>Fri, 15 May 2009 05:08:35 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Web development]]></category>

		<guid isPermaLink="false">http://rogerpence.com/blog/index.php/archives/116</guid>
		<description><![CDATA[Here are some of my favorite and most frequently-used resources for learning JavaScript. I’ll update this list on a recurring basis.



Resource
Description


JavaScript Tutorial
JavaScript Tutorial
JavaScript Reference Series
JavaScript Reference
JavaScript Closures

There are more online references and tutorials for JavaScript on the Web than there are naked pictures of Paris Hilton. To find them (the JavaScript stuff, you perv), you [...]]]></description>
			<content:encoded><![CDATA[<p>Here are some of my favorite and most frequently-used resources for learning JavaScript. I’ll update this list on a recurring basis.</p>
<table class="rpInfoTable" border="0" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<th width="167" valign="top">Resource</th>
<th width="414" valign="top">Description</th>
</tr>
<tr>
<td width="167" valign="top"><a href="http://www.w3schools.com/js/default.asp">JavaScript Tutorial</a><br />
<a href="http://www.javascriptkit.com/javatutors/index.shtml">JavaScript Tutorial</a><br />
<a href="http://www.hunlock.com/blogs/Essential_Javascript_--_A_Javascript_Tutorial">JavaScript Reference Series</a><br />
<a href="http://www.meb.uni-bonn.de/java/">JavaScript Reference</a><br />
<a href="http://blog.morrisjohns.com/javascript_closures_for_dummies">JavaScript Closures</a>
</td>
<td width="414" valign="top">There are more online references and tutorials for JavaScript on the Web than there are naked pictures of Paris Hilton. To find them (the JavaScript stuff, you perv), you only need a firm grasp of Google! Listed to the left are some of my favorites. Most of them speak for themselves. The first one, though, deserves special mention. Most readers will be familiar with it already, but for those of you who aren’t, be sure to bookmark <a href="http://www.w3schools.com/">W3Schools</a>. While it has great JavaScript info, it also has loads of other great Web development info.</td>
</tr>
<tr>
<td width="167" valign="top"><a href="http://jslint.com">JSLint</a></td>
<td width="414" valign="top">JSLint is an online JavaScript code quality tool. It investigates the JavaScript you paste into it and reports tons of information about it.  Perhaps the most important thing it reports is sloppy use of undefined variables. JSLint is the work of JavaScript Jedi <a href="http://www.crockford.com/">Douglas Crockford</a>. He promises that JSLint will hurt your feelings!</td>
</tr>
<tr>
<td width="167" valign="top"><a href="http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf" target="_blank">ECMAScript Language Specification</a></td>
<td width="414" valign="top">While no one but the official language spec committee calls JavaScript &#8220;ECMAScript,&#8221; this 188 page manual (it’s a PDF) is quite handy. It’s dry, and probably tells you a little more than you really want to know, but it its value, especially for free, as a JavaScript reference is superb.</td>
</tr>
<tr>
<td width="167" valign="top"><a href="http://getfirebug.com/">FireBug JavaScript debugger for FireFox</a><br />
<a href="http://blogs.msdn.com/jscript/archive/2008/03/13/jscript-debugger-in-internet-explorer-8.aspx">IE8 debugger</a><br />
<a href="http://www.opera.com/dragonfly/">Opera Dragonfly debugger</a></td>
<td width="414" valign="top">The combination of FireFox and Firebug has probably done more for learning and exploiting JavaScript than all of the JavaScript books ever written. The synergy of the two actually make writing JavaScript fun—and that’s an elusive word association. Both IE8 and Opera also now both offer intrinsic JavaScript debuggers that, while not as good as FireBug, are quite a step forward for these two browsers.</td>
</tr>
<tr>
<td width="167" valign="top"><a href="http://jquery.com">jQuery</a></td>
<td width="414" valign="top">This isn’t just a superb JavaScript library&#8211;it&#8217;s a JavaScript game changer. Using it will improve, vastly for the better, the way you write JavaScript. The decision tree for determining if you should use jQuery is very simple: do you write JavaScript? If yes, you need jQuery.</td>
</tr>
<tr>
<td width="167" valign="top"><a href="http://javascript.crockford.com/code.html" >JavaScript style guide</a></td>
<td width="414" valign="top">JavaScript coding conventions per Crockford.</td>
</tr>
<tr>
<td width="167" valign="top"><a href="http://search.yahoo.com/search?va=crockford&amp;vs=developer.yahoo.com&amp;vs=developer.yahoo.net">Douglas Crockford JavaScript videos</a></td>
<td width="414" valign="top">Douglas Crockford has made several videos about JavaScript and they are very enlightening. There is a series on JavaScript and then one on advanced JavaScript. Also, do an <a href="http://www.google.com/search?hl=en&amp;as_q=crockford+javascript&amp;as_epq=&amp;as_oq=&amp;as_eq=&amp;num=10&amp;lr=&amp;as_filetype=ppt&amp;ft=i&amp;as_sitesearch=&amp;as_qdr=all&amp;as_rights=&amp;as_occt=any&amp;cr=&amp;as_nlo=&amp;as_nhi=&amp;safe=images" target="_blank">advanced Google search for Crockford’s JavaScript PowerPoints</a>—they are terrific.<br/><br />
On a slightly related note, to hear ten or so of the most awkward <a href="http://www.dotnetrocks.com/">DotNetRocks</a> minutes ever, give a listen to <a href="http://www.dotnetrocks.com/default.aspx?showNum=422" target="_blank">Carl and Richard welcoming Douglas to their show #422</a>. Listen for a couple of minutes about 9 minutes into the Podcast. Richard&#8217;s uncomfortable laughter will make you cringe and Carl trying to explain away his Wierd Al reference draws dead air. I’m generally a big fan of DNR, but this interview had me wishing for a flat tire on my way to work just for an excuse to stop listening. An opportunity to interview a JavaScript god was completely pissed away. To Carl and Richard&#8217;s credit, Crockford does come across as a bit of a mooncat. He remains pretty much disengaged throughout the entire interview.</td>
</tr>
<tr>
<td width="167" valign="top"><a href="http://www.amazon.com/s/ref=nb_ss_b_0_9?url=search-alias%3Dstripbooks&amp;field-keywords=headfirst+javascript&amp;sprefix=headfirst"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="headfirstjavascript" src="http://rogerpence.com/blog/wp-content/uploads/2009/05/headfirstjavascript1.jpg" border="0" alt="headfirstjavascript" width="187" height="215" /></a></td>
<td width="414" valign="top">This is a good JavaScript book for beginners. The Head First books flirt with being just a little too pretentious (they are a little like a Dummies book gone nearly right) but overall the info in the book overcomes some of its “mom made me a JavaScript scrapbook” impact.</td>
</tr>
<tr>
<td width="167" valign="top"><a href="http://www.amazon.com/s/ref=nb_ss_b_1_15?url=search-alias%3Dstripbooks&amp;field-keywords=javascript+the+good+parts&amp;sprefix=javascript+the+"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="javascript_the_good_parts" src="http://rogerpence.com/blog/wp-content/uploads/2009/05/javascript-the-good-parts.jpg" border="0" alt="javascript_the_good_parts" width="189" height="244" /></a></td>
<td width="414" valign="top">One more Crockford reference and I swear I’m done with him (for now). <em>JavaScript: The Good Parts</em> is a very good book on intermediate/advanced JavaScript. If you’re new to JavaScript, don’t make this your first book. But once you think you’ve got a a handle on JavaScript, this book will definitely ramp up your JavaScript knowledge more than one level.</td>
</tr>
</tbody>
</table>
]]></content:encoded>
			<wfw:commentRss>http://rogerpence.com/blog/index.php/archives/116/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
