<?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>David Calhoun&#039;s Developer Blog &#187; javascript</title>
	<atom:link href="http://davidbcalhoun.com/category/javascript/feed" rel="self" type="application/rss+xml" />
	<link>http://davidbcalhoun.com</link>
	<description>Just another blog</description>
	<lastBuildDate>Fri, 03 Feb 2012 01:29:09 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Different ways of defining functions in JavaScript (this is madness!)</title>
		<link>http://davidbcalhoun.com/2011/different-ways-of-defining-functions-in-javascript-this-is-madness</link>
		<comments>http://davidbcalhoun.com/2011/different-ways-of-defining-functions-in-javascript-this-is-madness#comments</comments>
		<pubDate>Fri, 24 Jun 2011 17:20:02 +0000</pubDate>
		<dc:creator>David</dc:creator>
				<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://davidbcalhoun.com/?p=709</guid>
		<description><![CDATA[This is madness! This&#8230; is&#8230; JavaScript! In JavaScript, there&#8217;s many different ways of doing something. This is both a good thing and a bad thing. To the newcomer this is definitely a bad thing, as it means not only more things to learn, but more little caveats and more places to go wrong. And so [...]]]></description>
			<content:encoded><![CDATA[<h3>This is madness!  This&#8230; is&#8230; JavaScript!</h3>
<p>In JavaScript, there&#8217;s many different ways of doing something.  This is both a good thing and a bad thing.  To the newcomer this is definitely a bad thing, as it means not only more things to learn, but more little caveats and more places to go wrong.  And so it is with declaring functions!</p>
<p>The aim of this is just an accessible tour of the landscape, just so you know what&#8217;s out there and what the basic differences are.  Do be sure to check out the &#8220;further reading&#8221; section as well!  Much of this is based on <a href="http://kangax.github.com/nfe/">Juriy &#8220;kangax&#8221; Zaytsev&#8217;s article</a>, which goes into more depth.  But I found that there wasn&#8217;t just one reference to show all the different variable declarations.</p>
<p>How about ways to execute functions?  That opens up another can of worms, and incidentally opens up the possibility for a future post on that topic.  <img src='http://davidbcalhoun.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h3>Overview: different ways of declaring functions</h3>
<pre name="code" class="jscript">
function A(){};             // function declaration
var B = function(){};       // function expression
var C = (function(){});     // function expression with grouping operators
var D = function foo(){};   // named function expression
var E = (function(){        // immediately-invoked function expression (IIFE) that returns a function
  return function(){}
})();
var F = new Function();     // Function constructor
var G = new function(){};   // special case: object constructor
</pre>
<h3>Function declarations: function A(){};</h3>
<p>Function declarations are probably the most familiar and oldest way of doing things in JavaScript land.  This creates a variable A which is accessible in the current scope.  Scope is a separate topic, so we&#8217;ll do everything in the global scope for all these examples (something you want to avoid usually).</p>
<h4>1. Hoisting</h4>
<p>The interesting thing about these is that they are &#8220;hoisted&#8221; to the top of their scope, which means this code:</p>
<pre name="code" class="jscript">
A();
function A(){
  console.log('foo');
};
</pre>
<p>Gets executed as this code:</p>
<pre name="code" class="jscript">
function A(){
  console.log('foo');
};
A();
</pre>
<p>Which practically means that, yes, you can call the functions before they&#8217;re written in your code.  It won&#8217;t matter, because the entire function gets hoisted to the top of its containing scope.  (This is contrasted with variables, which only have their declaration hoisted, not their contents, as we&#8217;ll see in the next section).</p>
<h4>2. No function declarations in <code>If</code> statements (or loops, etc)</h4>
<p>You can&#8217;t define functions this way in expressions, for example <code>if</code> statements, which is common if we want to define different versions of a function for different circumstances, usually to address browser inconsistencies.  Well, you <em>can</em> in some implementations, but the way the code is processed is inconsistent (kangax has documented the inconsistencies <a href="http://kangax.github.com/nfe/">here</a>).  If you want to use this pattern, use function expressions instead.</p>
<h4>3. Functions declarations must have names</h4>
<p>This method doesn&#8217;t allow you to create anonymous functions, meaning that you always have to give it an identifier (in this case we&#8217;ve used &#8220;A&#8221;).</p>
<h3>Function expressions: var B = function(){};</h3>
<p>A function expression looks similar to function declarations, except that the function is assigned to a variable name.  Though functions are not primitive values in JavaScript, this is the way they can be utilized to their full effect in this functional language.  Functions are &#8220;<a href="http://en.wikipedia.org/wiki/First-class_function">first class</a>&#8220;:</p>
<blockquote><p>&#8220;[JavaScript] supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures&#8221;</p></blockquote>
<h4>1. Anonymous functions (they don&#8217;t need names)</h4>
<p>The function name is optional in function expressions, and we call these anonymous.  Here we&#8217;re setting the variable B equal to an anonymous function:</p>
<pre name="code" class="jscript">
var B = function(){};
</pre>
<h4>2. Variable declaration hoisting</h4>
<p>Variable declarations are hoisted to the top of their scope, somewhat similarly to function hoisting <em>except</em> the contents of the variable are not hoisted as well.  This happens with all variables, and it means it&#8217;s now happening with our functions, now that we&#8217;re assigning them to variables.</p>
<p>This code:</p>
<pre name="code" class="jscript">
var A = function(){};
var B = function(){};
var C = function(){};
</pre>
<p>Will be executed as this:</p>
<pre name="code" class="jscript">
var A, B, C;  // variable declarations are hoisted
A = function(){};
B = function(){};
C = function(){};
</pre>
<p>Therefore the order of setting and calling this type of function is important:</p>
<pre name="code" class="jscript">
// this works
var B = function(){};
B();

// this doesn't work
B2();  // TypeError (B2 is undefined)
var B2 = function(){};
</pre>
<p>The second example gives us an error because only the variable B2&#8242;s declaration is hoisted, but not its definition, thus the &#8220;undefined&#8221; error.</p>
<h3>Function expressions with grouping operators: var C = (function(){});</h3>
<p>These really aren&#8217;t different from plain old function expressions and aren&#8217;t really seen in the wild (so maybe they&#8217;re just good for JavaScript quizzes?).  Recently this way of declaring functions was brought up in <a href="http://ironjs.wordpress.com/2011/06/22/my-gripes-with-javascript/">this article</a> and confused some folks including myself.</p>
<p>Here&#8217;s a good way to see what&#8217;s happening:</p>
<pre name="code" class="jscript">
function(){};  // SyntaxError
(function(){});
</pre>
<p>Why does one work and the other doesn&#8217;t?  The first example is a function declaration, and we learned above that we can&#8217;t declare them anonymously &#8211; that is, they must have a name.  That&#8217;s why we&#8217;re getting the syntax error.</p>
<p>The second example is using parenthesis &#8211; grouping operators &#8211; and is therefore evaluated differently, as a function expression.  The grouping operators are the things we use to help show what should be evaluated first, as in mathematical problems.  We&#8217;re saying &#8220;evaluate this first, then take the result and do something with it&#8221;:</p>
<pre name="code" class="jscript">
(1 + 2) * 3;  // 9
1 + (2 * 3);  // 7
</pre>
<p>In the first example we&#8217;re saying &#8220;first add 1 and 2, then take the result and multiply by 3&#8243;, whereas in the second example we&#8217;re saying &#8220;first multiply 2 and 3, then take the result and add 1&#8243;.</p>
<p>Because functions are first class, we can use similar grouping operators.  Here&#8217;s a facetious example, but it shows how we can essentially drop in a function in the same way:</p>
<pre name="code" class="jscript">
(function(){} + 1);  // function(){}1
</pre>
<p>The result is a string (because toString is being called on the function, then added/appended with 1), but you get the idea I hope.</p>
<p>When the JavaScript engine encounters the opening parenthesis here, we&#8217;re essentially saying &#8220;ok, start grouping this together with something else&#8221;.  Using our technical terms, we&#8217;re telling the engine that we&#8217;re not making a function declaration, but instead a function expression.  And then we can assign the result to a variable:</p>
<pre name="code" class="jscript">
(function(){});           // resulting function not assigned
var foo = (function(){}); // resulting function assigned to foo
var bar = function(){};   // resulting function assigned to bar
</pre>
<p>Here we can see that foo and bar are really just the same, because in foo we&#8217;re not grouping the function together with anything but itself.</p>
<h3>Named function expression: var D = function foo(){};</h3>
<p>Here we have our same old friend, the function expression.  But instead of assigning the variable to an anonymous function, we&#8217;re assigning it to a named function (with the name foo).</p>
<h4>1. The function name is only accessible within the function</h4>
<p>We haven&#8217;t exposed the function name (foo) to the enclosing scope (in this case the global scope):</p>
<pre name="code" class="jscript">
var D = function foo(){
  console.log(typeof foo);
};
D();                       // function
console.log(typeof foo);   // undefined
</pre>
<h4>2. Useful for recursion</h4>
<p>Because the function&#8217;s name is accessible in the function itself, this turns out to be useful for recursive functions, much more useful than the plain old anonymous function.</p>
<p>Here&#8217;s a trivial recursive function to illustrate calling itself from within the named function expression:</p>
<pre name="code" class="jscript">
var countdown = function a(count){
  if(count > 0) {
    count--;
    return a(count);  // we can also do this: a(--count), which is less clear
  }
  console.log('end of recursive function');
}
countdown(5);
</pre>
<h4>3. Useful for debugging</h4>
<p>As a <a href="http://kangax.github.com/nfe/">few</a> <a href="http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/">have</a> pointed out, giving previously anonymous functions names helps in debugging, since the function name shows up on the call stack.</p>
<h4>4. Quirks: JScript&#8217;s bad implementation</h4>
<p><a href="http://kangax.github.com/nfe/">kangax</a> points out that named function expressions are basically poison to JScript, Internet Explorer&#8217;s implementation of JavaScript.</p>
<p>The named function becomes a global variable, is hoisted like a function declaration, and actually ends up creating multiple instances of the same function.</p>
<h3>Immediately-invoked function expressions (IIFE): var E = (function(){return function(){}})();</h3>
<p>&#8220;Execute this function, whose return value is another function, and assign that to the variable E&#8221;.  This may seem like magic, but it&#8217;s actually quite simple, and the pattern is powerful and has useful applications, the most famous of which is the <a href="http://www.klauskomenda.com/code/javascript-programming-patterns/#module">module pattern</a>.</p>
<p>First we&#8217;ll use an example that doesn&#8217;t look like magic:</p>
<pre name="code" class="jscript">
var foo = function(){
  return 'bar';
};
var output = foo();
console.log(output);  // 'bar'
</pre>
<p>We already learned about grouping operators above, so you should feel comfortable with saying this is equivalent:</p>
<pre name="code" class="jscript">
var foo = function(){
  return 'bar';
};
var output = (foo)(); // note the extra grouping operators
console.log(output);  // 'bar'
</pre>
<p>Since foo is pointing to our function expression, we know that we can simply refrain from using the variable &#8220;foo&#8221; and drop in the entire function as an anonymous function (since functions are first class, after all!):</p>
<pre name="code" class="jscript">
var output = (function(){
  return 'bar';
})();
console.log(output);  // 'bar'
</pre>
<p>Hey wait, we just arrived at the magical resulting function!  It turns out to be not so magical after all, once we break it down and see it for what it is.  It&#8217;s simply shorthand for the code we wrote originally, where we defined a function, executed it, and defined output to be its return value.</p>
<p>I&#8217;ve included this method on the list of declaring functions because we can assign the return value to itself be a function:</p>
<pre name="code" class="jscript">
var E = (function(){
  return function(){}
})();
</pre>
<h4>Applications</h4>
<p>There are good applications for this, including information hiding using in the module pattern, (<a href="http://ejohn.org/blog/partial-functions-in-javascript/">partial application</a>, for example), and other clever uses of it.  It&#8217;s definitely not a trivial pattern.</p>
<h3>Function constructor: var F = new Function();</h3>
<p>This method is extremely old and it&#8217;s not recommended to be used.  You pass in an unlimited number of arguments in the front, then the actual function body appears as a string in the last argument (because it&#8217;s a string, it&#8217;s effectively the equivalent of eval(), and isn&#8217;t recommended).</p>
<h4>1. Defining the function</h4>
<p>You can create a function like this:</p>
<pre name="code" class="jscript">
var F = new Function('arg1', 'arg2', 'console.log(arg1 + ", " + arg2)');
F('foo', 'bar');  // 'foo, bar'
</pre>
<h4>2. You don&#8217;t need the <code>new</code> operator</h4>
<p>You can simply write <code>var F = Function();</code> to get the same result.</p>
<h4>3. Quirks</h4>
<p>The <a href="https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope#Function_constructor_vs._function_declaration_vs._function_expression">MDN docs</a> have some good examples of the quirks, including the fact that functions declared with the Function constructor don&#8217;t inherit their current scope properly (i.e. a closure isn&#8217;t formed).</p>
<p>What this means is that they don&#8217;t have access to variables in their enclosing scope, which isn&#8217;t particularly useful:</p>
<pre name="code" class="jscript">
function foo(){
  var bar = 'blah';

  var first = new Function('console.log(typeof bar)');
  first();   // undefined

  var second = function(){
    console.log(typeof bar);
  }
  second();  // string
}
foo();
</pre>
<p>In the function &#8220;first&#8221;, we&#8217;re using the Function constructor, so it doesn&#8217;t have access to the variable bar.  However, if we use the function &#8220;second&#8221;, which is a function expression, it does in fact have access to variables defined in its enclosing scope (via closure).</p>
<p>In other words, <em>don&#8217;t use the Function constructor</em>.</p>
<h3>Special case &#8211; object constructor: var G = new function foo(){};</h3>
<p>I saved this for last because we&#8217;re not really defining a function, though we are using the function keyword, so it&#8217;s worth noting at least.</p>
<p><code>new function(){};</code> creates a new object and invokes the anonymous function as its constructor.  If an object is returned from the function, that becomes the resulting object, otherwise a new object is created from scratch and function is executed in the context of that new function (let&#8217;s save the details for another post!).</p>
<p>It&#8217;s a bit unusual to see it in this form.  Let&#8217;s do it the proper way:</p>
<pre name="code" class="jscript">
var Person = function(){
  console.log(this);  // Person
}
var joe = new Person();
</pre>
<p>So really with the new operator, we are giving it a new &#8216;this&#8217; context and then executing the given function with that new context.  Much different than the function definitions we&#8217;ve been dealing with above!  This does into a whole new topic, and we&#8217;ll save that for later!</p>
<h3>Further reading</h3>
<p><a href="http://kangax.github.com/nfe/">Named function expressions demystified</a> (kangax)</p>
<p><a href="http://benalman.com/news/2010/11/immediately-invoked-function-expression/">Immediately-Invoked Function Expression (IIFE) (Ben Alman)</a></p>
<p><a href="https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope">Functions and function scope</a> (Mozilla Developer Network &#8211; MDN)</p>
<p><a href="http://stackoverflow.com/questions/1140089/how-does-an-anonymous-function-in-javascript-work">How does an anonymous function in JavaScript work? (StackOverflow)</a></p>
<p><a href="http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/">Function Declarations vs. Function Expressions (JavaScript, JavaScript by Angus Croll)</a></p>
<p><a href="http://www.amazon.com/gp/product/0596805527/">JavaScript: The Definitive Guide</a> (classic book by David Flanagan)</p>
]]></content:encoded>
			<wfw:commentRss>http://davidbcalhoun.com/2011/different-ways-of-defining-functions-in-javascript-this-is-madness/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Checking for undefined, null, and empty variables in JavaScript</title>
		<link>http://davidbcalhoun.com/2011/checking-for-undefined-null-and-empty-variables-in-javascript</link>
		<comments>http://davidbcalhoun.com/2011/checking-for-undefined-null-and-empty-variables-in-javascript#comments</comments>
		<pubDate>Fri, 11 Feb 2011 07:16:33 +0000</pubDate>
		<dc:creator>David</dc:creator>
				<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://davidbcalhoun.com/?p=631</guid>
		<description><![CDATA[In general it&#8217;s a good practice to check for the existence of something before blindly using it by faith and hoping it works. There are various times during the execution of scripts when a variable may not be defined, it may be null, or it might be an empty string. These are three things that [...]]]></description>
			<content:encoded><![CDATA[<p>In general it&#8217;s a good practice to check for the existence of something before blindly using it by faith and hoping it works.  There are various times during the execution of scripts when a variable may not be defined, it may be null, or it might be an empty string.  These are three things that are easily conflated.  A good way to look at this is thinking of these as having increasing levels of existence (getting a bit philosophical here for a moment&#8230;):</p>
<pre name="code" class="JScript">
foo0;             // existence level 0 (creates the error "not defined")
var foo1;         // existence level 1 ("undefined" - variable declared but not defined/initialized)
var foo2 = null;  // existence level 2 (variable initialized, but isn't an Object, Number, String, etc)
var foo3 = "";    // existence level 3 (variable initialized to an empty String)
var foo4 = "bar"; // existence level 4 (variable initialized to String "foo")
</pre>
<p>Generally it would be handy if we had some way to filter out everything but the very last line.  We simply want to check for these cases without the script entirely blowing up, as it does with the first line:</p>
<pre name="code" class="JScript">
foo;  // ReferenceError: foo is not defined
</pre>
<p>We&#8217;re not particularly doing anything useful with foo here, but notice that the script fails out anyway.  At this point any code that follows will not be executed.  Your first instinct might be &#8220;Oh!  I know how to contain these errors!  We&#8217;ll use a try-catch!&#8221;:</p>
<pre name="code" class="JScript">
try {
  foo;
} catch(e) {
  e.message;  // "foo is not defined"
}
</pre>
<p>The script still fails, but not critically, so your script continues to execute.  But this turns out to aversely affect performance.  The basic lesson here is that try-catch can be useful in some situations, but shouldn&#8217;t be used where alternatives are available.</p>
<h3>typeof foo</h3>
<p>JavaScript has quite a useful remedy for this:</p>
<pre name="code" class="JScript">
typeof foo; // "undefined"
</pre>
<p>Unlike everything else in JavaScript, typeof will deal with whatever you throw at it, including undefined variables.  So you can use it as a simple check before using a variable that might not exist:</p>
<pre name="code" class="JScript">
if(typeof foo !== "undefined") {
  // do something with foo
}
</pre>
<p>Note that this is easy to confuse with the <code>undefined</code> keyword, which in this case doesn&#8217;t help us one bit, as it gives us a fatal error:</p>
<pre name="code" class="JScript">
if(foo !== undefined) {  // ReferenceError: foo is not defined

}
</pre>
<p>This filters out our first two cases, since they both evaluate to &#8220;undefined&#8221;:</p>
<pre name="code" class="JScript">
typeof foo; // "undefined"

var bar;
typeof bar; // "undefined"
</pre>
<p>But this turns out not to work well for our other conditions, which evaluate differently:</p>
<pre name="code" class="JScript">
typeof null;  // "object" (what?!)
typeof "";    // "string"
</pre>
<p>So we need to add other &#8220;if&#8221; conditions to check.. but there turns out to be a better way!</p>
<h3>Exploiting loose typing</h3>
<p>JavaScript is a loosely typed language, which means that it will &#8220;automagically&#8221; cast variables into other types when necessary (i.e. when adding a Number to a String), sometimes resulting in the unexpected.  For instance, whenever we use the &#8220;if&#8221; statement, the expected input is a Boolean true/false value.  If JavaScript gets anything other than a Boolean, such as a String or a Number, instead of blowing up completely (as in strictly typed languages such as C), it&#8217;ll cast the variable into a Boolean for you.</p>
<p>&#8220;How handy!&#8221; you might think.  Except in the following unexpected cases:</p>
<pre name="code" class="JScript">
if("0") {
  // this will run because "0" is true
}

if("false") {
  // this will run because "false" is true
}
</pre>
<p>To see what JavaScript will cast a value to without having to use an <code>if</code> statement, we could create a new Boolean value with the following:</p>
<pre name="code" class="JScript">
Boolean(0);    // false
Boolean("0");  // true
</pre>
<p>Or we can use the less intuitive but quick way of using double exclamation marks (this will probably award you cleverness points in someone&#8217;s book.. hopefully those points actually matter):</p>
<pre name="code" class="JScript">
!!0;    // false
!!"0";  // true
</pre>
<p>This works because !foo converts foo to a Boolean but negates its original value, turning it on its head.  !!foo converts foo to a Boolean and flips it back to its expected value, which is the same value that&#8217;s evaluated by our <code>if</code> statement.</p>
<p>Using this ALMOST gives us the answer we&#8217;re looking for:</p>
<pre name="code" class="JScript">
!!foo0; // ReferenceError: foo0 is not defined

var foo1;
!!foo1; // false

var foo2 = null;
!!foo2; // false (same as !!null)

var foo3 = "";
!!foo3; // false (same as !!"")

var foo4 = "bar";
!!foot4; // true (same as !!"bar")
</pre>
<p>Excluding the first example, now we can test for uninitialized variables (foo1), null variables (foo2), and empty strings (foo3) all with just an <code>if</code> statement:</p>
<pre name="code" class="JScript">
if(foo1) {
  // do something with foo1
}

if(foo2) {
  // do something with foo2
}

if(foo3) {
  // do something with foo3
}
</pre>
<p>Dang… so close!  But we can&#8217;t yet test the first case without an error:</p>
<pre name="code" class="JScript">
if(foo0) {  // ReferenceError: foo0 is not defined

}
</pre>
<h3>foo versus window.foo and this.foo</h3>
<p>The secret to our solution lies in how JavaScript handles undefined variables versus undefined properties.  Here&#8217;s a quick reminder on the difference between the two:</p>
<pre name="code" class="JScript">
// variable foo
var foo;

// property bar (and object variable foo)
var foo = {};  // create an empty object to add bar too
foo.bar = "";
</pre>
<p>The difference between these makes all the difference whether a fatal error occurs:</p>
<pre name="code" class="JScript">
foo;  // ReferenceError: foo is not defined

var foo = {};
foo.bar;  // undefined
foo.blah; // undefined
</pre>
<p>We can randomly invent and check any property of <code>foo</code> we want, and the code will keep chugging along:</p>
<pre name="code" class="JScript">
var foo = {};
foo.something = "hello";

if(foo.bar) { // undefined, interpreted as false (same as !!foo.bar)
  // never runs
}

if(foo.something) {
  foo.something;  // "hello"
}
</pre>
<p>Now comes the magic.  If you know anything about JavaScript running in the browser, you know that all global variables are part of the <code>window</code> object.  This means <code>foo</code> and <code>window.foo</code> are equivalent:</p>
<pre name="code" class="JScript">
var foo;

foo === window.foo;  // true

// "this" is another bag of worms, but note this anyway
this.foo === window.foo;
</pre>
<p>So technically our variable foo is a <i>property</i> of the window object.  So we should be able to check for any arbitrary variable in the window scope now!</p>
<pre name="code" class="JScript">
window.foo;  // undefined (not a fatal error!)

// even though we're checking for the same thing, we get a fatal error…
foo;  // ReferenceError: foo is not defined
</pre>
<h3>Practical uses</h3>
<p>Now as long as we have a global entry point for our code, we can write our code in such a way that it won&#8217;t ever give us a fatal error if our variables aren&#8217;t yet defined:</p>
<pre name="code" class="JScript">
if(window.foo &#038;&#038; foo.bar) {
  foo.bar();
}
</pre>
<p>Of course nothing happens, because we haven&#8217;t defined foo.  But why doesn&#8217;t foo.bar give us a fatal error?  Because the first test, <code>window.foo</code> failed out.  It would be useless processing for the JavaScript engine to also evaluate the second statement, because the end result will still be the same (false &#038;&#038; true results in false, false &#038;&#038; false results in false).  So it doesn&#8217;t get so far as <code>foo.bar</code>.</p>
<p>And now the code will work properly when we hook up our code to our <code>foo</code> global namespace:</p>
<pre name="code" class="JScript">
var foo = {
  bar: function() {
    alert("hello world");
  }
}

if(window.foo &#038;&#038; foo.bar) {
  foo.bar();  // "hello world"
}
</pre>
<h3>Shorthand</h3>
<p>It&#8217;s becoming common to see an abbreviation for the above code.  Check out the following two methods, which accomplish the same thing:</p>
<pre name="code" class="JScript">
// Method 1
if(window.foo &#038;&#038; foo.bar) {
  foo.bar();  // "hello world"
}

// Method 2
window.foo &#038;&#038; foo.bar &#038;&#038; (foo.bar());
</pre>
<p>Don&#8217;t get too scared.. these blocks of code are equivalent.  Method 2 is shorter, but it simply goes something like this: if window.foo isn&#8217;t set, stop evaluating this line (just as above in the <code>if</code> statement).  Otherwise, if foo.bar exists then execute the code in parentheses, which gives us an alert (&#8220;hello world&#8221;);</p>
<p>Just a word of caution about using Method 2: it&#8217;s obviously less clear what&#8217;s going on here.  Your own cleverness might actually result in unnecessary confusion, especially of other people work in the same code base and they&#8217;re at different levels of understanding.  In these cases we should first strive to be clear, and then only clever if it&#8217;s not at the expense of being clear.</p>
<p>It&#8217;s also likely that a code minifier would take care of this cleverness for us at build time, giving us the best of both worlds.</p>
]]></content:encoded>
			<wfw:commentRss>http://davidbcalhoun.com/2011/checking-for-undefined-null-and-empty-variables-in-javascript/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>JavaScript news resources</title>
		<link>http://davidbcalhoun.com/2011/javascript-news-resources</link>
		<comments>http://davidbcalhoun.com/2011/javascript-news-resources#comments</comments>
		<pubDate>Sat, 15 Jan 2011 01:28:54 +0000</pubDate>
		<dc:creator>David</dc:creator>
				<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://davidbcalhoun.com/?p=562</guid>
		<description><![CDATA[There&#8217;s an overwhelming amount of information being pumped out of the JavaScript community each week, but how do you keep up with it? Here&#8217;s some sources to keep you busy. Twitter This merits a category of its own. This has replaced the RSS reader for a lot of folks, or at the very least supplemented [...]]]></description>
			<content:encoded><![CDATA[<p>There&#8217;s an overwhelming amount of information being pumped out of the JavaScript community each week, but how do you keep up with it?  Here&#8217;s some sources to keep you busy.</p>
<h3>Twitter</h3>
<p>This merits a category of its own.  This has replaced the RSS reader for a lot of folks, or at the very least supplemented it.</p>
<p>I&#8217;ve consistently recommended <a href="http://twitter.com/#!/nathansmith/javascript/">Nathan Smith&#8217;s list of JavaScript folks</a>.  When I&#8217;m diligent, I keep up with this several times a week and <a href="http://twitter.com/#!/franksvalli/favorites/">favorite items from the feed</a> to be considered for inclusion in that week&#8217;s <a href="http://jsmag.com/blog/">JSMag Blog update</a>.</p>
<h3>Aggregators and communities</h3>
<p><a href="http://www.delicious.com/recent/javascript">Delicious</a><br />
<a href="https://github.com/languages/JavaScript">Github</a><br />
Reddit: <a href="http://www.reddit.com/r/web_design/">web_design</a> and <a href="http://www.reddit.com/r/javascript/">javascript</a><br />
<a href="http://groups.google.com/group/jsmentors">JSMentors</a></p>
<h3>Blogs</h3>
<p><a href="http://www.google.com/reader/bundle/user%2F00060481582380134484%2Fbundle%2FJavaScript">JavaScript Google Reader bundle</a><br />
<a href="http://www.google.com/reader/bundle/user%2F00060481582380134484%2Fbundle%2FJavaScript%20People">JavaScript People Blogs &#8211; Google Reader bundle</a></p>
<p><a href="http://hacks.mozilla.org/articles/">Mozilla articles on hacks.mozilla.org</a><br />
<a href="http://msdn.microsoft.com/en-us/scriptjunkie/">Script Junkie</a><br />
<a href="http://dailyjs.com/">DailyJS</a> &#8211; very frequently updated news by Alex Young<br />
<a href="http://www.quirksmode.org/blog/">QuirksBlog (ppk)</a> &#8211; focus on mobile<br />
<a href="http://javascriptweblog.wordpress.com/">JavaScript, JavaScript (Angus Croll)</a><br />
<a href="http://ejohn.org/category/blog/">John Resig&#8217;s blog</a> &#8211; unfortunately not too active lately (check out <a href="http://twitter.com/#!/jeresig">his Twitter</a> for more updated info)<br />
<a href="http://ajaxian.com/">Ajaxian</a> &#8211; used to be THE source for news, but it isn&#8217;t updated too much anymore</p>
<p>&#8230;and many more.  Check out <a href="http://blog.reybango.com/2010/12/15/what-to-read-to-get-up-to-speed-in-javascript/">Rey Bango&#8217;s &#8220;What to Read to Get Up to Speed in JavaScript&#8221;</a> for more.</p>
<h3>Browser blogs</h3>
<p>It&#8217;s important to know what&#8217;s going down in the browser world.  These have mixed content, so it&#8217;s not just JavaScript.</p>
<p><a href="http://webkit.org/blog/">Surfin&#8217; Safari</a><br />
<a href="http://blog.chromium.org/">The Chromium Blog</a><br />
<a href="http://blog.mozilla.com/">The Mozilla Blog</a></p>
<h3>Weekly news</h3>
<p>These sources attempt to do the legwork for you and round up the most important articles each week.  (Disclaimer: I currently write for JSMag!)</p>
<p><a href="http://javascriptweekly.com/">JavaScript Weekly</a>: a weekly email newsletter<br />
<a href="http://badassjs.com/">Badass JS</a><br />
<a href="http://jsmag.com/blog/">JSMag blog</a></p>
<h3>Podcasts and Videos</h3>
<p><a href="http://www.aminutewithbrendan.com/">A Minute With Brendan</a><br />
<a href="http://node.minutewith.com/">node.minutewith</a><br />
<a href="http://developer.yahoo.com/yui/theater/">YUI Theatre</a><br />
<a href="http://nodeup.com/">Node Up</a></p>
<p>Am I missing anything (I&#8217;m very sure)?  Post a link below in the comments.  Thanks!</p>
]]></content:encoded>
			<wfw:commentRss>http://davidbcalhoun.com/2011/javascript-news-resources/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>What happens when you have no JavaScript fallback?</title>
		<link>http://davidbcalhoun.com/2011/what-happens-when-you-have-no-javascript-fallback</link>
		<comments>http://davidbcalhoun.com/2011/what-happens-when-you-have-no-javascript-fallback#comments</comments>
		<pubDate>Wed, 12 Jan 2011 07:50:18 +0000</pubDate>
		<dc:creator>David</dc:creator>
				<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://davidbcalhoun.com/?p=555</guid>
		<description><![CDATA[Here&#8217;s an example of what happens when your interface completely relies on JavaScript. There&#8217;s code with translated mojibake of some sort which caused the JavaScript to break. The code wasn&#8217;t in a try-catch block, so it caused all of the code on the page to fail, thus presenting me with the only part of the [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://davidbcalhoun.com/wp-content/uploads/2011/01/twitter-fallback.png"><img src="http://davidbcalhoun.com/wp-content/uploads/2011/01/twitter-fallback.png" alt="" title="Twitter no-JavaScript fallback" width="1036" height="772" class="aligncenter size-full wp-image-556" /></a></p>
<p>Here&#8217;s an example of what happens when your interface completely relies on JavaScript.  There&#8217;s code with translated <a href="http://en.wikipedia.org/wiki/Mojibake">mojibake</a> of some sort which caused the JavaScript to break.  The code wasn&#8217;t in a try-catch block, so it caused all of the code on the page to fail, thus presenting me with the only part of the screen that wasn&#8217;t generated by JavaScript: the completely useless header.</p>
<p>Where&#8217;s the tweets!?</p>
]]></content:encoded>
			<wfw:commentRss>http://davidbcalhoun.com/2011/what-happens-when-you-have-no-javascript-fallback/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How to spot outdated JavaScript</title>
		<link>http://davidbcalhoun.com/2011/how-to-spot-outdated-javascript</link>
		<comments>http://davidbcalhoun.com/2011/how-to-spot-outdated-javascript#comments</comments>
		<pubDate>Fri, 07 Jan 2011 08:21:38 +0000</pubDate>
		<dc:creator>David</dc:creator>
				<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://davidbcalhoun.com/?p=536</guid>
		<description><![CDATA[Introduction Those that are just setting out to learn JavaScript are typically overwhelmed by the amount of online resources to be found about learning JavaScript. Not only this, but every webpage visited presents a potential learning opportunity just by inspecting the source. However, not all resources are guaranteed to be up-to-date. JavaScript has been around [...]]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>Those that are just setting out to learn JavaScript are typically overwhelmed by the amount of online resources to be found about learning JavaScript.  Not only this, but every webpage visited presents a potential learning opportunity just by inspecting the source.</p>
<p>However, not all resources are guaranteed to be up-to-date.  JavaScript has been around for over a decade, and coding standards have changed drastically over time.  While a code snippet may still work in today&#8217;s browsers, you may unknowingly be using an outdated practice that might eventually lead to a bit of embarrassment.</p>
<p>You may sometimes find these old practices mixed in with good and modern code.  It seems that folks might learn new code styles without necessarily casting away all their old habits.  So keep in mind not to throw out the baby with the bathwater!</p>
<p>Here&#8217;s some old practices that should help you spot old outdated code. </p>
<h3>Global variables</h3>
<pre name="code" class="JScript">
function foo() {  // global function
  greeting = 'Hello' + name;  // global function
};
name = 'James';  // global variable
foo();
</pre>
<p>Tons of global variables is a sure sign of outdated code.  Ideally you want to aim to have at most one global variable, which is a namespace for all your code to be written under.  All variables in your functions should be defined with the &#8216;var&#8217; keyword to ensure they don&#8217;t break out of their scope.</p>
<p>Here&#8217;s an example where we defined one global variable entry point (myNamespace) for our code:</p>
<pre name="code" class="JScript">
var myNamespace = (function() {
  // declare all variables with var
  var greeting, name;

  name = 'James';

  greeting = function() {
    return 'Hello ' + name;
  };

  return {
    greeting: greeting
  }
})();

greeting();              // ERROR: not defined
myNameSpace.greeting();  // 'Hello James'
</pre>
<h3>Commented CDATA blocks</h3>
<pre name="code" class="JScript">
/* &lt;![CDATA[ */
// code here
/* ]]&gt; */
</pre>
<p>This appears in old scripts that are presented inline (instead of externally in a separate file).  The original purpose of those was to get around HTML validator errors (and to conform to XHTML), but that appears to no longer be an issue with validators today.  Also, the usage of HTML validators itself seems to be waning, although they may sometimes be helpful in the development of websites.</p>
<h3>document.write()</h3>
<pre name="code" class="JScript">
document.write('foo');
</pre>
<p>The <a href="http://dev.w3.org/html5/spec/apis-in-html-documents.html#document.write">W3C</a>, along with most everyone else, warns against using this, as it may result in overwriting (blanking) the entire page and other unwanted behavior.</p>
<p>It&#8217;s now used mostly by ads, and <a href="http://www.stevesouders.com/blog/2010/12/15/controljs-part-3/">developers have for years been trying to control them</a>.  So don&#8217;t use it, unless you&#8217;re trying to prevent ads from using them.  In other words, don&#8217;t use it unless you know what you&#8217;re doing.</p>
<h3>Inlined event handlers</h3>
<pre name="code" class="HTML">
&lt;a onclick=&quot;myClickFunction()&quot; href=&quot;http://foo.com&quot;&gt;&lt;/a&gt;
&lt;a onmouseover=&quot;myMouseoverFunction()&quot; href=&quot;http://foo.com&quot;&gt;&lt;/a&gt;
&lt;form onsubmit=&quot;mySubmitFunction()&quot; href=&quot;http://foo.com&quot;&gt;&lt;/form&gt;
</pre>
<p>This mixes behavior with the actual content, which means when it&#8217;s time to make changes to the code, you likely have to change both the HTML and the JavaScript, instead of simply just the JavaScript.  It also means that you may be serving useless content to users with JavaScript disabled (<a href="http://developer.yahoo.com/blogs/ydn/posts/2010/10/followup-how-many-users-have-javascript-disabled/">they&#8217;re still out there</a>, believe it or not).  This also might have an affect on search engines, that might not be able to access this JavaScript-only content (although crawlers are getting more sophisticated and this may be less of an issue as time progresses).</p>
<p>Instead, the very least you can do is add IDs to each element (or better, use a JavaScript selector engine) and hook into them in your JavaScript, which makes the code much easier to maintain:</p>
<pre name="code" class="HTML">
&lt;a id=&quot;link1&quot; href=&quot;http://foo.com&quot;&gt;&lt;/a&gt;
&lt;a id=&quot;link2&quot; href=&quot;http://foo.com&quot;&gt;&lt;/a&gt;
&lt;form id=&quot;myForm&quot; href=&quot;http://foo.com&quot;&gt;&lt;/form&gt;
</pre>
<pre name="code" class="JScript">
(function() {  // sandbox everything
  // variable declarations
  var link1, link2, myForm;

  window.onload = function() {  // or onDOMContentLoaded (wait for DOM to be ready)
    // simple DOM selectors
    link1 = document.getElementById('link1');
    link2 = document.getElementById('link2');
    myForm = document.getElementById('myForm');

    // well-supported older event handler
    link1.onclick = function(){
      // code
    };

    // better (DOM2)
    link1.addEventListener('click', function(){ // or attachEvent for IE
      // code
    },false);

    // etc...
  }

})();
</pre>
<p>link1.onclick is widely supported, but there&#8217;s a few downsides, including the fact you can only add ONE event listener on the element (it will be overwritten if you try to add another).  Use addEventListener (attachEvent in IE) instead, or the method of your favorite JavaScript engine.</p>
<p>In any case, the point here is to get the JavaScript out of the HTML and into the rest of your JavaScript.</p>
<h3>Inline JavaScript in link hrefs</h3>
<pre name="code" class="HTML">
&lt;a href=&quot;javascript:doSomething()&quot;&gt;&lt;/a&gt;
&lt;a href=&quot;javascript:void(0)&quot;&gt;&lt;/a&gt;
</pre>
<p>Both of these examples commit the same error as above &#8211; mixing JavaScript behavior with the HTML content.  And the solution is similar: find these links with JavaScript (most simply by adding an id on them) and hook into them there.</p>
<p>The second example brings up a good issue, and a point of contention.  Ideally this would be a link to fallback content for users that have JavaScript disabled (and for search engines!), which would be a link to a new page (Flickr is an example of a modern site that uses this approach).  For better or worse, however, you might be building a web app that only works with JavaScript, and you might want a link that only exists to kick off a JavaScript event.</p>
<p>You&#8217;ll find that removing the href value or making it blank (href=&#8221;") might remove the styling from the link and no longer makes it clickable.  An easy fix is to set the href equal to a hash tag (href=&#8221;#&#8221;).  A side effect might be a &#8220;jump&#8221; to the top of the page after clicking the link, which requires and requires e.preventDefault() within the attached event.  Href=&#8221;#&#8221; may soon become an antipattern (or maybe it is already), since you can also fix this with CSS styling:</p>
<pre name="code" class="CSS">
a { cursor: pointer; }
</pre>
<p>This gives the cursor a pointer when the user hovers over the link, even if it&#8217;s missing the href value.</p>
<p>But again, this isn&#8217;t generally recommended.  It&#8217;s better to make a non-JavaScript fallback by linking to an actual page, then overriding it with e.preventDefault() for JavaScript-enabled users!</p>
<h3>Slow arrays</h3>
<pre name="code" class="JScript">
var arr = [1, 2, 3, 4, 5];

for(var x in arr) {
  /* code */
}

for(var i=0; i < arr.length; i++) {
  /* code */
}
</pre>
<p>For-in loops turn out to be quite slow while going through arrays, so only use them when iterating through properties of an object.  The second for loop is much faster, but can be made faster still when we realize what's being evaluated on each iteration:</p>
<pre name="code" class="JScript">
for(1; n; n) {}
</pre>
<p>The first statement is evaluated once (1 time) as the loop is initialized, and the second and third parts are evaluated on each run through the loop (n times).  Because of this, just as removing fluff from the main body of the loop itself, we would also do well to remove fluff from these statements themselves.  As it turns out, it's quite slow finding the length of the array (arr.length) on each pass, and it's not necessary to do it more than once since it's not changing.  So we can "cache" the length in a variable in the initializer:</p>
<pre name="code" class="JScript">
for(var i=0, len=arr.length; i < len; i++) {
  // code
}
</pre>
<p>And faster yet is a while loop (keep in mind that it will run backwards), which stops when the counter hits 0, which is falsy, causing the loop to stop:</p>
<pre name="code" class="JScript">
var i = arr.length;
while(i--) {
  // code
}
</pre>
<h3>new Object(), new Array(), new Function(), etc</h3>
<pre name="code" class="JScript">
var obj  = new Object();
var arr  = new Array();
var func = new Function("param1", "param2", "return true;");
</pre>
<p>While these work, no one really uses them, as there exist less verbose and more common alternatives.  Use these instead, which are exactly equal to the above code:</p>
<pre name="code" class="JScript">
var obj  = {};
var arr  = [];
var func = function(param1, param1) {return true;}
</pre>
<h3>alert()</h3>
<p>Ok, alert can sometimes still be useful for debugging, but generally you want to use console.log for that anyway.  Generally you don't want to ever prompt the user with alert() however.  Its use on the desktop for mainstream use has long been discouraged.</p>
<p>I'm still on the fence about using alert() however, as I think it's pretty useful and not necessarily ugly in mobile browsers.  I'll spare you and save that for another post.</p>
<h3>Missing semicolons</h3>
<pre name="code" class="JScript">
var name='Bill'
alert('Hi ' + name)
</pre>
<p>The above code works fine because of a controversial feature of JavaScript called semicolon insertion.  But doesn't it make you feel dirty?  It should, especially if you've read JavaScript: The Good Parts.  Use semicolons for your own good and to prevent major headaches.  Leave it to your JavaScript minifier to be clever in deciding when to remove them:</p>
<pre name="code" class="JScript">
var name='Bill';
alert('Hi ' + name);
</pre>
<h3>Code for particular user agents</h3>
<p>This is also a bit controversial, since unfortunately user agent sniffing is still sometimes necessary.  However, in the past it was really abused with code such as this:</p>
<pre name="code" class="JScript">
isIE  = document.all;
isNS4 = document.layers;
isNS6 = document.getElementById;
if(isIE) {
  // code for IE
} else if(isNS4) {
  // code for Netscape 4
} else if(isNS6) {
  // code for Netscape 6
}
</pre>
<p>(did I mention that any references to ancient browsers like Netscape is also a surefire sign of old code?  But that's probably too obvious...)</p>
<p>This example detects browsers by features that only exist in each of these old browsers, but the same sin is committed by "sniffing" for words in the user agent string.  The unfortunate result is fragmented code targeting each predetermined browser.  Not to mention that it's not future-proof, as it can't properly anticipate newer browsers.</p>
<p>The better method?  If there's a question about the availability of a method, simply check for it first before using it:</p>
<pre name="code" class="JScript">
if(document.addEventListener) {  // detect addEventListener
  // Try the standard first
  document.addEventListener('click', function(){}, false);
} else if(document.attachEvent) {  // detect attachEvent
  // Typically IE
  document.attachEvent('onclick', function(){});
}
</pre>
<p>This code is considered feature detection, which is much more acceptable.  It also anticipates newer browsers such as IE9, which support addEventListener.  This makes sure the code you write doesn't condemn Internet Explorer to forever use attachEvent.</p>
<h3>Related links</h3>
<p>Christian Heilmann and PPK's old posts inspired me to write this brief post.  You can read much better rationale against using some of the things above at these links:</p>
<p><a href="http://www.wait-till-i.com/2005/06/21/six-javascript-features-we-do-not-need-any-longer/">Six JavaScript features we do not need any longer (Christian Heilmann, 2005)</a></p>
<p><a href="http://icant.co.uk/articles/from-dhtml-to-dom/from-dhtml-to-dom-scripting.html">From DHTML to DOM scripting (Christian Heilmann, 2006)</a></p>
<p><a href="http://www.quirksmode.org/blog/archives/2005/06/three_javascrip_1.html">Three JavaScript articles and one best practice (PPK 2005)</a></p>
]]></content:encoded>
			<wfw:commentRss>http://davidbcalhoun.com/2011/how-to-spot-outdated-javascript/feed</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>What is a closure in JavaScript?</title>
		<link>http://davidbcalhoun.com/2011/what-is-a-closure-in-javascript</link>
		<comments>http://davidbcalhoun.com/2011/what-is-a-closure-in-javascript#comments</comments>
		<pubDate>Tue, 04 Jan 2011 01:27:28 +0000</pubDate>
		<dc:creator>David</dc:creator>
				<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://davidbcalhoun.com/?p=532</guid>
		<description><![CDATA[Intro There have been many attempts to answer this question in a succinct way, but I haven&#8217;t really been satisfied by them. Here&#8217;s my attempt at a (relatively) concise explanation. This is adapted from a reply I posted on reddit which people seemed to have found useful. Broad definition Normally when people talk about closures [...]]]></description>
			<content:encoded><![CDATA[<h3>Intro</h3>
<p>There have been many attempts to answer this question in a succinct way, but I haven&#8217;t really been satisfied by them.  Here&#8217;s my attempt at a (relatively) concise explanation.</p>
<p>This is adapted from a <a href="http://www.reddit.com/r/javascript/comments/eti86/can_somebody_explain_closures_to_me/c1atir1">reply I posted on reddit</a> which people seemed to have found useful.</p>
<h3>Broad definition</h3>
<p>Normally when people talk about closures in JavaScript, they&#8217;re talking about methods and properties that outlive the scope of their original function (more on that in a second), but actually the definition is a bit broader. A closure is how a function &#8220;closes over&#8221; (Crockford) its variables and creates a different scope for them out of the way of the global [window] scope. So an understanding of closures will require some understanding of scope, which is definitely a common stumbling block in first learning JavaScript.</p>
<p>Essentially, closures make this possible:</p>
<pre name="code" class="JScript">
var a = 1;
function(){
  var a = 2;
  a; // 2 (functional scope)
};
a;  // 1 (global scope)
</pre>
<h3>Variables that survive after function execution</h3>
<p>But when people get excited about closures, they&#8217;re not really talking about the example above, but about the ability for functional variables to outlive their original functional scope:</p>
<pre name="code" class="JScript">
var b = function() {
  var myPrivateVar = 'Foo';
  var myPublicVar = 'Bar';

  return myPublicVar;
};

b();  // 'Bar'
myPrivateVar;  // ERROR (not defined, because it was only defined in functional scope and is trying to be accessed from the global [window] scope)
myPublicVar;   // ERROR (not defined)
</pre>
<p>But note that the original method name (myPublicVar) isn&#8217;t available &#8211; but the value IS available from what we exposed to the global scope through the variable &#8216;b&#8217;.</p>
<h3>Closures and the Module Pattern</h3>
<p>How is this useful?  This turns out to be the foundation for the Module Pattern in JavaScript &#8211; the building block of modern JavaScript applications. They&#8217;re in essence a glorified version of the block of code above, with the purpose of hiding the function&#8217;s private variables (this comes by default when declaring variables with the &#8216;var&#8217; keyword in functions), and exposing public variables. And note that because functions are first class in JavaScript, those variables can even be references to functions themselves!</p>
<p>So in essence this is the module pattern, with both private and public properties and methods:</p>
<pre name="code" class="JScript">
var myAPI = (function() {
  var privateProperty = 'Foo';
  var publicProperty = 'Bar';

  var privateMethod = function() {
    alert('I can only be executed from the scope of myAPI');
  };

  var publicMethod = function() {
    alert('I am publicly accessible (through the global scope) because a reference to publicMethod is returned by myAPI');
  };

  // set up an object whose own property names (on the left) match the references to the internal, functionally-scoped methods (on the right)
  var publicStuff = {
    publicProperty: publicProperty,
    publicMethod: publicMethod
  };

  // return our public object (myAPI is now equal to this object)
  return publicStuff;
})();   // immediately execute myAPI as a function, which returns an object that contains pointers to stuff in myAPI, which is exposed through myAPI.x, myAPI.y, etc
</pre>
<p>By the time we reach the last line of the above script, the function has stopped executing, but some original pieces of the function still live on! Because some references to functional variables were returned by the function, we can now access these through the &#8220;namespace&#8221; myAPI:</p>
<pre name="code" class="JScript">
myAPI.publicProperty;  // 'Bar'
myAPI.publicMethod(); // (alert: 'I am publicly accessible'...)
</pre>
<p>But those variables that were not exposed are of course not accessible:</p>
<pre name="code" class="JScript">
myAPI.privateProperty;  // error (not defined)
myAPI.privateMethod(); // error (not defined)
</pre>
<h3>Access to unexposed variables</h3>
<p>Exposed public methods still have the context of the original function, meaning that they have access to all the function&#8217;s variables, public and private:</p>
<pre name="code" class="JScript">
var myAPI = (function(){
  var privateProperty = 'Foo';

  var publicFunction = function() {
    // this function has access to privateProperty because it's in the same scope, even after the main function stops executing!
    return privateProperty;
  };

  // create a new object and return it
  return {
    publicFunction: publicFunction
  };
})();

privateProperty;         // ERROR (not defined)
myAPI.publicFunction();  // 'Foo'
</pre>
<p>There&#8217;s definitely more to be said here, but hopefully this helps!</p>
]]></content:encoded>
			<wfw:commentRss>http://davidbcalhoun.com/2011/what-is-a-closure-in-javascript/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>What happens when we serve JavaScript with random MIME types?</title>
		<link>http://davidbcalhoun.com/2010/what-happens-when-we-serve-javascript-with-random-mime-types</link>
		<comments>http://davidbcalhoun.com/2010/what-happens-when-we-serve-javascript-with-random-mime-types#comments</comments>
		<pubDate>Tue, 02 Nov 2010 02:16:28 +0000</pubDate>
		<dc:creator>David</dc:creator>
				<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://davidbcalhoun.com/?p=494</guid>
		<description><![CDATA[Introduction When people started to learn about the HTML5 doctype, they kind of freaked out a little, not knowing how older browsers would handle it. A post by Dustin Diaz prompted me to test out how pages rendered (in QuirksMode or Standards Mode) with a little help from document.compatMode, and I found that surprisingly every [...]]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>When people started to learn about the HTML5 doctype, they kind of freaked out a little, not knowing how older browsers would handle it.  A <a href="http://www.dustindiaz.com/skinny-on-doctypes/">post by Dustin Diaz</a> prompted me to test out how pages rendered (in QuirksMode or Standards Mode) with a little help from <code>document.compatMode</code>, and <a href="http://themaingate.net/dev/html/all-you-need-is-doctype-html">I found that surprisingly every browser rendered in Standards Mode with the new doctype</a>.  In other words, no need to worry!</p>
<p>There&#8217;s another welcome simplification (<a href="http://davidbcalhoun.com/2010/top-ten-things-html5-makes-simpler">along with others</a>): the &#8220;type&#8221; attribute is no longer necessary on script tags:</p>
<blockquote><p>The type attribute gives the language of the script or format of the data. If the attribute is present, its value must be a valid MIME type. The charset parameter must not be specified. <b>The default, which is used if the attribute is absent, is &#8220;text/javascript&#8221;.</b> <a href="http://dev.w3.org/html5/spec/Overview.html#script">-W3C HTML5 spec</a></p></blockquote>
<p>Which means that this is all that&#8217;s required now:</p>
<pre name="code" class="html">
&lt;script src=&quot;script.js&quot;&gt;&lt;/script&gt;
</pre>
<p>But how do older browsers handle this?  Also, what if we send some crazy Content-Type back in the response header?  To make matters more confusing, I noticed that different CDNs send back different Content-Types: <a href="http://yui.yahooapis.com/3.2.0/build/yui/yui-min.js">YUI</a> and <a href="http://code.jquery.com/jquery-1.4.3.min.js">jQuery</a>&#8216;s CDNs send back &#8220;application/x-javascript&#8221; whereas <a href="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">Google&#8217;s CDN</a> serving jQuery sends back &#8220;text/javascript; charset=UTF-8&#8243;.</p>
<p>So does it really matter what the Content-Type is?  Let&#8217;s find out!</p>
<h3>Setting up the tests</h3>
<p>The test is fairly simple: I have six JavaScript files that all write to the DOM when they&#8217;re executed successfully.  Each of these files has a different file extension (js.one, js.two, js.three, etc) and each is served with an extension determined by the .htaccess file, which is in the same directory, and contains this bit of magic:</p>
<pre>
AddType text/javascript .one
AddType application/x-javascript .two
AddType application/javascript .three
AddType text/ecmascript .four
AddType text/jscript .five
AddType text/foo .six
</pre>
<p>My index.html contains a little helper utility for each of these scripts to use:</p>
<pre name="code" class="JScript">
var TEST = {
  node: document.body,
  addMessage: function(message) {
    var p = document.createElement('p');
    p.innerHTML = message;
    this.node.appendChild(p);
  }
}
</pre>
<p>TEST.addMessage() is simply a glorified document.write.  As each of the six scripts is run, they&#8217;ll write out a message to the page essentially saying &#8220;I&#8217;m here!  It worked!&#8221;.</p>
<h3>Results</h3>
<p>All the browsers I tested worked better than expected.  It turns out that Content-Type doesn&#8217;t even matter.  I made up my own content type &#8220;text/foo&#8221;, served the file successfully, and it still executed as JavaScript!</p>
<p>I tried all the major A-grade browsers (yes, including IE6-8), plus other random browsers through <a href="http://browsershots.org/">Browsershots.org</a>.</p>
<p>One thing I still need to try is IE9, which <a href="http://twitter.com/#!/paul_irish/status/29416115232">Paul Irish said may not work</a>.  I&#8217;ll give it a test&#8230; soon.</p>
<h3>Additional test #1: playing with the &#8220;type&#8221; attribute</h3>
<p>Instead of messing around with the MIME type sent back in the response header, what happens when we mess around with the &#8220;type&#8221; attribute on the script tag?  For instance:</p>
<pre name="code" class="HTML">
&lt;script type=&quot;text/foo&quot;&gt;&lt;/script&gt;
</pre>
<p>Using the same testing technique as above, I found these results to be more pronounced.  Browsers were more picky.  For instance, Chrome and Safari ran all the content types successfully except my made-up &#8220;text/foo&#8221;.  Firefox was even more picky, choosing not to recognize the type &#8220;text/jscript&#8221;.  I&#8217;d imagine there&#8217;s similar results with other browsers such as IE.</p>
<p>&#8230;But none of that really matters now!  Simply omit the type attribute and everything seems to work fine (except possibly not in IE9?).</p>
<h3>Additional test #2: content type and caching</h3>
<p><a href="http://twitter.com/#!/bluesmoon/status/29418676869">Philip Tellis</a> wanted to know if Content-Type had any bearing on how the browser caches data.  For instance, if something previously requested has the same filename but a different content type, is there a cache hit (304 code returned) or miss?</p>
<p>In the first test I made a page that requested a file.  Then in a not-too-fancy way I changed the content type through .htaccess on the fly and made another request.  A 304 code was returned even with the new content type, so it was clear that this traditional caching method wasn&#8217;t affected.</p>
<p>In my second test I instead changed the &#8220;type&#8221; attribute on the script tag itself (in the HTML).  The file was still cached normally, even after the type changed.</p>
<p>I only tested in Chrome, Safari, and Firefox, so the story might be different in IE.  Anyhow, this is an edge case anyway and more of a test out of curiosity!  It seems the way browsers handle caching in these instances is truly RESTful, that is, the current state of the file is determined entirely by the filename.</p>
]]></content:encoded>
			<wfw:commentRss>http://davidbcalhoun.com/2010/what-happens-when-we-serve-javascript-with-random-mime-types/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript links from last week (September 26)</title>
		<link>http://davidbcalhoun.com/2010/javascript-links-september-26</link>
		<comments>http://davidbcalhoun.com/2010/javascript-links-september-26#comments</comments>
		<pubDate>Tue, 05 Oct 2010 18:40:35 +0000</pubDate>
		<dc:creator>David</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[links]]></category>

		<guid isPermaLink="false">http://davidbcalhoun.com/?p=478</guid>
		<description><![CDATA[JavaScript Asteroids &#8211; blow up any webpage with this bookmarklet! JS1k contest &#8211; and the winner PromoteJS &#8211; Google bombing with a good intent. Better links to JavaScript documentation! Async and defer attributes for Script tags added to WebKit Evercookie &#8211; uses devious ways to try to track users. Hmm, this one is questionable. Please [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://erkie.github.com/">JavaScript Asteroids</a> &#8211; blow up any webpage with this bookmarklet!</p>
<p><a href="http://js1k.com">JS1k contest</a> &#8211; and the <a href="http://marijn.haverbeke.nl/js1k.html">winner</a></p>
<p><a href="http://www.wait-till-i.com/2010/09/26/promote-better-javascript-documentation-with-promotejs/">PromoteJS</a> &#8211; Google bombing with a good intent.  Better links to JavaScript documentation!</p>
<p><a href="http://webkit.org/blog/1395/running-scripts-in-webkit/">Async and defer attributes for Script tags added to WebKit</a></p>
<p><a href="http://samy.pl/evercookie/">Evercookie</a> &#8211; uses devious ways to try to track users.  Hmm, this one is questionable.  Please use it for good, not evil.. :/</p>
<p><a href="http://jsperf.com">JSPerf.com</a> &#8211; not really new news, but a nice quick way to test algorithm performance in JavaScript</p>
<p><a href="http://github.com/SlexAxton/yepnope.js">yepnope.js</a> &#8211; a wrapper around <a href="http://labjs.com/">LABjs Script Loader</a> to save bandwidth by only loading needed components.  Think of JSON &#8211; there&#8217;s no reason to send this down the wire if the browser supports this natively.</p>
<p><a href="https://hacks.mozilla.org/2010/01/classlist-in-firefox-3-6/">Classlist in Firefox 3.6</a> &#8211; for easier manipulation of classes on elements.  And <a href="http://trac.webkit.org/changeset/68440">it just landed a patch in WebKit</a>!</p>
<p>QuirksBlog: <a href="http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html">Click event delegation on the iPhone</a> and an <a href="http://www.quirksmode.org/blog/archives/2010/10/click_event_del_1.html">update</a></p>
<p><a href="http://almaer.com/blog/chrome-speak-to-site-give-any-input-the-power-to-listen-to-you">Chrome Speak To Site; Give any input the power to listen to you</a> &#8211; support for input type=speech (supported by <a href="http://trac.webkit.org/export/66389/trunk/LayoutTests/fast/speech/input-appearance-speechbutton.html">WebKit</a>)</p>
<p><a href="http://embedjs.org/">embedJS</a> &#8211; selective JS for embedded devices (mobile, TV, etc.) based on capabilities.</p>
<p><a href="http://github.com/remy/jsconsole-iphone">JS Console for iOS</a> &#8211; native JS console built by Remy Sharp.</p>
<p><a href="https://no.de/">Joyent Node SmartMachine</a> &#8211; API for node.js?</p>
<p><a href="http://jsconfeu2010-bfirsh.heroku.com/">Slides: Pushing browsers to the limit (Ben Firshman)</a> &#8211; by the creator of <a href="http://www.virtualnes.com/">Virtual NES</a> &#8211; all in JavaScript!</p>
<p><a href="http://blog.mozilla.com/blog/2010/09/14/release-the-kraken-2/">Release the Kraken</a> &#8211; Mozilla releases its Kraken JavaScript benchmark, analogue to <a href="http://www2.webkit.org/perf/sunspider-0.9/sunspider.html">WebKit&#8217;s SunSpider</a></p>
]]></content:encoded>
			<wfw:commentRss>http://davidbcalhoun.com/2010/javascript-links-september-26/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Server side console.log</title>
		<link>http://davidbcalhoun.com/2010/server-side-console-log</link>
		<comments>http://davidbcalhoun.com/2010/server-side-console-log#comments</comments>
		<pubDate>Thu, 16 Sep 2010 04:35:08 +0000</pubDate>
		<dc:creator>David</dc:creator>
				<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://davidbcalhoun.com/?p=452</guid>
		<description><![CDATA[The problem On the desktop we&#8217;re quite privileged to have nice debugging tools such as Firebug and Web Inspector in Webkit-based browsers. But when it comes to mobile, debugging JavaScript with console.log isn&#8217;t quite as easy. Probably the best available tool on mobile at the moment is mobile Safari&#8217;s console, which looks like the following [...]]]></description>
			<content:encoded><![CDATA[<h3>The problem</h3>
<p>On the desktop we&#8217;re quite privileged to have nice debugging tools such as Firebug and Web Inspector in Webkit-based browsers.  But when it comes to mobile, debugging JavaScript with <code>console.log</code> isn&#8217;t quite as easy.</p>
<p>Probably the best available tool on mobile at the moment is mobile Safari&#8217;s console, which looks like the following when enabled (Settings -> Safari -> Developer -> Debug Console):<br />
<div id="attachment_453" class="wp-caption aligncenter" style="width: 710px"><img src="http://davidbcalhoun.com/wp-content/uploads/2010/09/mobile-safari-console.png" alt="" title="mobile-safari-console" width="700" height="480" class="size-full wp-image-453" /><p class="wp-caption-text">Mobile Safari's debug console</p></div></p>
<p>On the left you can see the debug console displayed above the document itself, and on the right is an example of what you might see after outputting an object or a string of text to <code>console.log</code>.  It&#8217;s the best debugging tool on mobile, but it&#8217;s not without its issues.</p>
<p>The first issue is that the debug console is taking up space in the screen and interfering with how an actual user would view the website.  I could image this could become particularly annoying when trying to develop a web app in the style of the new YouTube mobile, which doesn&#8217;t function like a traditional webpage at all, and relies on the screen being a certain height in order to display its content.</p>
<p>The second issue is that you can&#8217;t see the contents of JavaScript Objects.  We&#8217;re a bit spoiled being able to see a tree view of objects on the latest browsers with the latest debugging tools, and therefore it makes the experience on mobile Safari less than adequate.  When we type <code>console.log(navigator)</code> all we can see on mobile Safari is <code>[object Navigator]</code>, which leaves something to be desired.</p>
<p>So what about Android?  Google offers something called <a href="http://developer.android.com/guide/developing/tools/adb.html">Android Debug Bridge</a>, which is a client-server debugging solution that can be used either for web or application development.  As such, when you view the messages the devices sends to the server, the vast majority of messages will be messages about low-level operations, stuff we usually don&#8217;t care much about when developing with JavaScript.  The workaround for this is to grep for &#8220;console&#8221; on the command line, which will only display the messages we&#8217;re interested in.</p>
<h3>The solution: server side console.log!</h3>
<p>Why not just send the contents of your console message to a server, and have it log it?  The concept is pretty simple:</p>
<ol>
<li>Create a log function that sends an XHR to a server.</li>
<li>Have the server process the request and log the message to a file.</li>
<li>Tail the end of the file on the command line to see the latest messages.</li>
</ol>
<p>The implementation is pretty simple.  In JavaScript we have this code:</p>
<pre name="code" class="JScript">
(function(){

// define console if not already defined
console || (console = {});

// new toFile method
console.toFile = function(log) {
  // variable declarations
  var http, url, params;

  // might as well use the traditional console.log() as well
  console.log(log);

  // ajax request
  http = new XMLHttpRequest();
  url = "//example.com/log.php";
  params = "log=" + Date.now() + ' ' + escape(sanitize(log));
  http.open("POST", url, true);
  http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http.send(params);
}

// do something special if txt is an object
var sanitize = function(txt) {
  var output, x;

  if(typeof txt == 'object') {
    // create a new object to get around circular references
    output = {};
    for(x in txt) {
        // type conversion of each element to a string
        output[x] = txt[x] + '';
    }
    output = JSON.stringify(output, null, 2);
  } else {
    output = txt;
  }

  return output;
}

})();
</pre>
<p>In summary, the above code adds a new method to the console object called <code>toFile</code>, which simply takes the inputted data and sends it to the specified URL.  The only bit of trickery here is the function <code>sanitize</code>, which detects if the message being passed in is an object.  If it is, it copies it to a new object containing only strings (which gets around JSON &#8220;circular reference&#8221; errors) and runs JSON.stringify() on it, which lets us peek into its contents one level deep.</p>
<p>The server side PHP code to make this work is even simpler:</p>
<pre name="code" class="PHP">
// log.php
&lt;?php

// take advantage of error_log to log the message to the file console.log
@error_log($_POST['log'] . "\n", 3, 'console.log');

?&gt;
</pre>
<p>On the server, we log in with terminal, navigate to the directory containing the file console.log, and simply tail the end of the file, which shows live updates as new messages are added to the end of the file:</p>
<pre name="code">
tail -f console.log
</pre>
<h3>Example</h3>
<p>Once we have the above code in place, using the console is very simple:</p>
<pre name="code" class="JScript">
console.toFile('hello world!');
console.toFile(navigator);
</pre>
<p>After running this code, you should see this pop up on your terminal:</p>
<pre name="code">
1284574866900 hello world!
1284575008914 {
  "geolocation": "[object Geolocation]",
  "standalone": "false",
  "cookieEnabled": "true",
  "language": "en-us",
  "productSub": "20030107",
  "product": "Gecko",
  "appCodeName": "Mozilla",
  "mimeTypes": "[object MimeTypeArray]",
  "vendorSub": "",
  "vendor": "Apple Computer, Inc.",
  "platform": "iPhone",
  "appName": "Netscape",
  "appVersion": "5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8B117 Safari/6531.22.7",
  "userAgent": "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8B117 Safari/6531.22.7",
  "plugins": "[object PluginArray]",
  "onLine": "true",
  "javaEnabled": "function javaEnabled() {\n    [native code]\n}",
  "getStorageUpdates": "function getStorageUpdates() {\n    [native code]\n}",
  "registerProtocolHandler": "function registerProtocolHandler() {\n    [native code]\n}",
  "registerContentHandler": "function registerContentHandler() {\n    [native code]\n}"
}
</pre>
<p>Sweet!  Now we can easily see console messages from <i>actual devices</i>.  You can potentially use this code to log Events as they occur (on click or touch interactions) and view the actual x/y coordinate values as they&#8217;re being detected on the device!</p>
<h3>Related</h3>
<p>Alex Kessinger implemented a <a href="http://alexkessinger.net/story/one-file-remote-consolelog-using-nodejs">similar concept with node.js running locally</a></p>
<h3>Update</h3>
<p>It turns out that Joe Hewitt did this before me with his <a href="http://www.joehewitt.com/blog/firebug_for_iph.php">&#8220;Firebug for iPhone&#8221;</a>.  I have no idea why it took me so long to find this!</p>
]]></content:encoded>
			<wfw:commentRss>http://davidbcalhoun.com/2010/server-side-console-log/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Video: John Resig &#8211; Testing, Performance Analysis, and jQuery 1.4</title>
		<link>http://davidbcalhoun.com/2009/video-john-resig-testing-performance-analysis-and-jquery-1-4</link>
		<comments>http://davidbcalhoun.com/2009/video-john-resig-testing-performance-analysis-and-jquery-1-4#comments</comments>
		<pubDate>Tue, 22 Dec 2009 03:54:01 +0000</pubDate>
		<dc:creator>David</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[video]]></category>
		<category><![CDATA[john resig]]></category>
		<category><![CDATA[yahoo]]></category>

		<guid isPermaLink="false">http://davidbcalhoun.com/?p=78</guid>
		<description><![CDATA[In case you hadn&#8217;t seen it yet, John Resig was kind enough to stop by Yahoo! for the December Bayjax meetup. Here&#8217;s the video: Usually developers are more interested in just getting the dang code to work, and as a result actual the testing and maintenance of JavaScript isn&#8217;t talked about too much, so I&#8217;m [...]]]></description>
			<content:encoded><![CDATA[<p>In case you hadn&#8217;t seen it yet, <a href="http://ejohn.org/">John Resig</a> was kind enough to stop by Yahoo! for the December <a href="http://www.meetup.com/BayJax/">Bayjax</a> meetup.  Here&#8217;s the <a href="http://developer.yahoo.com/yui/theater/video.php?v=resig-testing">video</a>:</p>
<div class="video" style="width:576px; height: 324px;"><object width="576" height="324"><param name="movie" value="http://d.yimg.com/m/up/ypp/default/player.swf"></param><param name="flashVars" value="vid=17156941&#038;"></param><param name="allowfullscreen" value="true"></param><param name="wmode" value="transparent"></param><embed width="576" height="324" allowFullScreen="true" src="http://d.yimg.com/m/up/ypp/default/player.swf" type="application/x-shockwave-flash" flashvars="vid=17156941&#038;"></embed></object></div>
<p>Usually developers are more interested in just getting the dang code to work, and as a result actual the testing and maintenance of JavaScript isn&#8217;t talked about too much, so I&#8217;m sure this will be new territory for many developers.  And since it&#8217;s John Resig speaking, there was of course a bit about using <a href="http://testswarm.com/">TestSwarm</a>, a testing distributed framework-agnostic automated testing tool (that&#8217;s a mouthful!).</p>
<p>Included in the talk are good things to note while testing, such as the fact unless you&#8217;re running Firefox or Chrome on Windows, all test times have a margin of error of up to 15ms (not to be confused with <a href="http://www.quirksmode.org/blog/archives/2009/08/when_to_read_ou.html">PPK&#8217;s observation of the delay between JavaScript computation and browser rendering</a>).</p>
<p>(via <a href="http://www.yuiblog.com/blog/2009/12/16/video-resig-testing-and-jquery/">YUIBlog</a>)</p>
]]></content:encoded>
			<wfw:commentRss>http://davidbcalhoun.com/2009/video-john-resig-testing-performance-analysis-and-jquery-1-4/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

