<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>Ed at Work</title>
    <link>http://www.ejball.com/EdAtWork/</link>
    <description>Thoughts from the office by Ed Ball</description>
    <copyright>Ed Ball</copyright>
    <lastBuildDate>Tue, 19 Apr 2005 23:44:13 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 1.8.5223.0</generator>
    <managingEditor>ed@libronix.com</managingEditor>
    <webMaster>ed@libronix.com</webMaster>
    <item>
      <trackback:ping>http://www.ejball.com/EdAtWork/Trackback.aspx?guid=95cf774a-ceb7-45b6-983e-c0c43353a0c6</trackback:ping>
      <pingback:server>http://www.ejball.com/EdAtWork/pingback.aspx</pingback:server>
      <pingback:target>http://www.ejball.com/EdAtWork/PermaLink,guid,95cf774a-ceb7-45b6-983e-c0c43353a0c6.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.ejball.com/EdAtWork/CommentView,guid,95cf774a-ceb7-45b6-983e-c0c43353a0c6.aspx</wfw:comment>
      <wfw:commentRss>http://www.ejball.com/EdAtWork/SyndicationService.asmx/GetEntryCommentsRss?guid=95cf774a-ceb7-45b6-983e-c0c43353a0c6</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
      This is hopefully the first of a series of posts about object-oriented programming
      in JavaScript. You can’t get far in JavaScript without learning about functions
      and the built-in object types, but the mechanisms for defining your own object types
      aren’t quite as obvious. Let’s start as simple as we can – we’ll
      create an object that represents a two-dimensional point:
   </p>
        <pre>var pt = {};
pt.X = 3;
pt.Y = 4;</pre>
        <p>
      No surprises there. The <code>pt</code> object has two properties, <code>X</code> and <code>Y</code>.
      We can write functions that manipulate points; for example:
   </p>
        <pre>function MovePoint(pt, dx, dy)
{
  pt.X += dx;
  pt.Y += dy;
}</pre>
        <pre>MovePoint(pt, 1, 2);</pre>
        <p>
      Of course, we’d rather have a <code>Move</code> method on the <code>pt</code> object
      itself.
   </p>
        <pre>pt.Move = function (dx, dy) { this.X += dx; this.Y += dy; };</pre>
        <pre>pt.Move(1, 2);</pre>
        <p>
      When a function is assigned to a property of an object, and that function is called
      using the syntax shown, the special <code>this</code> variable references that object,
      so that when <code>pt.Move</code> is called, <code>this.X</code> refers to the <code>X</code> property
      of <code>pt</code>.
   </p>
        <p>
      Now, it would be rather inconvenient to type all of that every time we need a new
      point, so we can write a function that creates a point.
   </p>
        <pre>function CreatePoint(x, y)
{
  return { X : x, Y : y, Move : Point_Move };
}</pre>
        <pre>function Point_Move(dx, dy)
{
  this.X += dx;
  this.Y += dy;
}</pre>
        <pre>var pt = CreatePoint(3, 4);
pt.Move(1, 2);</pre>
        <p>
      I’ve also taken the liberty of creating a <code>Point_Move</code> function so
      that a new anonymous function isn’t created every time a new point is created.
      (The actual name of the <code>Point_Move</code> function isn’t relevant; I could
      have called it <code>Krebf</code>, but the <code>Point_Move</code> naming convention
      helps me remember that I’m using it as the <code>Move</code> method for a <code>Point</code>.)
   </p>
        <p>
      This actually works quite well, but it would be more natural if we could use the <code>new</code> operator,
      as with built-in objects. Fortunately, this is easy enough to do – we just create
      a function that will serve as the constructor.
   </p>
        <pre>function Point(x, y)
{
  this.X = x;
  this.Y = y;
  this.Move = Point_Move;
}</pre>
        <pre>var pt = new Point (3, 4);
pt.Move(1, 2);</pre>
        <p>
      The two approaches do almost exactly the same thing; <code>new Point</code> creates
      a new object and immediately calls the <code>Point</code> function as if it were a
      member of the new object. There are subtle (and useful) differences that I’ll
      describe in my next post.
   </p>
        <img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=95cf774a-ceb7-45b6-983e-c0c43353a0c6" />
      </body>
      <title>JavaScript: Objects with Methods</title>
      <guid>http://www.ejball.com/EdAtWork/PermaLink,guid,95cf774a-ceb7-45b6-983e-c0c43353a0c6.aspx</guid>
      <link>http://www.ejball.com/EdAtWork/2005/04/19/JavaScriptObjectsWithMethods.aspx</link>
      <pubDate>Tue, 19 Apr 2005 23:44:13 GMT</pubDate>
      <description>&lt;p&gt;
   This is hopefully the first of a series of posts about object-oriented programming
   in JavaScript. You can&amp;#8217;t get far in JavaScript without learning about functions
   and the built-in object types, but the mechanisms for defining your own object types
   aren&amp;#8217;t quite as obvious. Let&amp;#8217;s start as simple as we can &amp;#8211; we&amp;#8217;ll
   create an object that represents a two-dimensional point:
&lt;/p&gt;
&lt;pre&gt;var pt = {};
pt.X = 3;
pt.Y = 4;&lt;/pre&gt;
&lt;p&gt;
   No surprises there. The &lt;code&gt;pt&lt;/code&gt; object has two properties, &lt;code&gt;X&lt;/code&gt; and &lt;code&gt;Y&lt;/code&gt;.
   We can write functions that manipulate points; for example:
&lt;/p&gt;
&lt;pre&gt;function MovePoint(pt, dx, dy)
{
&amp;nbsp; pt.X += dx;
&amp;nbsp; pt.Y += dy;
}&lt;/pre&gt;
&lt;pre&gt;MovePoint(pt, 1, 2);&lt;/pre&gt;
&lt;p&gt;
   Of course, we&amp;#8217;d rather have a &lt;code&gt;Move&lt;/code&gt; method on the &lt;code&gt;pt&lt;/code&gt; object
   itself.
&lt;/p&gt;
&lt;pre&gt;pt.Move = function (dx, dy) { this.X += dx; this.Y += dy; };&lt;/pre&gt;
&lt;pre&gt;pt.Move(1, 2);&lt;/pre&gt;
&lt;p&gt;
   When a function is assigned to a property of an object, and that function is called
   using the syntax shown, the special &lt;code&gt;this&lt;/code&gt; variable references that object,
   so that when &lt;code&gt;pt.Move&lt;/code&gt; is called, &lt;code&gt;this.X&lt;/code&gt; refers to the &lt;code&gt;X&lt;/code&gt; property
   of &lt;code&gt;pt&lt;/code&gt;.
&lt;/p&gt;
&lt;p&gt;
   Now, it would be rather inconvenient to type all of that every time we need a new
   point, so we can write a function that creates a point.
&lt;/p&gt;
&lt;pre&gt;function CreatePoint(x, y)
{
&amp;nbsp; return { X : x, Y : y, Move : Point_Move };
}&lt;/pre&gt;
&lt;pre&gt;function Point_Move(dx, dy)
{
&amp;nbsp; this.X += dx;
&amp;nbsp; this.Y += dy;
}&lt;/pre&gt;
&lt;pre&gt;var pt = CreatePoint(3, 4);
pt.Move(1, 2);&lt;/pre&gt;
&lt;p&gt;
   I&amp;#8217;ve also taken the liberty of creating a &lt;code&gt;Point_Move&lt;/code&gt; function so
   that a new anonymous function isn&amp;#8217;t created every time a new point is created.
   (The actual name of the &lt;code&gt;Point_Move&lt;/code&gt; function isn&amp;#8217;t relevant; I could
   have called it &lt;code&gt;Krebf&lt;/code&gt;, but the &lt;code&gt;Point_Move&lt;/code&gt; naming convention
   helps me remember that I&amp;#8217;m using it as the &lt;code&gt;Move&lt;/code&gt; method for a &lt;code&gt;Point&lt;/code&gt;.)
&lt;/p&gt;
&lt;p&gt;
   This actually works quite well, but it would be more natural if we could use the &lt;code&gt;new&lt;/code&gt; operator,
   as with built-in objects. Fortunately, this is easy enough to do &amp;#8211; we just create
   a function that will serve as the constructor.
&lt;/p&gt;
&lt;pre&gt;function Point(x, y)
{
&amp;nbsp; this.X = x;
&amp;nbsp; this.Y = y;
&amp;nbsp; this.Move = Point_Move;
}&lt;/pre&gt;
&lt;pre&gt;var pt = new Point (3, 4);
pt.Move(1, 2);&lt;/pre&gt;
&lt;p&gt;
   The two approaches do almost exactly the same thing; &lt;code&gt;new Point&lt;/code&gt; creates
   a new object and immediately calls the &lt;code&gt;Point&lt;/code&gt; function as if it were a
   member of the new object. There are subtle (and useful) differences that I&amp;#8217;ll
   describe in my next post.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=95cf774a-ceb7-45b6-983e-c0c43353a0c6" /&gt;</description>
      <comments>http://www.ejball.com/EdAtWork/CommentView,guid,95cf774a-ceb7-45b6-983e-c0c43353a0c6.aspx</comments>
      <category>Code;JavaScript</category>
    </item>
    <item>
      <trackback:ping>http://www.ejball.com/EdAtWork/Trackback.aspx?guid=e97e4da1-e994-4dc4-8a14-d8cc1155e221</trackback:ping>
      <pingback:server>http://www.ejball.com/EdAtWork/pingback.aspx</pingback:server>
      <pingback:target>http://www.ejball.com/EdAtWork/PermaLink,guid,e97e4da1-e994-4dc4-8a14-d8cc1155e221.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.ejball.com/EdAtWork/CommentView,guid,e97e4da1-e994-4dc4-8a14-d8cc1155e221.aspx</wfw:comment>
      <wfw:commentRss>http://www.ejball.com/EdAtWork/SyndicationService.asmx/GetEntryCommentsRss?guid=e97e4da1-e994-4dc4-8a14-d8cc1155e221</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
      Have you ever wanted to determine programmatically the name of the function represented
      by a function object? There’s no direct way to get it, but there is an indirect
      way. The <code>toString</code> method of a function object returns the function declaration,
      from the <code>function</code> keyword at the start all the way to the last closing
      brace. Even “native” functions support the <code>toString</code> method
      in this fashion, though the implementation is omitted. This means that a simple regular
      expression can be used to determine the name of any function.
   </p>
        <pre>function GetFunctionName(fn)
{
  var m = fn.toString().match(/^\s*function\s+([^\s\(]+)/);
  return m ? m[1] : "";
}</pre>
        <p>
      The regular expression simply finds the identifier after the <code>function</code> keyword.
      If it isn’t there (as can be the case with anonymous functions) <code>GetFunctionName</code> returns
      the empty string.
   </p>
        <img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=e97e4da1-e994-4dc4-8a14-d8cc1155e221" />
      </body>
      <title>JavaScript: Function Names</title>
      <guid>http://www.ejball.com/EdAtWork/PermaLink,guid,e97e4da1-e994-4dc4-8a14-d8cc1155e221.aspx</guid>
      <link>http://www.ejball.com/EdAtWork/2005/04/06/JavaScriptFunctionNames.aspx</link>
      <pubDate>Wed, 06 Apr 2005 23:22:20 GMT</pubDate>
      <description>&lt;p&gt;
   Have you ever wanted to determine programmatically the name of the function represented
   by a function object? There&amp;#8217;s no direct way to get it, but there is an indirect
   way. The &lt;code&gt;toString&lt;/code&gt; method of a function object returns the function declaration,
   from the &lt;code&gt;function&lt;/code&gt; keyword at the start all the way to the last closing
   brace. Even &amp;#8220;native&amp;#8221; functions support the &lt;code&gt;toString&lt;/code&gt; method
   in this fashion, though the implementation is omitted. This means that a simple regular
   expression can be used to determine the name of any function.
&lt;/p&gt;
&lt;pre&gt;function GetFunctionName(fn)
{
&amp;nbsp; var m = fn.toString().match(/^\s*function\s+([^\s\(]+)/);
&amp;nbsp; return m ? m[1] : "";
}&lt;/pre&gt;
&lt;p&gt;
   The regular expression simply finds the identifier after the &lt;code&gt;function&lt;/code&gt; keyword.
   If it isn&amp;#8217;t there (as can be the case with anonymous functions) &lt;code&gt;GetFunctionName&lt;/code&gt; returns
   the empty string.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=e97e4da1-e994-4dc4-8a14-d8cc1155e221" /&gt;</description>
      <comments>http://www.ejball.com/EdAtWork/CommentView,guid,e97e4da1-e994-4dc4-8a14-d8cc1155e221.aspx</comments>
      <category>Code;JavaScript</category>
    </item>
    <item>
      <trackback:ping>http://www.ejball.com/EdAtWork/Trackback.aspx?guid=e93378bb-8b8c-4aee-9a6d-8887d04f41ea</trackback:ping>
      <pingback:server>http://www.ejball.com/EdAtWork/pingback.aspx</pingback:server>
      <pingback:target>http://www.ejball.com/EdAtWork/PermaLink,guid,e93378bb-8b8c-4aee-9a6d-8887d04f41ea.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.ejball.com/EdAtWork/CommentView,guid,e93378bb-8b8c-4aee-9a6d-8887d04f41ea.aspx</wfw:comment>
      <wfw:commentRss>http://www.ejball.com/EdAtWork/SyndicationService.asmx/GetEntryCommentsRss?guid=e93378bb-8b8c-4aee-9a6d-8887d04f41ea</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
      My <a href="http://www.ejball.com/EdAtWork/PermaLink.aspx?guid=14c020c7-20a6-47d7-b445-9c3ecda153b2">last
      post</a> described the <code>BindArguments</code> function – it returns an anonymous
      function that, when called, calls another function with the arguments originally specified
      in the call to <code>BindArguments</code>. Put another way, <code>BindArguments</code> converts
      a function that takes <i>n</i> arguments into a function that takes 0 arguments. But
      what if we need a function that takes 1 argument?
   </p>
        <p>
      Imagine we have a <code>Transform</code> function that transforms an array of numbers
      in place:
   </p>
        <pre>function Transform(array, fn)
{
  ForEach(array, function (x, n) { array[n] = fn(x); });
}</pre>
        <p>
      We want to use this <code>Divide</code> function to do the transformation.
   </p>
        <pre>function Divide(n1, n2)
{
  return n1 / n2;
}</pre>
        <p>
      If we want to invert the numbers in the array:
   </p>
        <pre>Transform(array, function (x) { return Divide(1, x); });</pre>
        <p>
      Can we write a binding function like <code>BindArguments</code> that allows us to
      avoid the explicit anonymous function? <code>BindArguments</code> won’t work,
      because it returns a function that takes 0 arguments. If the returned function is
      called with any arguments, those arguments are ignored. We need the returned function
      to accept an argument and call <code>Divide</code> with 1 and that argument. We’ll
      call it <code>BindFirst</code>, because it accepts a function that takes two arguments
      and binds the first one.
   </p>
        <pre>Transform(array, BindFirst(Divide, 1));</pre>
        <p>
      In other words,
   </p>
        <pre>BindFirst(fn, x)(y) === fn(x, y)</pre>
        <p>
      Can we write such a function? Of course!
   </p>
        <pre>function BindFirst(fn, arg)
{
  return function (x) { return fn.call(this, arg, x); };
}</pre>
        <p>
      We can do better and create a function that will bind any number of arguments before
      any number of additional arguments.
   </p>
        <pre>// BindFirst(fn, x1, x2, …, x<em>n</em>)(y1, y2, …, y<em>n</em>)
   === fn(x1, x2, …, x<em>n</em>, y1, y2, …, y<em>n</em>)</pre>
        <pre>function BindFirst(fn)
{
  var args = [];
  for (var n = 1; n &lt; arguments.length; n++)
    args.push(arguments[n]);
  return function ()
    {
      var myargs = [];
      for (var m = 0; m &lt; arguments.length; m++)
        myargs.push(arguments[m]);
      return fn.apply(this, args.concat(myargs));
    };
}</pre>
        <p>
      Outstanding. But wait; what if we want to divide the numbers in our array by 2?
   </p>
        <pre>Transform(array, function (x) { return Divide(x, 2); });</pre>
        <p>
      What we need here is a <code>BindSecond</code> function.
   </p>
        <pre>// BindSecond(fn, x)(y) === fn(y, x)</pre>
        <pre>function BindSecond(fn, arg)
{
  return function (x) { return fn.call(this, x, arg); };
}</pre>
        <pre>Transform(array, BindSecond(Divide, 2));</pre>
        <p>
      Better yet, <code>BindLast</code>, whose implementation I leave as an exercise for
      the reader. (It is <em>very</em> similar to that of <code>BindFirst</code>.)
   </p>
        <pre>// BindLast(fn, x1, x2, …, x<em>n</em>)(y1, y2, …, y<em>n</em>) ===
   fn(y1, y2, …, y<em>n</em>, x1, x2, …, x<em>n</em>)</pre>
        <p>
      Is it possible to write a truly generic <code>Bind</code> function that can be used
      in place of both <code>BindFirst</code> and <code>BindLast</code> and support even
      more complex binding scenarios? It is, and I hope to show it to you… in a future
      post.
   </p>
        <img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=e93378bb-8b8c-4aee-9a6d-8887d04f41ea" />
      </body>
      <title>JavaScript: Advanced Binding</title>
      <guid>http://www.ejball.com/EdAtWork/PermaLink,guid,e93378bb-8b8c-4aee-9a6d-8887d04f41ea.aspx</guid>
      <link>http://www.ejball.com/EdAtWork/2005/04/05/JavaScriptAdvancedBinding.aspx</link>
      <pubDate>Tue, 05 Apr 2005 20:31:44 GMT</pubDate>
      <description>&lt;p&gt;
   My &lt;a href="http://www.ejball.com/EdAtWork/PermaLink.aspx?guid=14c020c7-20a6-47d7-b445-9c3ecda153b2"&gt;last
   post&lt;/a&gt; described the &lt;code&gt;BindArguments&lt;/code&gt; function &amp;#8211; it returns an anonymous
   function that, when called, calls another function with the arguments originally specified
   in the call to &lt;code&gt;BindArguments&lt;/code&gt;. Put another way, &lt;code&gt;BindArguments&lt;/code&gt; converts
   a function that takes &lt;i&gt;n&lt;/i&gt; arguments into a function that takes 0 arguments. But
   what if we need a function that takes 1 argument?
&lt;/p&gt;
&lt;p&gt;
   Imagine we have a &lt;code&gt;Transform&lt;/code&gt; function that transforms an array of numbers
   in place:
&lt;/p&gt;
&lt;pre&gt;function Transform(array, fn)
{
&amp;nbsp; ForEach(array, function (x, n) { array[n] = fn(x); });
}&lt;/pre&gt;
&lt;p&gt;
   We want to use this &lt;code&gt;Divide&lt;/code&gt; function to do the transformation.
&lt;/p&gt;
&lt;pre&gt;function Divide(n1, n2)
{
&amp;nbsp; return n1 / n2;
}&lt;/pre&gt;
&lt;p&gt;
   If we want to invert the numbers in the array:
&lt;/p&gt;
&lt;pre&gt;Transform(array, function (x) { return Divide(1, x); });&lt;/pre&gt;
&lt;p&gt;
   Can we write a binding function like &lt;code&gt;BindArguments&lt;/code&gt; that allows us to
   avoid the explicit anonymous function? &lt;code&gt;BindArguments&lt;/code&gt; won&amp;#8217;t work,
   because it returns a function that takes 0 arguments. If the returned function is
   called with any arguments, those arguments are ignored. We need the returned function
   to accept an argument and call &lt;code&gt;Divide&lt;/code&gt; with 1 and that argument. We&amp;#8217;ll
   call it &lt;code&gt;BindFirst&lt;/code&gt;, because it accepts a function that takes two arguments
   and binds the first one.
&lt;/p&gt;
&lt;pre&gt;Transform(array, BindFirst(Divide, 1));&lt;/pre&gt;
&lt;p&gt;
   In other words,
&lt;/p&gt;
&lt;pre&gt;BindFirst(fn, x)(y) === fn(x, y)&lt;/pre&gt;
&lt;p&gt;
   Can we write such a function? Of course!
&lt;/p&gt;
&lt;pre&gt;function BindFirst(fn, arg)
{
&amp;nbsp; return function (x) { return fn.call(this, arg, x); };
}&lt;/pre&gt;
&lt;p&gt;
   We can do better and create a function that will bind any number of arguments before
   any number of additional arguments.
&lt;/p&gt;
&lt;pre&gt;// BindFirst(fn, x1, x2, &amp;#8230;, x&lt;em&gt;n&lt;/em&gt;)(y1, y2, &amp;#8230;, y&lt;em&gt;n&lt;/em&gt;)
=== fn(x1, x2, &amp;#8230;, x&lt;em&gt;n&lt;/em&gt;, y1, y2, &amp;#8230;, y&lt;em&gt;n&lt;/em&gt;)&lt;/pre&gt;
&lt;pre&gt;function BindFirst(fn)
{
&amp;nbsp; var args = [];
&amp;nbsp; for (var n = 1; n &amp;lt; arguments.length; n++)
&amp;nbsp;&amp;nbsp;&amp;nbsp; args.push(arguments[n]);
&amp;nbsp; return function ()
&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; var myargs = [];
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; for (var m = 0; m &amp;lt; arguments.length; m++)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; myargs.push(arguments[m]);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return fn.apply(this, args.concat(myargs));
&amp;nbsp;&amp;nbsp;&amp;nbsp; };
}&lt;/pre&gt;
&lt;p&gt;
   Outstanding. But wait; what if we want to divide the numbers in our array by 2?
&lt;/p&gt;
&lt;pre&gt;Transform(array, function (x) { return Divide(x, 2); });&lt;/pre&gt;
&lt;p&gt;
   What we need here is a &lt;code&gt;BindSecond&lt;/code&gt; function.
&lt;/p&gt;
&lt;pre&gt;// BindSecond(fn, x)(y) === fn(y, x)&lt;/pre&gt;
&lt;pre&gt;function BindSecond(fn, arg)
{
&amp;nbsp; return function (x) { return fn.call(this, x, arg); };
}&lt;/pre&gt;
&lt;pre&gt;Transform(array, BindSecond(Divide, 2));&lt;/pre&gt;
&lt;p&gt;
   Better yet, &lt;code&gt;BindLast&lt;/code&gt;, whose implementation I leave as an exercise for
   the reader. (It is &lt;em&gt;very&lt;/em&gt; similar to that of &lt;code&gt;BindFirst&lt;/code&gt;.)
&lt;/p&gt;
&lt;pre&gt;// BindLast(fn, x1, x2, &amp;#8230;, x&lt;em&gt;n&lt;/em&gt;)(y1, y2, &amp;#8230;, y&lt;em&gt;n&lt;/em&gt;) ===
fn(y1, y2, &amp;#8230;, y&lt;em&gt;n&lt;/em&gt;, x1, x2, &amp;#8230;, x&lt;em&gt;n&lt;/em&gt;)&lt;/pre&gt;
&lt;p&gt;
   Is it possible to write a truly generic &lt;code&gt;Bind&lt;/code&gt; function that can be used
   in place of both &lt;code&gt;BindFirst&lt;/code&gt; and &lt;code&gt;BindLast&lt;/code&gt; and support even
   more complex binding scenarios? It is, and I hope to show it to you&amp;#8230; in a future
   post.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=e93378bb-8b8c-4aee-9a6d-8887d04f41ea" /&gt;</description>
      <comments>http://www.ejball.com/EdAtWork/CommentView,guid,e93378bb-8b8c-4aee-9a6d-8887d04f41ea.aspx</comments>
      <category>Code;JavaScript</category>
    </item>
    <item>
      <trackback:ping>http://www.ejball.com/EdAtWork/Trackback.aspx?guid=14c020c7-20a6-47d7-b445-9c3ecda153b2</trackback:ping>
      <pingback:server>http://www.ejball.com/EdAtWork/pingback.aspx</pingback:server>
      <pingback:target>http://www.ejball.com/EdAtWork/PermaLink,guid,14c020c7-20a6-47d7-b445-9c3ecda153b2.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.ejball.com/EdAtWork/CommentView,guid,14c020c7-20a6-47d7-b445-9c3ecda153b2.aspx</wfw:comment>
      <wfw:commentRss>http://www.ejball.com/EdAtWork/SyndicationService.asmx/GetEntryCommentsRss?guid=14c020c7-20a6-47d7-b445-9c3ecda153b2</wfw:commentRss>
      <slash:comments>8</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
      When you start passing functions around, you often end up creating anonymous functions
      that call other functions with specific arguments.
   </p>
        <p>
      For example, let’s suppose that we’re writing a DHTML calculator, and
      we have a function <code>WriteDigit</code> that writes the specified digit to the
      display. To set the <code>onclick</code> handlers of the calculator buttons, we could
      do something like this:
   </p>
        <pre>btnOne.onclick = function () { WriteDigit(1); };
btnTwo.onclick = function () { WriteDigit(2); };</pre>
        <p>
      That will work just fine, but there is another way. We can write a function that takes
      an integer as its argument and returns the anonymous function.
   </p>
        <pre>function BindWriteDigit(n)
{
  return function () { WriteDigit(n); };
}</pre>
        <pre>btnOne.onclick = BindWriteDigit(1);
btnTwo.onclick = BindWriteDigit(2);</pre>
        <p>
      Why would we do such a thing? Well, one good reason is to avoid unwanted closures.
      Whenever you create an anonymous function, you’ve got to pay attention to the
      local variables that will be kept alive, particularly under Internet Explorer, as
      I alluded to in a <a href="http://www.ejball.com/EdAtWork/PermaLink.aspx?guid=481764a7-5831-46f0-aabe-2b0f5c635995">previous
      post</a>. In general, when you are creating anonymous functions that will outlive
      the function that is creating them, you should minimize the number of local variables
      in that surrounding function to prevent unwanted closures, accidental modification
      of local variables used by the anonymous function, and other surprises.
   </p>
        <p>
      It would be a pain to write a separate binding function for every function that we
      want to bind; fortunately, we can write a function that takes a function as its first
      argument and returns an anonymous function that calls that function with its second
      argument.
   </p>
        <pre>function BindArgument(fn, arg)
{
  return function () { return fn(arg); };
}</pre>
        <pre>btnOne.onclick = BindArgument(WriteDigit, 1);
btnTwo.onclick = BindArgument(WriteDigit, 2);</pre>
        <p>
      No need to stop with one argument, though; with a little more effort, we can write
      a function that will bind to any number of arguments by using the <code>apply</code> method.
   </p>
        <pre>function BindArguments(fn)
{
  var args = [];
  for (var n = 1; n &lt; arguments.length; n++)
    args.push(arguments[n]);
  return function () { return fn.apply(this, args); };
}</pre>
        <pre>btnOne.onclick = BindArguments(WriteDigit, 1);
btnTwo.onclick = BindArguments(WriteDigit, 2);</pre>
        <p>
      This technique comes in very handy, particularly in problems that are less contrived
      than this one. You can do a lot more than this with a sufficiently complex binding
      function; more on that in a <a href="http://www.ejball.com/EdAtWork/PermaLink.aspx?guid=e93378bb-8b8c-4aee-9a6d-8887d04f41ea">future
      post</a>.
   </p>
        <p>
          <strong>Update:</strong> Fixed a bug in <code>BindArguments</code>. (Thanks, Bradley!)
   </p>
        <img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=14c020c7-20a6-47d7-b445-9c3ecda153b2" />
      </body>
      <title>JavaScript: Binding Function Arguments</title>
      <guid>http://www.ejball.com/EdAtWork/PermaLink,guid,14c020c7-20a6-47d7-b445-9c3ecda153b2.aspx</guid>
      <link>http://www.ejball.com/EdAtWork/2005/03/31/JavaScriptBindingFunctionArguments.aspx</link>
      <pubDate>Thu, 31 Mar 2005 21:50:13 GMT</pubDate>
      <description>&lt;p&gt;
   When you start passing functions around, you often end up creating anonymous functions
   that call other functions with specific arguments.
&lt;/p&gt;
&lt;p&gt;
   For example, let&amp;#8217;s suppose that we&amp;#8217;re writing a DHTML calculator, and
   we have a function &lt;code&gt;WriteDigit&lt;/code&gt; that writes the specified digit to the
   display. To set the &lt;code&gt;onclick&lt;/code&gt; handlers of the calculator buttons, we could
   do something like this:
&lt;/p&gt;
&lt;pre&gt;btnOne.onclick = function () { WriteDigit(1); };
btnTwo.onclick = function () { WriteDigit(2); };&lt;/pre&gt;
&lt;p&gt;
   That will work just fine, but there is another way. We can write a function that takes
   an integer as its argument and returns the anonymous function.
&lt;/p&gt;
&lt;pre&gt;function BindWriteDigit(n)
{
&amp;nbsp; return function () { WriteDigit(n); };
}&lt;/pre&gt;
&lt;pre&gt;btnOne.onclick = BindWriteDigit(1);
btnTwo.onclick = BindWriteDigit(2);&lt;/pre&gt;
&lt;p&gt;
   Why would we do such a thing? Well, one good reason is to avoid unwanted closures.
   Whenever you create an anonymous function, you&amp;#8217;ve got to pay attention to the
   local variables that will be kept alive, particularly under Internet Explorer, as
   I alluded to in a &lt;a href="http://www.ejball.com/EdAtWork/PermaLink.aspx?guid=481764a7-5831-46f0-aabe-2b0f5c635995"&gt;previous
   post&lt;/a&gt;. In general, when you are creating anonymous functions that will outlive
   the function that is creating them, you should minimize the number of local variables
   in that surrounding function to prevent unwanted closures, accidental modification
   of local variables used by the anonymous function, and other surprises.
&lt;/p&gt;
&lt;p&gt;
   It would be a pain to write a separate binding function for every function that we
   want to bind; fortunately, we can write a function that takes a function as its first
   argument and returns an anonymous function that calls that function with its second
   argument.
&lt;/p&gt;
&lt;pre&gt;function BindArgument(fn, arg)
{
&amp;nbsp; return function () { return fn(arg); };
}&lt;/pre&gt;
&lt;pre&gt;btnOne.onclick = BindArgument(WriteDigit, 1);
btnTwo.onclick = BindArgument(WriteDigit, 2);&lt;/pre&gt;
&lt;p&gt;
   No need to stop with one argument, though; with a little more effort, we can write
   a function that will bind to any number of arguments by using the &lt;code&gt;apply&lt;/code&gt; method.
&lt;/p&gt;
&lt;pre&gt;function BindArguments(fn)
{
&amp;nbsp; var args = [];
&amp;nbsp; for (var n = 1; n &amp;lt; arguments.length; n++)
&amp;nbsp;&amp;nbsp;&amp;nbsp; args.push(arguments[n]);
&amp;nbsp; return function () { return fn.apply(this, args); };
}&lt;/pre&gt;
&lt;pre&gt;btnOne.onclick = BindArguments(WriteDigit, 1);
btnTwo.onclick = BindArguments(WriteDigit, 2);&lt;/pre&gt;
&lt;p&gt;
   This technique comes in very handy, particularly in problems that are less contrived
   than this one. You can do a lot more than this with a sufficiently complex binding
   function; more on that in a &lt;a href="http://www.ejball.com/EdAtWork/PermaLink.aspx?guid=e93378bb-8b8c-4aee-9a6d-8887d04f41ea"&gt;future
   post&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
   &lt;strong&gt;Update:&lt;/strong&gt; Fixed a bug in &lt;code&gt;BindArguments&lt;/code&gt;. (Thanks, Bradley!)
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=14c020c7-20a6-47d7-b445-9c3ecda153b2" /&gt;</description>
      <comments>http://www.ejball.com/EdAtWork/CommentView,guid,14c020c7-20a6-47d7-b445-9c3ecda153b2.aspx</comments>
      <category>Code;JavaScript</category>
    </item>
    <item>
      <trackback:ping>http://www.ejball.com/EdAtWork/Trackback.aspx?guid=c2d0f53f-afc7-4831-b60e-f4354ae3f7fa</trackback:ping>
      <pingback:server>http://www.ejball.com/EdAtWork/pingback.aspx</pingback:server>
      <pingback:target>http://www.ejball.com/EdAtWork/PermaLink,guid,c2d0f53f-afc7-4831-b60e-f4354ae3f7fa.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.ejball.com/EdAtWork/CommentView,guid,c2d0f53f-afc7-4831-b60e-f4354ae3f7fa.aspx</wfw:comment>
      <wfw:commentRss>http://www.ejball.com/EdAtWork/SyndicationService.asmx/GetEntryCommentsRss?guid=c2d0f53f-afc7-4831-b60e-f4354ae3f7fa</wfw:commentRss>
      <slash:comments>3</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
      As I <a href="http://www.ejball.com/EdAtWork/PermaLink.aspx?guid=ff4814cd-3d23-46b8-bb11-cbbc7d20d900">mentioned
      before</a>, <code>for...in</code> would be a convenient way to enumerate arrays, if
      it actually worked the way you’d expect it to. Fortunately, anonymous functions
      make it possible to write a <code>ForEach</code> method that’s almost as easy
      to use as a proper <code>foreach</code>.
   </p>
        <pre>function ForEach(array, fn)
{
  for (var n = 0; n &lt; array.length; n++)
    fn(array[n]);
}</pre>
        <p>
      As you can see, <code>ForEach</code> calls the specified function for each element
      of the array. So if you’d like to calculate the sum of the items in an array:
   </p>
        <pre>function SumArray(array)
{
  var nSum = 0;
  ForEach(array, function (n) { nSum += n; });
  return nSum;
}</pre>
        <p>
      I hope you agree that this syntax is not only more compact than an explicit loop,
      but that it is also easier to understand. It is also less efficient, of course, but
      not significantly so, except in special cases where you would certainly measure to
      determine its impact; you could easily unravel it into a standard loop if necessary.
   </p>
        <p>
      My preferred implementation of <code>ForEach</code> is slightly more complicated.
   </p>
        <pre>function ForEach(array, fn, objThis)
{
  objThis = objThis || this;
  var len = array.length;
  for (var n = 0; n &lt; len; n++)
  {
    var r = fn.call(objThis, array[n], n);
    if (r !== undefined)
      return r;
  }
}</pre>
        <p>
      Let me explain:
   </p>
        <ul>
          <li>
         Calculating the array length outside the loop can be slightly faster. 
      </li>
          <li>
         I pass the item index as the second argument to the called function, since that can
         often be useful. (The called function doesn’t need to declare it as an explicit
         argument if it doesn’t need it.) 
      </li>
          <li>
         If the called function returns anything but <code>undefined</code>, the loop is terminated.
         This allows us to simulate what would be a <code>break</code> statement in a normal <code>for</code> loop.
         The <code>ForEach</code> method returns the value returned by the called function. 
      </li>
          <li>
         If the called function returns <code>undefined</code>, the loop continues. (A function
         returns <code>undefined</code> if it gets to the end without hitting a <code>return</code> statement,
         if it hits a <code>return</code> statement without an expression, or if it hits a <code>return
         undefined</code> (naturally).) An explicit <code>return</code> statement without an
         expression thus simulates what would be a <code>continue</code> statement in a normal <code>for</code> loop. 
      </li>
          <li>
         Using the <code>call</code> method allows us to specify <code>this</code> for the
         called function, which can be useful when calling <code>ForEach</code> from an object
         method. 
      </li>
          <li>
         The <code>objThis</code> argument is optional, but I make sure that it is never <code>undefined</code>,
         because under Internet Explorer, the <code>call</code> method is slightly faster when
         the first argument is a valid object (passing <code>undefined</code> forces it to
         determine the “global” object itself).</li>
        </ul>
        <p>
      For example, we can use <code>ForEach</code> to find an item in an array, returning
      the index of that item, or <code>-1</code> if the item is not found.
   </p>
        <pre>function FindInArray(array, find)
{
  var index = ForEach(array,
    function (item, n)
    {
      if (item == find)
        return n;
    });
  return index === undefined ? -1 : index;
}</pre>
        <p>
      In many cases (but not all) I have found that using <code>ForEach</code> is easier
      to write and more natural than an explicit loop. YMMV.
   </p>
        <p>
          <strong>Update:</strong> Explicitly described how to simulate a <code>continue</code>;
      thanks to Eli for his comment.
   </p>
        <img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=c2d0f53f-afc7-4831-b60e-f4354ae3f7fa" />
      </body>
      <title>JavaScript: ForEach</title>
      <guid>http://www.ejball.com/EdAtWork/PermaLink,guid,c2d0f53f-afc7-4831-b60e-f4354ae3f7fa.aspx</guid>
      <link>http://www.ejball.com/EdAtWork/2005/03/30/JavaScriptForEach.aspx</link>
      <pubDate>Wed, 30 Mar 2005 16:53:48 GMT</pubDate>
      <description>&lt;p&gt;
   As I &lt;a href="http://www.ejball.com/EdAtWork/PermaLink.aspx?guid=ff4814cd-3d23-46b8-bb11-cbbc7d20d900"&gt;mentioned
   before&lt;/a&gt;, &lt;code&gt;for...in&lt;/code&gt; would be a convenient way to enumerate arrays, if
   it actually worked the way you&amp;#8217;d expect it to. Fortunately, anonymous functions
   make it possible to write a &lt;code&gt;ForEach&lt;/code&gt; method that&amp;#8217;s almost as easy
   to use as a proper &lt;code&gt;foreach&lt;/code&gt;.
&lt;/p&gt;
&lt;pre&gt;function ForEach(array, fn)
{
&amp;nbsp; for (var n = 0; n &amp;lt; array.length; n++)
&amp;nbsp;&amp;nbsp;&amp;nbsp; fn(array[n]);
}&lt;/pre&gt;
&lt;p&gt;
   As you can see, &lt;code&gt;ForEach&lt;/code&gt; calls the specified function for each element
   of the array. So if you&amp;#8217;d like to calculate the sum of the items in an array:
&lt;/p&gt;
&lt;pre&gt;function SumArray(array)
{
&amp;nbsp; var nSum = 0;
&amp;nbsp; ForEach(array, function (n) { nSum += n; });
&amp;nbsp; return nSum;
}&lt;/pre&gt;
&lt;p&gt;
   I hope you agree that this syntax is not only more compact than an explicit loop,
   but that it is also easier to understand. It is also less efficient, of course, but
   not significantly so, except in special cases where you would certainly measure to
   determine its impact; you could easily unravel it into a standard loop if necessary.
&lt;/p&gt;
&lt;p&gt;
   My preferred implementation of &lt;code&gt;ForEach&lt;/code&gt; is slightly more complicated.
&lt;/p&gt;
&lt;pre&gt;function ForEach(array, fn, objThis)
{
&amp;nbsp; objThis = objThis || this;
&amp;nbsp; var len = array.length;
&amp;nbsp; for (var n = 0; n &amp;lt; len; n++)
&amp;nbsp; {
&amp;nbsp;&amp;nbsp;&amp;nbsp; var r = fn.call(objThis, array[n], n);
&amp;nbsp;&amp;nbsp;&amp;nbsp; if (r !== undefined)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return r;
&amp;nbsp; }
}&lt;/pre&gt;
&lt;p&gt;
   Let me explain:
&lt;/p&gt;
&lt;ul&gt;
   &lt;li&gt;
      Calculating the array length outside the loop can be slightly faster. 
   &lt;li&gt;
      I pass the item index as the second argument to the called function, since that can
      often be useful. (The called function doesn&amp;#8217;t need to declare it as an explicit
      argument if it doesn&amp;#8217;t need it.) 
   &lt;li&gt;
      If the called function returns anything but &lt;code&gt;undefined&lt;/code&gt;, the loop is terminated.
      This allows us to simulate what would be a &lt;code&gt;break&lt;/code&gt; statement in a normal &lt;code&gt;for&lt;/code&gt; loop.
      The &lt;code&gt;ForEach&lt;/code&gt; method returns the value returned by the called function. 
   &lt;li&gt;
      If the called function returns &lt;code&gt;undefined&lt;/code&gt;, the loop continues. (A function
      returns &lt;code&gt;undefined&lt;/code&gt; if it gets to the end without hitting a &lt;code&gt;return&lt;/code&gt; statement,
      if it hits a &lt;code&gt;return&lt;/code&gt; statement without an expression, or if it hits a &lt;code&gt;return
      undefined&lt;/code&gt; (naturally).) An explicit &lt;code&gt;return&lt;/code&gt; statement without an
      expression thus simulates what would be a &lt;code&gt;continue&lt;/code&gt; statement in a normal &lt;code&gt;for&lt;/code&gt; loop. 
   &lt;li&gt;
      Using the &lt;code&gt;call&lt;/code&gt; method allows us to specify &lt;code&gt;this&lt;/code&gt; for the
      called function, which can be useful when calling &lt;code&gt;ForEach&lt;/code&gt; from an object
      method. 
   &lt;li&gt;
      The &lt;code&gt;objThis&lt;/code&gt; argument is optional, but I make sure that it is never &lt;code&gt;undefined&lt;/code&gt;,
      because under Internet Explorer, the &lt;code&gt;call&lt;/code&gt; method is slightly faster when
      the first argument is a valid object (passing &lt;code&gt;undefined&lt;/code&gt; forces it to
      determine the &amp;#8220;global&amp;#8221; object itself).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
   For example, we can use &lt;code&gt;ForEach&lt;/code&gt; to find an item in an array, returning
   the index of that item, or &lt;code&gt;-1&lt;/code&gt; if the item is not found.
&lt;/p&gt;
&lt;pre&gt;function FindInArray(array, find)
{
&amp;nbsp; var index = ForEach(array,
&amp;nbsp;&amp;nbsp;&amp;nbsp; function (item, n)
&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (item == find)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return n;
&amp;nbsp;&amp;nbsp;&amp;nbsp; });
&amp;nbsp; return index === undefined ? -1 : index;
}&lt;/pre&gt;
&lt;p&gt;
   In many cases (but not all) I have found that using &lt;code&gt;ForEach&lt;/code&gt; is easier
   to write and more natural than an explicit loop. YMMV.
&lt;/p&gt;
&lt;p&gt;
   &lt;strong&gt;Update:&lt;/strong&gt; Explicitly described how to simulate a &lt;code&gt;continue&lt;/code&gt;;
   thanks to Eli for his comment.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=c2d0f53f-afc7-4831-b60e-f4354ae3f7fa" /&gt;</description>
      <comments>http://www.ejball.com/EdAtWork/CommentView,guid,c2d0f53f-afc7-4831-b60e-f4354ae3f7fa.aspx</comments>
      <category>Code;JavaScript</category>
    </item>
    <item>
      <trackback:ping>http://www.ejball.com/EdAtWork/Trackback.aspx?guid=481764a7-5831-46f0-aabe-2b0f5c635995</trackback:ping>
      <pingback:server>http://www.ejball.com/EdAtWork/pingback.aspx</pingback:server>
      <pingback:target>http://www.ejball.com/EdAtWork/PermaLink,guid,481764a7-5831-46f0-aabe-2b0f5c635995.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.ejball.com/EdAtWork/CommentView,guid,481764a7-5831-46f0-aabe-2b0f5c635995.aspx</wfw:comment>
      <wfw:commentRss>http://www.ejball.com/EdAtWork/SyndicationService.asmx/GetEntryCommentsRss?guid=481764a7-5831-46f0-aabe-2b0f5c635995</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
      Let’s say you want to sort an array of integers.
   </p>
        <pre>var array = [ 3, 14, 15, 9, 26 ];</pre>
        <p>
      You might think that you could just use the <code>sort</code> method of the <code>Array</code>.
      You’d be wrong.
   </p>
        <pre>array.sort(); // [ 14, 15, 26, 3, 9 ]</pre>
        <p>
      The <code>sort</code> method of an <code>Array</code> always sorts strings, which
      produces the unexpected result shown above. However, you can pass a function to the <code>sort</code> method.
   </p>
        <pre>function CompareIntegers(x, y) { return x - y; }
array.sort(CompareIntegers); // [ 3, 9, 14, 15, 26 ]</pre>
        <p>
      Now we’re talking. The <code>CompareIntegers</code> function returns a positive
      integer if <code>x &gt; y</code>, a negative integer if <code>x &lt; y</code>, and
      zero if <code>x == y</code>, which is what we needed for the <code>sort</code> method.
   </p>
        <p>
      What if we wanted to sort the numbers in reverse order? Well, we could define a <code>CompareIntegersDescending</code> function,
      but it’s easier to use an anonymous function.
   </p>
        <pre>array.sort(function (x, y) { return y - x; }); // [ 26, 15, 14, 9, 3 ]</pre>
        <p>
      Very convenient. Here’s a function that can be used to find an item in an array.
   </p>
        <pre>function Find(array, fn)
{
  for (var n = 0; n &lt; array.length; n++)
    if (fn(array[n]))
      return n;
  return -1;
}</pre>
        <p>
      The first argument is the array to search; the second argument is a function that
      returns <code>true</code> when the item has been found. We can use the <code>Find</code> function
      to find the index of the first item greater than 10:
   </p>
        <pre>function FindGreaterThanTen(array)
{
  return Find(array, function (x) { return x &gt; 10; });
}</pre>
        <p>
      But what if you want to find the first item greater than an arbitrary number? Remarkably,
      this works fine:
   </p>
        <pre>function FindGreaterThan(array, n)
{
  return Find(array, function (x) { return x &gt; n; });
}</pre>
        <p>
      This demonstrates the true power of anonymous functions. The definition of an anonymous
      function has access to any and every variable that was visible where the function
      was defined, including local variables. Furthermore, it retains access to those variables
      as long as the anonymous function lives, even after the calling function has returned!
      An anonymous function used in this way is called a “closure.”
   </p>
        <p>
      Whenever you create an anonymous function that is stored in such a way that it will
      outlive the function call that created it (which is <em>not</em> the case in the example
      above) you need to keep in mind that every local variable of that function call will
      live as long as the anonymous function lives. (That’s right – <em>every</em> local
      variable, not just the variables that the anonymous function happens to use.) If any
      of the local variables are references to objects that aren’t needed by the anonymous
      function, this could prevent garbage collection from freeing otherwise unused memory;
      if the objects reference large amounts of memory, this can quickly become a serious
      performance problem. If you’re working with Internet Explorer, you should also
      be aware of a serious <a href="http://jibbering.com/faq/faq_notes/closures.html#clMem">memory
      leak</a> that occurs when reference cycles are created that involve DOM nodes; these
      cycles are easy to create inadvertently when using anonymous functions as event handlers.
   </p>
        <p>
      Occasionally, you’ll want an anonymous function to support recursion, in which
      case you can use <code>arguments.callee</code> to reference the otherwise unnamed
      function.
   </p>
        <pre>var fnClearAll = function (obj)
  {
    for (var key in obj)
      arguments.callee(obj[key]);
    Clear(obj);
  };</pre>
        <p>
      Now that I’ve talked about anonymous functions, I can describe my favorite way
      to enumerate an array – see my <a href="http://www.ejball.com/EdAtWork/PermaLink.aspx?guid=c2d0f53f-afc7-4831-b60e-f4354ae3f7fa">next
      post</a> for a description of the <code>ForEach</code> function.
   </p>
        <img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=481764a7-5831-46f0-aabe-2b0f5c635995" />
      </body>
      <title>JavaScript: Anonymous Functions</title>
      <guid>http://www.ejball.com/EdAtWork/PermaLink,guid,481764a7-5831-46f0-aabe-2b0f5c635995.aspx</guid>
      <link>http://www.ejball.com/EdAtWork/2005/03/28/JavaScriptAnonymousFunctions.aspx</link>
      <pubDate>Mon, 28 Mar 2005 20:42:10 GMT</pubDate>
      <description>&lt;p&gt;
   Let&amp;#8217;s say you want to sort an array of integers.
&lt;/p&gt;
&lt;pre&gt;var array = [ 3, 14, 15, 9, 26 ];&lt;/pre&gt;
&lt;p&gt;
   You might think that you could just use the &lt;code&gt;sort&lt;/code&gt; method of the &lt;code&gt;Array&lt;/code&gt;.
   You&amp;#8217;d be wrong.
&lt;/p&gt;
&lt;pre&gt;array.sort(); // [ 14, 15, 26, 3, 9 ]&lt;/pre&gt;
&lt;p&gt;
   The &lt;code&gt;sort&lt;/code&gt; method of an &lt;code&gt;Array&lt;/code&gt; always sorts strings, which
   produces the unexpected result shown above. However, you can pass a function to the &lt;code&gt;sort&lt;/code&gt; method.
&lt;/p&gt;
&lt;pre&gt;function CompareIntegers(x, y) { return x - y; }
array.sort(CompareIntegers); // [ 3, 9, 14, 15, 26 ]&lt;/pre&gt;
&lt;p&gt;
   Now we&amp;#8217;re talking. The &lt;code&gt;CompareIntegers&lt;/code&gt; function returns a positive
   integer if &lt;code&gt;x &amp;gt; y&lt;/code&gt;, a negative integer if &lt;code&gt;x &amp;lt; y&lt;/code&gt;, and
   zero if &lt;code&gt;x == y&lt;/code&gt;, which is what we needed for the &lt;code&gt;sort&lt;/code&gt; method.
&lt;/p&gt;
&lt;p&gt;
   What if we wanted to sort the numbers in reverse order? Well, we could define a &lt;code&gt;CompareIntegersDescending&lt;/code&gt; function,
   but it&amp;#8217;s easier to use an anonymous function.
&lt;/p&gt;
&lt;pre&gt;array.sort(function (x, y) { return y - x; }); // [ 26, 15, 14, 9, 3 ]&lt;/pre&gt;
&lt;p&gt;
   Very convenient. Here&amp;#8217;s a function that can be used to find an item in an array.
&lt;/p&gt;
&lt;pre&gt;function Find(array, fn)
{
&amp;nbsp; for (var n = 0; n &amp;lt; array.length; n++)
&amp;nbsp;&amp;nbsp;&amp;nbsp; if (fn(array[n]))
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return n;
&amp;nbsp; return -1;
}&lt;/pre&gt;
&lt;p&gt;
   The first argument is the array to search; the second argument is a function that
   returns &lt;code&gt;true&lt;/code&gt; when the item has been found. We can use the &lt;code&gt;Find&lt;/code&gt; function
   to find the index of the first item greater than 10:
&lt;/p&gt;
&lt;pre&gt;function FindGreaterThanTen(array)
{
&amp;nbsp; return Find(array, function (x) { return x &amp;gt; 10; });
}&lt;/pre&gt;
&lt;p&gt;
   But what if you want to find the first item greater than an arbitrary number? Remarkably,
   this works fine:
&lt;/p&gt;
&lt;pre&gt;function FindGreaterThan(array, n)
{
&amp;nbsp; return Find(array, function (x) { return x &amp;gt; n; });
}&lt;/pre&gt;
&lt;p&gt;
   This demonstrates the true power of anonymous functions. The definition of an anonymous
   function has access to any and every variable that was visible where the function
   was defined, including local variables. Furthermore, it retains access to those variables
   as long as the anonymous function lives, even after the calling function has returned!
   An anonymous function used in this way is called a &amp;#8220;closure.&amp;#8221;
&lt;/p&gt;
&lt;p&gt;
   Whenever you create an anonymous function that is stored in such a way that it will
   outlive the function call that created it (which is &lt;em&gt;not&lt;/em&gt; the case in the example
   above) you need to keep in mind that every local variable of that function call will
   live as long as the anonymous function lives. (That&amp;#8217;s right &amp;#8211; &lt;em&gt;every&lt;/em&gt; local
   variable, not just the variables that the anonymous function happens to use.) If any
   of the local variables are references to objects that aren&amp;#8217;t needed by the anonymous
   function, this could prevent garbage collection from freeing otherwise unused memory;
   if the objects reference large amounts of memory, this can quickly become a serious
   performance problem. If you&amp;#8217;re working with Internet Explorer, you should also
   be aware of a serious &lt;a href="http://jibbering.com/faq/faq_notes/closures.html#clMem"&gt;memory
   leak&lt;/a&gt; that occurs when reference cycles are created that involve DOM nodes; these
   cycles are easy to create inadvertently when using anonymous functions as event handlers.
&lt;/p&gt;
&lt;p&gt;
   Occasionally, you&amp;#8217;ll want an anonymous function to support recursion, in which
   case you can use &lt;code&gt;arguments.callee&lt;/code&gt; to reference the otherwise unnamed
   function.
&lt;/p&gt;
&lt;pre&gt;var fnClearAll = function (obj)
&amp;nbsp; {
&amp;nbsp;&amp;nbsp;&amp;nbsp; for (var key in obj)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; arguments.callee(obj[key]);
&amp;nbsp;&amp;nbsp;&amp;nbsp; Clear(obj);
&amp;nbsp; };&lt;/pre&gt;
&lt;p&gt;
   Now that I&amp;#8217;ve talked about anonymous functions, I can describe my favorite way
   to enumerate an array &amp;#8211; see my &lt;a href="http://www.ejball.com/EdAtWork/PermaLink.aspx?guid=c2d0f53f-afc7-4831-b60e-f4354ae3f7fa"&gt;next
   post&lt;/a&gt; for a description of the &lt;code&gt;ForEach&lt;/code&gt; function.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=481764a7-5831-46f0-aabe-2b0f5c635995" /&gt;</description>
      <comments>http://www.ejball.com/EdAtWork/CommentView,guid,481764a7-5831-46f0-aabe-2b0f5c635995.aspx</comments>
      <category>Code;JavaScript</category>
    </item>
    <item>
      <trackback:ping>http://www.ejball.com/EdAtWork/Trackback.aspx?guid=d2d50942-e8fb-430e-9e40-953e224abc1d</trackback:ping>
      <pingback:server>http://www.ejball.com/EdAtWork/pingback.aspx</pingback:server>
      <pingback:target>http://www.ejball.com/EdAtWork/PermaLink,guid,d2d50942-e8fb-430e-9e40-953e224abc1d.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.ejball.com/EdAtWork/CommentView,guid,d2d50942-e8fb-430e-9e40-953e224abc1d.aspx</wfw:comment>
      <wfw:commentRss>http://www.ejball.com/EdAtWork/SyndicationService.asmx/GetEntryCommentsRss?guid=d2d50942-e8fb-430e-9e40-953e224abc1d</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
      Normally you access function arguments by name.
   </p>
        <pre>function WriteAll(a, b)
{
  Write(a);
  Write(b);
}</pre>
        <p>
      However, you can also access function arguments by index using the special <code>arguments</code> object.
      This technique is particularly useful when implementing a function that takes an arbitrary
      number of arguments.
   </p>
        <pre>function WriteAll()
{
  for (var n = 0; n &lt; arguments.length; n++)
    Write(arguments[n]);
}</pre>
        <p>
      The <code>arguments</code> object has a <code>length</code> property and one integer
      property for each argument (starting with <code>0</code>, of course), but its similarity
      to <code>Array</code> ends there – it has none of the other methods of an <code>Array</code>.
      It is easy enough to convert an <code>arguments</code> object to an array; I use <code>SliceArguments</code>:
   </p>
        <pre>function SliceArguments(args, nStart, nEnd)
{
  if (nStart === undefined)
    nStart = 0;
  if (nEnd === undefined)
    nEnd = args.length;
  var aResult = [];
  while (nStart &lt; nEnd)
    aResult.push(args[nStart++]);
  return aResult;
}</pre>
        <p>
      The <code>arguments</code> object has another useful property; the <code>callee</code> property
      returns the <code>Function</code> object that is being executed. This is primarily
      useful for recursion in anonymous functions, since there’s no function name
      to use. (I’ll talk more about anonymous functions in a <a href="http://www.ejball.com/EdAtWork/PermaLink.aspx?guid=481764a7-5831-46f0-aabe-2b0f5c635995">future
      post</a>.)
   </p>
        <p>
      The <code>arguments</code> object has one more property: <code>caller</code>. It returns
      the <code>Function</code> object that called the currently executing function. However,
      the <code>caller</code> property has limited use, and has been deprecated in the most
      recent versions of JavaScript.
   </p>
        <p>
      One more item of interest – each <code>Function</code> object has a <code>length</code> property
      that indicates the number of named arguments of that function.
   </p>
        <pre>function Blorb(a, b, c) {}
// Blorb.length == 3</pre>
        <img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=d2d50942-e8fb-430e-9e40-953e224abc1d" />
      </body>
      <title>JavaScript: Function Arguments</title>
      <guid>http://www.ejball.com/EdAtWork/PermaLink,guid,d2d50942-e8fb-430e-9e40-953e224abc1d.aspx</guid>
      <link>http://www.ejball.com/EdAtWork/2005/03/18/JavaScriptFunctionArguments.aspx</link>
      <pubDate>Fri, 18 Mar 2005 20:58:31 GMT</pubDate>
      <description>&lt;p&gt;
   Normally you access function arguments by name.
&lt;/p&gt;
&lt;pre&gt;function WriteAll(a, b)
{
&amp;nbsp; Write(a);
&amp;nbsp; Write(b);
}&lt;/pre&gt;
&lt;p&gt;
   However, you can also access function arguments by index using the special &lt;code&gt;arguments&lt;/code&gt; object.
   This technique is particularly useful when implementing a function that takes an arbitrary
   number of arguments.
&lt;/p&gt;
&lt;pre&gt;function WriteAll()
{
&amp;nbsp; for (var n = 0; n &amp;lt; arguments.length; n++)
&amp;nbsp;&amp;nbsp;&amp;nbsp; Write(arguments[n]);
}&lt;/pre&gt;
&lt;p&gt;
   The &lt;code&gt;arguments&lt;/code&gt; object has a &lt;code&gt;length&lt;/code&gt; property and one integer
   property for each argument (starting with &lt;code&gt;0&lt;/code&gt;, of course), but its similarity
   to &lt;code&gt;Array&lt;/code&gt; ends there &amp;#8211; it has none of the other methods of an &lt;code&gt;Array&lt;/code&gt;.
   It is easy enough to convert an &lt;code&gt;arguments&lt;/code&gt; object to an array; I use &lt;code&gt;SliceArguments&lt;/code&gt;:
&lt;/p&gt;
&lt;pre&gt;function SliceArguments(args, nStart, nEnd)
{
&amp;nbsp; if (nStart === undefined)
&amp;nbsp;&amp;nbsp;&amp;nbsp; nStart = 0;
&amp;nbsp; if (nEnd === undefined)
&amp;nbsp;&amp;nbsp;&amp;nbsp; nEnd = args.length;
&amp;nbsp; var aResult = [];
&amp;nbsp; while (nStart &amp;lt; nEnd)
&amp;nbsp;&amp;nbsp;&amp;nbsp; aResult.push(args[nStart++]);
&amp;nbsp; return aResult;
}&lt;/pre&gt;
&lt;p&gt;
   The &lt;code&gt;arguments&lt;/code&gt; object has another useful property; the &lt;code&gt;callee&lt;/code&gt; property
   returns the &lt;code&gt;Function&lt;/code&gt; object that is being executed. This is primarily
   useful for recursion in anonymous functions, since there&amp;#8217;s no function name
   to use. (I&amp;#8217;ll talk more about anonymous functions in a &lt;a href="http://www.ejball.com/EdAtWork/PermaLink.aspx?guid=481764a7-5831-46f0-aabe-2b0f5c635995"&gt;future
   post&lt;/a&gt;.)
&lt;/p&gt;
&lt;p&gt;
   The &lt;code&gt;arguments&lt;/code&gt; object has one more property: &lt;code&gt;caller&lt;/code&gt;. It returns
   the &lt;code&gt;Function&lt;/code&gt; object that called the currently executing function. However,
   the &lt;code&gt;caller&lt;/code&gt; property has limited use, and has been deprecated in the most
   recent versions of JavaScript.
&lt;/p&gt;
&lt;p&gt;
   One more item of interest &amp;#8211; each &lt;code&gt;Function&lt;/code&gt; object has a &lt;code&gt;length&lt;/code&gt; property
   that indicates the number of named arguments of that function.
&lt;/p&gt;
&lt;pre&gt;function Blorb(a, b, c) {}
// Blorb.length == 3&lt;/pre&gt;
&lt;img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=d2d50942-e8fb-430e-9e40-953e224abc1d" /&gt;</description>
      <comments>http://www.ejball.com/EdAtWork/CommentView,guid,d2d50942-e8fb-430e-9e40-953e224abc1d.aspx</comments>
      <category>Code;JavaScript</category>
    </item>
    <item>
      <trackback:ping>http://www.ejball.com/EdAtWork/Trackback.aspx?guid=ff4814cd-3d23-46b8-bb11-cbbc7d20d900</trackback:ping>
      <pingback:server>http://www.ejball.com/EdAtWork/pingback.aspx</pingback:server>
      <pingback:target>http://www.ejball.com/EdAtWork/PermaLink,guid,ff4814cd-3d23-46b8-bb11-cbbc7d20d900.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.ejball.com/EdAtWork/CommentView,guid,ff4814cd-3d23-46b8-bb11-cbbc7d20d900.aspx</wfw:comment>
      <wfw:commentRss>http://www.ejball.com/EdAtWork/SyndicationService.asmx/GetEntryCommentsRss?guid=ff4814cd-3d23-46b8-bb11-cbbc7d20d900</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
      The nicest way to enumerate an array would be to use the <code>for...in</code> operator:
   </p>
        <pre>for (var obj in array)
  ...</pre>
        <p>
          <strong>Don’t do it.</strong> The biggest surprise to the uninitiated is that
      this <strong>enumerates the indexes</strong> into the array, not the elements of the
      array itself. You’ll also find that the enumerated <strong>indexes are
      strings</strong> rather than integers. Worst of all, you’ll find that the indexes
      aren’t enumerated in numerical order, but in <strong>arbitrary order</strong>.
      You’ve probably figured out by now that what you’re actually doing is
      enumerating the properties of the array object, which happen to include the <a href="http://www.ejball.com/EdAtWork/PermaLink.aspx?guid=b3cb19af-8375-4a46-82f2-6b2c94cce41d">properties
      whose names are non-negative integers</a>, but would also include any other custom
      properties you had assigned to the array.
   </p>
        <p>
      So, how to enumerate an array? Well, the best approach is the most obvious –
      walk through the indexes of the array with a simple <code>for</code> loop:
   </p>
        <pre>for (var n = 0; n &lt; array.length; n++)
  DoSomething(array[n]);</pre>
        <p>
      For a small speed increase, pull the length out of the loop.
   </p>
        <pre>var len = array.length;
for (var n = 0; n &lt; len; n++)
  DoSomething(array[n]);</pre>
        <p>
      However, my favorite way to enumerate an array is to call a <code>ForEach</code> function that
      does all this for me – more on that in a <a href="http://www.ejball.com/EdAtWork/PermaLink.aspx?guid=c2d0f53f-afc7-4831-b60e-f4354ae3f7fa">future
      post</a>...
   </p>
        <img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=ff4814cd-3d23-46b8-bb11-cbbc7d20d900" />
      </body>
      <title>JavaScript: Enumerating Arrays</title>
      <guid>http://www.ejball.com/EdAtWork/PermaLink,guid,ff4814cd-3d23-46b8-bb11-cbbc7d20d900.aspx</guid>
      <link>http://www.ejball.com/EdAtWork/2005/03/15/JavaScriptEnumeratingArrays.aspx</link>
      <pubDate>Tue, 15 Mar 2005 17:05:23 GMT</pubDate>
      <description>&lt;p&gt;
   The nicest way to enumerate an array would be to use the &lt;code&gt;for...in&lt;/code&gt; operator:
&lt;/p&gt;
&lt;pre&gt;for (var obj in array)
&amp;nbsp; ...&lt;/pre&gt;
&lt;p&gt;
   &lt;strong&gt;Don&amp;#8217;t do it.&lt;/strong&gt; The biggest surprise to the uninitiated is that
   this &lt;strong&gt;enumerates the indexes&lt;/strong&gt; into the array, not the elements of the
   array itself. You&amp;#8217;ll also find that the enumerated&amp;nbsp;&lt;strong&gt;indexes are
   strings&lt;/strong&gt; rather than integers. Worst of all, you&amp;#8217;ll find that the indexes
   aren&amp;#8217;t enumerated in numerical order, but in &lt;strong&gt;arbitrary order&lt;/strong&gt;.
   You&amp;#8217;ve probably figured out by now that what you&amp;#8217;re actually doing is
   enumerating the properties of the array object, which happen to include the &lt;a href="http://www.ejball.com/EdAtWork/PermaLink.aspx?guid=b3cb19af-8375-4a46-82f2-6b2c94cce41d"&gt;properties
   whose names are non-negative integers&lt;/a&gt;, but would also include any other custom
   properties you had assigned to the array.
&lt;/p&gt;
&lt;p&gt;
   So, how to enumerate an array? Well, the best approach is the most obvious &amp;#8211;
   walk through the indexes of the array with a simple &lt;code&gt;for&lt;/code&gt; loop:
&lt;/p&gt;
&lt;pre&gt;for (var n = 0; n &amp;lt; array.length; n++)
&amp;nbsp; DoSomething(array[n]);&lt;/pre&gt;
&lt;p&gt;
   For a small speed increase, pull the length out of the loop.
&lt;/p&gt;
&lt;pre&gt;var len = array.length;
for (var n = 0; n &amp;lt; len; n++)
&amp;nbsp; DoSomething(array[n]);&lt;/pre&gt;
&lt;p&gt;
   However, my favorite way to enumerate an array is to call a &lt;code&gt;ForEach&lt;/code&gt; function&amp;nbsp;that
   does all this for me&amp;nbsp;&amp;#8211; more on that in a &lt;a href="http://www.ejball.com/EdAtWork/PermaLink.aspx?guid=c2d0f53f-afc7-4831-b60e-f4354ae3f7fa"&gt;future
   post&lt;/a&gt;...
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=ff4814cd-3d23-46b8-bb11-cbbc7d20d900" /&gt;</description>
      <comments>http://www.ejball.com/EdAtWork/CommentView,guid,ff4814cd-3d23-46b8-bb11-cbbc7d20d900.aspx</comments>
      <category>Code;JavaScript</category>
    </item>
    <item>
      <trackback:ping>http://www.ejball.com/EdAtWork/Trackback.aspx?guid=b3cb19af-8375-4a46-82f2-6b2c94cce41d</trackback:ping>
      <pingback:server>http://www.ejball.com/EdAtWork/pingback.aspx</pingback:server>
      <pingback:target>http://www.ejball.com/EdAtWork/PermaLink,guid,b3cb19af-8375-4a46-82f2-6b2c94cce41d.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.ejball.com/EdAtWork/CommentView,guid,b3cb19af-8375-4a46-82f2-6b2c94cce41d.aspx</wfw:comment>
      <wfw:commentRss>http://www.ejball.com/EdAtWork/SyndicationService.asmx/GetEntryCommentsRss?guid=b3cb19af-8375-4a46-82f2-6b2c94cce41d</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
      Arrays in JavaScript are really just Objects with properties whose names happen to
      be non-negative integers. They also have one very special property: <code>length</code>.
   </p>
        <p>
      A new array has a length of zero.
   </p>
        <pre>var a = []; // a.length == 0</pre>
        <p>
      Whenever a property whose name happens to be a non-negative integer is set, the length
      is automatically set to one more than that integer (unless the length is already greater
      than that integer).
   </p>
        <pre>a[3] = true; // a.length == 4
a[9] = false; // a.length == 10
a[6] = false; // a.length == 10</pre>
        <p>
      JavaScript Arrays are “sparse” – no space is allocated for unused
      elements.
   </p>
        <pre>// a[2] === undefined, (2 in a) === false</pre>
        <p>
      Deleting an item in the array has no effect on the length.
   </p>
        <pre>delete a[9]; // a.length == 10</pre>
        <p>
      Explicitly enlarging the length of the array has no effect on the items in the array.
   </p>
        <pre>a.length = 12; // a[11] === undefined, (11 in a) === false</pre>
        <p>
      Explicitly reducing the length of the array automatically deletes any items in the
      array whose index is greater than or equal to the length.
   </p>
        <pre>a.length = 5; // a[6] === undefined, (6 in a) === false</pre>
        <p>
      You can use the length to add an item to an array (but prefer the <code>push</code> method).
   </p>
        <pre>a[a.length] = true; // a[5] === true, a.length == 6</pre>
        <p>
      Arrays support a number of useful methods that treat the object like a traditional
      array:
   </p>
        <ul>
          <li>
            <code>push, pop</code>: Adds or removes items from the end of the array. 
      </li>
          <li>
            <code>unshift, shift</code>: Adds or removes items from the beginning of the array. 
      </li>
          <li>
            <code>slice</code>: Returns a range of array items as a new array. 
      </li>
          <li>
            <code>splice</code>: Inserts and/or removes items to/from the array. 
      </li>
          <li>
            <code>concat</code>: Combines one or more arrays to form a new, concatenated array. 
      </li>
          <li>
            <code>join</code>: Joins the string forms of the array items into one string. 
      </li>
          <li>
            <code>sort</code>: Sorts the items in the array. 
      </li>
          <li>
            <code>reverse</code>: Reverses the items in the array.</li>
        </ul>
        <p>
      There’s no <code>clone</code> method, but you can clone an array by calling
      either <code>slice</code> or <code>concat</code> with no arguments.
   </p>
        <img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=b3cb19af-8375-4a46-82f2-6b2c94cce41d" />
      </body>
      <title>JavaScript: Array Basics</title>
      <guid>http://www.ejball.com/EdAtWork/PermaLink,guid,b3cb19af-8375-4a46-82f2-6b2c94cce41d.aspx</guid>
      <link>http://www.ejball.com/EdAtWork/2005/03/04/JavaScriptArrayBasics.aspx</link>
      <pubDate>Fri, 04 Mar 2005 23:08:09 GMT</pubDate>
      <description>&lt;p&gt;
   Arrays in JavaScript are really just Objects with properties whose names happen to
   be non-negative integers. They also have one very special property: &lt;code&gt;length&lt;/code&gt;.
&lt;/p&gt;
&lt;p&gt;
   A new array has a length of zero.
&lt;/p&gt;
&lt;pre&gt;var a = []; // a.length == 0&lt;/pre&gt;
&lt;p&gt;
   Whenever a property whose name happens to be a non-negative integer is set, the length
   is automatically set to one more than that integer (unless the length is already greater
   than that integer).
&lt;/p&gt;
&lt;pre&gt;a[3] = true; // a.length == 4
a[9] = false; // a.length == 10
a[6] = false; // a.length == 10&lt;/pre&gt;
&lt;p&gt;
   JavaScript Arrays are &amp;#8220;sparse&amp;#8221; &amp;#8211; no space is allocated for unused
   elements.
&lt;/p&gt;
&lt;pre&gt;// a[2] === undefined, (2 in a) === false&lt;/pre&gt;
&lt;p&gt;
   Deleting an item in the array has no effect on the length.
&lt;/p&gt;
&lt;pre&gt;delete a[9]; // a.length == 10&lt;/pre&gt;
&lt;p&gt;
   Explicitly enlarging the length of the array has no effect on the items in the array.
&lt;/p&gt;
&lt;pre&gt;a.length = 12; // a[11] === undefined, (11 in a) === false&lt;/pre&gt;
&lt;p&gt;
   Explicitly reducing the length of the array automatically deletes any items in the
   array whose index is greater than or equal to the length.
&lt;/p&gt;
&lt;pre&gt;a.length = 5; // a[6] === undefined, (6 in a) === false&lt;/pre&gt;
&lt;p&gt;
   You can use the length to add an item to an array (but prefer the &lt;code&gt;push&lt;/code&gt; method).
&lt;/p&gt;
&lt;pre&gt;a[a.length] = true; // a[5] === true, a.length == 6&lt;/pre&gt;
&lt;p&gt;
   Arrays support a number of useful methods that treat the object like a traditional
   array:
&lt;/p&gt;
&lt;ul&gt;
   &lt;li&gt;
      &lt;code&gt;push, pop&lt;/code&gt;: Adds or removes items from the end of the array. 
   &lt;li&gt;
      &lt;code&gt;unshift, shift&lt;/code&gt;: Adds or removes items from the beginning of the array. 
   &lt;li&gt;
      &lt;code&gt;slice&lt;/code&gt;: Returns a range of array items as a new array. 
   &lt;li&gt;
      &lt;code&gt;splice&lt;/code&gt;: Inserts and/or removes items to/from the array. 
   &lt;li&gt;
      &lt;code&gt;concat&lt;/code&gt;: Combines one or more arrays to form a new, concatenated array. 
   &lt;li&gt;
      &lt;code&gt;join&lt;/code&gt;: Joins the string forms of the array items into one string. 
   &lt;li&gt;
      &lt;code&gt;sort&lt;/code&gt;: Sorts the items in the array. 
   &lt;li&gt;
      &lt;code&gt;reverse&lt;/code&gt;: Reverses the items in the array.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
   There&amp;#8217;s no &lt;code&gt;clone&lt;/code&gt; method, but you can clone an array by calling
   either &lt;code&gt;slice&lt;/code&gt; or &lt;code&gt;concat&lt;/code&gt; with no arguments.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=b3cb19af-8375-4a46-82f2-6b2c94cce41d" /&gt;</description>
      <comments>http://www.ejball.com/EdAtWork/CommentView,guid,b3cb19af-8375-4a46-82f2-6b2c94cce41d.aspx</comments>
      <category>Code;JavaScript</category>
    </item>
    <item>
      <trackback:ping>http://www.ejball.com/EdAtWork/Trackback.aspx?guid=9ce84925-e8f0-4552-9baf-0e0961ac5cad</trackback:ping>
      <pingback:server>http://www.ejball.com/EdAtWork/pingback.aspx</pingback:server>
      <pingback:target>http://www.ejball.com/EdAtWork/PermaLink,guid,9ce84925-e8f0-4552-9baf-0e0961ac5cad.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.ejball.com/EdAtWork/CommentView,guid,9ce84925-e8f0-4552-9baf-0e0961ac5cad.aspx</wfw:comment>
      <wfw:commentRss>http://www.ejball.com/EdAtWork/SyndicationService.asmx/GetEntryCommentsRss?guid=9ce84925-e8f0-4552-9baf-0e0961ac5cad</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
      Since new object properties can be created at will, a plain old Object is quite useful
      in JavaScript.
   </p>
        <p>
      One common use of an Object is as a simple data structure. For example, if you want
      to return multiple values from a function, you can return an object with multiple
      properties:
   </p>
        <pre>function SplitAt(str, n)
{
  var obj = new Object;
  obj.Before = str.substring(0, n);
  obj.After = str.substring(n + 1);
  return obj;
}</pre>
        <p>
      Or, using the abbreviated syntax:
   </p>
        <pre>function SplitAt(str, n)
{
  return { Before : str.substring(0, n), After : str.substring(n + 1) };
}</pre>
        <p>
      Another common use of an Object is as an associative array; specifically, a mapping
      from strings to objects.
   </p>
        <pre>var map = {};
map["George Washington"] = 1789;
map["John Adams"] = 1797;</pre>
        <p>
      Or:
   </p>
        <pre>var map = { "George Washington" : 1789, "John Adams" : 1797 };</pre>
        <p>
      To see if a string is represented by an associative array, you could simply check
      that it isn’t undefined (e.g., <code>map["Ed Ball"] !== undefined</code>), but
      a property can be explicitly set to undefined, so you should use the <code>in</code> statement
      (e.g., <code>"Ed Ball" in map</code>).
   </p>
        <p>
      To remove a string from an associative array, use <code>delete</code> (e.g., <code>delete
      map["Ed Ball"]</code>).
   </p>
        <p>
      To see all of the strings represented by an associative array, use <code>for...in</code>:
   </p>
        <pre>for (var str in map)
  write(str + " (" + map[str] + ")");</pre>
        <p>
      When using an Object as an associative array, make sure that your strings will never
      be the same as the name of a built-in property of Object, e.g., "toString" or "prototype".
      Why? Well, for example, unless it has been overwritten, <code>map["toString"]</code> evaluates
      to a Function object instead of undefined. Furthermore, <code>"toString" in map</code> will
      always return true, but <code>for...in</code> will never enumerate "toString", and <code>delete
      map["toString"]</code> will always fail.
   </p>
        <p>
      Also keep in mind that future versions of JavaScript could add new built-in properties;
      for example, version 5.5 added "hasOwnProperty". When I want to make absolutely sure
      that I won’t have any conflicts with built-in properties, I prefix the string
      with a space character – no built-in property will ever start with a space,
      after all.
   </p>
        <pre>function Get(map, str) { return map[" " + str]; }
function Set(map, str, obj) { map[" " + str] = obj; }
function Has(map, str) { return (" " + str) in map; }
function Erase(map, str) { delete map[" " + str]; }
function Find(map, obj)
{
  for (var str in map)
    if (map[str] == obj)
      return str.substring(1); // remove space
}</pre>
        <img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=9ce84925-e8f0-4552-9baf-0e0961ac5cad" />
      </body>
      <title>JavaScript: Plain Old Objects</title>
      <guid>http://www.ejball.com/EdAtWork/PermaLink,guid,9ce84925-e8f0-4552-9baf-0e0961ac5cad.aspx</guid>
      <link>http://www.ejball.com/EdAtWork/2005/03/03/JavaScriptPlainOldObjects.aspx</link>
      <pubDate>Thu, 03 Mar 2005 21:23:58 GMT</pubDate>
      <description>&lt;p&gt;
   Since new object properties can be created at will, a plain old Object is quite useful
   in JavaScript.
&lt;/p&gt;
&lt;p&gt;
   One common use of an Object is as a simple data structure. For example, if you want
   to return multiple values from a function, you can return an object with multiple
   properties:
&lt;/p&gt;
&lt;pre&gt;function SplitAt(str, n)
{
&amp;nbsp; var obj = new Object;
&amp;nbsp; obj.Before = str.substring(0, n);
&amp;nbsp; obj.After = str.substring(n + 1);
&amp;nbsp; return obj;
}&lt;/pre&gt;
&lt;p&gt;
   Or, using the abbreviated syntax:
&lt;/p&gt;
&lt;pre&gt;function SplitAt(str, n)
{
&amp;nbsp; return { Before : str.substring(0, n), After : str.substring(n + 1) };
}&lt;/pre&gt;
&lt;p&gt;
   Another common use of an Object is as an associative array; specifically, a mapping
   from strings to objects.
&lt;/p&gt;
&lt;pre&gt;var map = {};
map["George Washington"] = 1789;
map["John Adams"] = 1797;&lt;/pre&gt;
&lt;p&gt;
   Or:
&lt;/p&gt;
&lt;pre&gt;var map = { "George Washington" : 1789, "John Adams" : 1797 };&lt;/pre&gt;
&lt;p&gt;
   To see if a string is represented by an associative array, you could simply check
   that it isn&amp;#8217;t undefined (e.g., &lt;code&gt;map["Ed Ball"] !== undefined&lt;/code&gt;), but
   a property can be explicitly set to undefined, so you should use the &lt;code&gt;in&lt;/code&gt; statement
   (e.g., &lt;code&gt;"Ed Ball" in map&lt;/code&gt;).
&lt;/p&gt;
&lt;p&gt;
   To remove a string from an associative array, use &lt;code&gt;delete&lt;/code&gt; (e.g., &lt;code&gt;delete
   map["Ed Ball"]&lt;/code&gt;).
&lt;/p&gt;
&lt;p&gt;
   To see all of the strings represented by an associative array, use &lt;code&gt;for...in&lt;/code&gt;:
&lt;/p&gt;
&lt;pre&gt;for (var str in map)
&amp;nbsp; write(str + " (" + map[str] + ")");&lt;/pre&gt;
&lt;p&gt;
   When using an Object as an associative array, make sure that your strings will never
   be the same as the name of a built-in property of Object, e.g., "toString" or "prototype".
   Why? Well, for example, unless it has been overwritten, &lt;code&gt;map["toString"]&lt;/code&gt; evaluates
   to a Function object instead of undefined. Furthermore, &lt;code&gt;"toString" in map&lt;/code&gt; will
   always return true, but &lt;code&gt;for...in&lt;/code&gt; will never enumerate "toString", and &lt;code&gt;delete
   map["toString"]&lt;/code&gt; will always fail.
&lt;/p&gt;
&lt;p&gt;
   Also keep in mind that future versions of JavaScript could add new built-in properties;
   for example, version 5.5 added "hasOwnProperty". When I want to make absolutely sure
   that I won&amp;#8217;t have any conflicts with built-in properties, I prefix the string
   with a space character&amp;nbsp;&amp;#8211; no built-in property will ever start with a space,
   after all.
&lt;/p&gt;
&lt;pre&gt;function Get(map, str) { return map[" " + str]; }
function Set(map, str, obj) { map[" " + str] = obj; }
function Has(map, str) { return (" " + str) in map; }
function Erase(map, str) { delete map[" " + str]; }
function Find(map, obj)
{
&amp;nbsp; for (var str in map)
&amp;nbsp;&amp;nbsp;&amp;nbsp; if (map[str] == obj)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return str.substring(1); // remove space
}&lt;/pre&gt;
&lt;img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=9ce84925-e8f0-4552-9baf-0e0961ac5cad" /&gt;</description>
      <comments>http://www.ejball.com/EdAtWork/CommentView,guid,9ce84925-e8f0-4552-9baf-0e0961ac5cad.aspx</comments>
      <category>Code;JavaScript</category>
    </item>
    <item>
      <trackback:ping>http://www.ejball.com/EdAtWork/Trackback.aspx?guid=46fbdf9b-9708-4c51-b760-43d12971e62f</trackback:ping>
      <pingback:server>http://www.ejball.com/EdAtWork/pingback.aspx</pingback:server>
      <pingback:target>http://www.ejball.com/EdAtWork/PermaLink,guid,46fbdf9b-9708-4c51-b760-43d12971e62f.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.ejball.com/EdAtWork/CommentView,guid,46fbdf9b-9708-4c51-b760-43d12971e62f.aspx</wfw:comment>
      <wfw:commentRss>http://www.ejball.com/EdAtWork/SyndicationService.asmx/GetEntryCommentsRss?guid=46fbdf9b-9708-4c51-b760-43d12971e62f</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://www.amazon.com/exec/obidos/tg/detail/-/0596000480">JavaScript: The
      Definitive Guide</a>, by David Flanagan, is an outstanding book about the JavaScript
      language. It has excellent documentation on both the “core” JavaScript
      language and “client-side” JavaScript as used by a web browser. Best of
      all, it doesn’t mix the two, which is particularly useful if you find yourself
      using JavaScript outside of a browser. It also gives the author a chance to dig deep
      into the core language, which is a far more powerful and expressive language than
      most people realize.
   </p>
        <p>
      The second half of the book consists of three references – one for “core”
      JavaScript, one for “client-side” JavaScript, and one for the W3C DOM.
      The references aren’t nearly as useful as the first half of the book, since
      that sort of documentation is more widely available, but it could come in handy.
   </p>
        <p>
      I have extensive experience using JavaScript both inside and outside of a browser,
      and have recently been studying the more “advanced” features. I was surprised
      by some of the details I had overlooked:
   </p>
        <ul>
          <li>
         The switch statement uses identity (<code>===</code>), not equality (<code>==</code>),
         when looking for a matching case statement.</li>
          <li>
         Each <code>case</code> of a switch statement can use any expression (not just numbers
         or strings).</li>
          <li>
         The first expression of a <code>for...in</code> statement is evaluated for each item.
         (I don’t plan on taking advantage of that obscure feature.)</li>
          <li>
         You can <code>break</code> or <code>continue</code> to a label.</li>
          <li>
            <code>FunctionName.length</code> is the declared number of function arguments.</li>
          <li>
         If a function used as a constructor returns an object, that object becomes the “new”
         object.</li>
          <li>
         The <code>push</code> method of an <code>Array</code> can take multiple arguments.</li>
          <li>
         In client-side JavaScript, “global” variables become properties of the
         global object, the window.</li>
          <li>
            <code>SCRIPT</code> elements should use <code>DEFER</code> if they don’t call <code>document.write</code>.</li>
          <li>
         The Internet Explorer event model has important differences from the standard event
         model.</li>
          <li>
         The standard <code>Error</code> object simply takes a string in its constructor (in
         Internet Explorer, the <code>Error</code> constructor is documented as taking a number
         followed by the message; I have since discovered that the standard behavior is supported
         as well).</li>
          <li>
         The <code>substr</code> method of <code>String</code> is deprecated in favor of <code>substring</code> or <code>slice</code>.
         (Unfortunately, I find <code>substr</code> far more natural than <code>substring</code> or <code>slice</code>.)</li>
          <li>
         There are a lot of methods that only work in Internet Explorer (and this book only
         scratched the surface).</li>
        </ul>
        <p>
      The book also talks some about “Object-Oriented JavaScript,” which I hope
      to talk more about in a future post.
   </p>
        <p>
      If you are a JavaScript programmer but realize that you may only be scratching the
      surface of what is possible, or wonder why the language doesn’t always behave
      as you’d expect it to, I highly recommend that you read this book.
   </p>
        <img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=46fbdf9b-9708-4c51-b760-43d12971e62f" />
      </body>
      <title>Book Review: JavaScript: The Definitive Guide</title>
      <guid>http://www.ejball.com/EdAtWork/PermaLink,guid,46fbdf9b-9708-4c51-b760-43d12971e62f.aspx</guid>
      <link>http://www.ejball.com/EdAtWork/2005/03/01/BookReviewJavaScriptTheDefinitiveGuide.aspx</link>
      <pubDate>Tue, 01 Mar 2005 21:36:27 GMT</pubDate>
      <description>&lt;p&gt;
   &lt;a href="http://www.amazon.com/exec/obidos/tg/detail/-/0596000480"&gt;JavaScript: The
   Definitive Guide&lt;/a&gt;, by David Flanagan, is an outstanding book about the JavaScript
   language. It has excellent documentation on both the &amp;#8220;core&amp;#8221; JavaScript
   language and &amp;#8220;client-side&amp;#8221; JavaScript as used by a web browser. Best of
   all, it doesn&amp;#8217;t mix the two, which is particularly useful if you find yourself
   using JavaScript outside of a browser. It also gives the author a chance to dig deep
   into the core language, which is a far more powerful and expressive language than
   most people realize.
&lt;/p&gt;
&lt;p&gt;
   The second half of the book consists of three references &amp;#8211; one for &amp;#8220;core&amp;#8221;
   JavaScript, one for &amp;#8220;client-side&amp;#8221; JavaScript, and one for the W3C DOM.
   The references aren&amp;#8217;t nearly as useful as the first half of the book, since
   that sort of documentation is more widely available, but it could come in handy.
&lt;/p&gt;
&lt;p&gt;
   I have extensive experience using JavaScript both inside and outside of a browser,
   and have recently been studying the more &amp;#8220;advanced&amp;#8221; features. I was surprised
   by some of the details I had overlooked:
&lt;/p&gt;
&lt;ul&gt;
   &lt;li&gt;
      The switch statement uses identity (&lt;code&gt;===&lt;/code&gt;), not equality (&lt;code&gt;==&lt;/code&gt;),
      when looking for a matching case statement.&lt;/li&gt;
   &lt;li&gt;
      Each &lt;code&gt;case&lt;/code&gt; of a switch statement can use any expression (not just numbers
      or strings).&lt;/li&gt;
   &lt;li&gt;
      The first expression of a &lt;code&gt;for...in&lt;/code&gt; statement is evaluated for each item.
      (I don&amp;#8217;t plan on taking advantage of that obscure feature.)&lt;/li&gt;
   &lt;li&gt;
      You can &lt;code&gt;break&lt;/code&gt; or &lt;code&gt;continue&lt;/code&gt; to a label.&lt;/li&gt;
   &lt;li&gt;
      &lt;code&gt;FunctionName.length&lt;/code&gt; is the declared number of function arguments.&lt;/li&gt;
   &lt;li&gt;
      If a function used as a constructor returns an object, that object becomes the &amp;#8220;new&amp;#8221;
      object.&lt;/li&gt;
   &lt;li&gt;
      The &lt;code&gt;push&lt;/code&gt; method of an &lt;code&gt;Array&lt;/code&gt; can take multiple arguments.&lt;/li&gt;
   &lt;li&gt;
      In client-side JavaScript, &amp;#8220;global&amp;#8221; variables become properties of the
      global object, the window.&lt;/li&gt;
   &lt;li&gt;
      &lt;code&gt;SCRIPT&lt;/code&gt; elements should use &lt;code&gt;DEFER&lt;/code&gt; if they don&amp;#8217;t call &lt;code&gt;document.write&lt;/code&gt;.&lt;/li&gt;
   &lt;li&gt;
      The Internet Explorer event model has important differences from the standard event
      model.&lt;/li&gt;
   &lt;li&gt;
      The standard &lt;code&gt;Error&lt;/code&gt; object simply takes a string in its constructor (in
      Internet Explorer, the &lt;code&gt;Error&lt;/code&gt; constructor is documented as taking a number
      followed by the message; I have since discovered that the standard behavior is supported
      as well).&lt;/li&gt;
   &lt;li&gt;
      The &lt;code&gt;substr&lt;/code&gt; method of &lt;code&gt;String&lt;/code&gt; is deprecated in favor of &lt;code&gt;substring&lt;/code&gt; or &lt;code&gt;slice&lt;/code&gt;.
      (Unfortunately, I find &lt;code&gt;substr&lt;/code&gt; far more natural than &lt;code&gt;substring&lt;/code&gt; or &lt;code&gt;slice&lt;/code&gt;.)&lt;/li&gt;
   &lt;li&gt;
      There are a lot of methods that only work in Internet Explorer (and this book only
      scratched the surface).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
   The book also talks some about &amp;#8220;Object-Oriented JavaScript,&amp;#8221; which I hope
   to talk more about in a future post.
&lt;/p&gt;
&lt;p&gt;
   If you are a JavaScript programmer but realize that you may only be scratching the
   surface of what is possible, or wonder why the language doesn&amp;#8217;t always behave
   as you&amp;#8217;d expect it to, I highly recommend that you read this book.
&lt;/p&gt;
&gt;&lt;img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=46fbdf9b-9708-4c51-b760-43d12971e62f" /&gt;</description>
      <comments>http://www.ejball.com/EdAtWork/CommentView,guid,46fbdf9b-9708-4c51-b760-43d12971e62f.aspx</comments>
      <category>Books;JavaScript</category>
    </item>
    <item>
      <trackback:ping>http://www.ejball.com/EdAtWork/Trackback.aspx?guid=d5c66b20-dd92-4b4a-9d67-c3fbeafd0e31</trackback:ping>
      <pingback:server>http://www.ejball.com/EdAtWork/pingback.aspx</pingback:server>
      <pingback:target>http://www.ejball.com/EdAtWork/PermaLink,guid,d5c66b20-dd92-4b4a-9d67-c3fbeafd0e31.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.ejball.com/EdAtWork/CommentView,guid,d5c66b20-dd92-4b4a-9d67-c3fbeafd0e31.aspx</wfw:comment>
      <wfw:commentRss>http://www.ejball.com/EdAtWork/SyndicationService.asmx/GetEntryCommentsRss?guid=d5c66b20-dd92-4b4a-9d67-c3fbeafd0e31</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
      In JavaScript, the “Boolean” operators <code>&amp;&amp;</code> and <code>||</code> aren’t
      very Boolean at all. In most C-style languages, <code>a || b</code> returns a Boolean
      – true if either <em>a</em> or <em>b</em> are “true,” and false
      otherwise. (<a href="http://www.ejball.com/EdAtWork/PermaLink.aspx?guid=1a946f91-d37d-4104-a1d3-63e633afafba">Remember</a> that
      lots of things are “true” in JavaScript – in fact, the only things
      that are “false” are the false Boolean, the numbers 0 and NaN, the empty
      string, null, and undefined.)
   </p>
        <p>
      Actually, that’s a somewhat simplified view, because the <code>&amp;&amp;</code> and <code>||</code> operators
      of C-style languages short-circuit, meaning that <em>b</em> is not evaluated if <em>a</em> is
      “false.” Thus it is safe to have an expression like <code>a == null ||
      a.isEmpty()</code> – the isEmpty method will not be called if <em>a</em> is
      null.
   </p>
        <p>
      Where was I? Ah, yes, in most C-style languages, <code>a || b</code> returns a Boolean,
      so it’s the same as
   </p>
        <pre>a ? true : (b ? true : false)</pre>
        <p>
      But in JavaScript, a || b doesn’t necessarily return a Boolean, because it is
      really the same as
   </p>
        <pre>a ? a : b</pre>
        <p>
      How does this work? Well, if <em>a</em> is “true,” then <code>a || b</code> returns <em>a</em>,
      which is “true.” If <em>a</em> is “false” but <em>b</em> is
      “true,” then <code>a || b</code> returns <em>b</em>, which is “true.”
      If both <em>a</em> and <em>b</em> are “false”, then <code>a || b</code> returns <em>b</em>,
      which is “false.”
   </p>
        <p>
      The danger is in assuming that <code>a || b</code> returns a Boolean when <em>a</em> and <em>b</em> are
      not Booleans themselves. For example:
   </p>
        <pre>var hasItems = a &amp;&amp; a.getCount();
if (hasItems == true) // should be: if (hasItems)
  ...</pre>
        <p>
      Now, you shouldn’t be comparing Booleans to true or false anyway, but if you
      did, you’d find that <em>hasItems</em> equals true only when <em>a.getCount()</em> returns
      1 (and then only because 1 equals true in JavaScript). Furthermore, <em>hasItems</em> equals
      false only when <em>a.getCount()</em> returns 0 (because 0 equals false). If <em>a</em> is
      null, <em>hasItems</em> will be null, which equals neither true nor false. If <em>a.getCount()</em> returns
      2, <em>hasItems</em> equals 2, which, again, equals neither true nor false.
   </p>
        <p>
      Be aware that the <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/js56jsoprand.asp">MSDN
      documentation</a> is stunningly inaccurate here; it suggests that &amp;&amp; and ||
      always return true or false. (The <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/jscript7/html/jsoprand.asp">JScript.NET
      documentation</a> is more accurate, thankfully.)
   </p>
        <p>
      Why does JavaScript evaluates the binary Boolean operators this way? Well, a || b
      provides a great shortcut for a ? a : b that only evaluates a once. Similarly, a &amp;&amp;
      b provides a nice shortcut for a ? b : a. For example, instead of
   </p>
        <pre>var pane = null;
if (view != null)
  pane = view.getPane();</pre>
        <p>
        </p>
        <p>
      or
   </p>
        <pre>var pane = view == null ? null : view.getPane();</pre>
        <p>
      you can use
   </p>
        <pre>var pane = view &amp;&amp; view.getPane();</pre>
        <p>
      You could argue that it’s not as clear, of course, particularly to anyone that
      doesn’t know about this feature of JavaScript, so take advantage of it at your
      own discretion.
   </p>
        <p>
      I should also mention the unary Boolean operator of JavaScript. The “not”
      operator (!) is quite Boolean, because it always returns true or false. That is, !a
      evaluates to true if a is false, 0, NaN, "", null, or undefined; otherwise, !a evaluates
      to false. To explicitly convert a value to a Boolean, you could use a ? true : false,
      or you can simply use a double-not: !!a.
   </p>
        <img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=d5c66b20-dd92-4b4a-9d67-c3fbeafd0e31" />
      </body>
      <title>JavaScript: “Boolean” operators</title>
      <guid>http://www.ejball.com/EdAtWork/PermaLink,guid,d5c66b20-dd92-4b4a-9d67-c3fbeafd0e31.aspx</guid>
      <link>http://www.ejball.com/EdAtWork/2005/02/19/JavaScriptBooleanOperators.aspx</link>
      <pubDate>Sat, 19 Feb 2005 00:45:39 GMT</pubDate>
      <description>&lt;p&gt;
   In JavaScript, the &amp;#8220;Boolean&amp;#8221; operators &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt; and &lt;code&gt;||&lt;/code&gt; aren&amp;#8217;t
   very Boolean at all. In most C-style languages, &lt;code&gt;a || b&lt;/code&gt; returns a Boolean
   &amp;#8211; true if either &lt;em&gt;a&lt;/em&gt; or &lt;em&gt;b&lt;/em&gt; are &amp;#8220;true,&amp;#8221; and false
   otherwise. (&lt;a href="http://www.ejball.com/EdAtWork/PermaLink.aspx?guid=1a946f91-d37d-4104-a1d3-63e633afafba"&gt;Remember&lt;/a&gt; that
   lots of things are &amp;#8220;true&amp;#8221; in JavaScript &amp;#8211; in fact, the only things
   that are &amp;#8220;false&amp;#8221; are the false Boolean, the numbers 0 and NaN, the empty
   string, null, and undefined.)
&lt;/p&gt;
&lt;p&gt;
   Actually, that&amp;#8217;s a somewhat simplified&amp;nbsp;view, because the &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt; and &lt;code&gt;||&lt;/code&gt; operators
   of C-style languages short-circuit, meaning that &lt;em&gt;b&lt;/em&gt; is not evaluated if &lt;em&gt;a&lt;/em&gt; is
   &amp;#8220;false.&amp;#8221; Thus it is safe to have an expression like &lt;code&gt;a == null ||
   a.isEmpty()&lt;/code&gt; &amp;#8211; the isEmpty method will not be called if &lt;em&gt;a&lt;/em&gt; is
   null.
&lt;/p&gt;
&lt;p&gt;
   Where was I? Ah, yes, in most C-style languages, &lt;code&gt;a || b&lt;/code&gt; returns a Boolean,
   so it&amp;#8217;s the same as
&lt;/p&gt;
&lt;pre&gt;a ? true : (b ? true : false)&lt;/pre&gt;
&lt;p&gt;
   But in JavaScript, a || b doesn&amp;#8217;t necessarily return a Boolean, because it is
   really the same as
&lt;/p&gt;
&lt;pre&gt;a ? a : b&lt;/pre&gt;
&lt;p&gt;
   How does this work? Well, if &lt;em&gt;a&lt;/em&gt; is &amp;#8220;true,&amp;#8221; then &lt;code&gt;a || b&lt;/code&gt; returns &lt;em&gt;a&lt;/em&gt;,
   which is &amp;#8220;true.&amp;#8221; If &lt;em&gt;a&lt;/em&gt; is &amp;#8220;false&amp;#8221; but &lt;em&gt;b&lt;/em&gt; is
   &amp;#8220;true,&amp;#8221; then &lt;code&gt;a || b&lt;/code&gt; returns &lt;em&gt;b&lt;/em&gt;, which is &amp;#8220;true.&amp;#8221;
   If both &lt;em&gt;a&lt;/em&gt; and &lt;em&gt;b&lt;/em&gt; are &amp;#8220;false&amp;#8221;, then &lt;code&gt;a || b&lt;/code&gt; returns &lt;em&gt;b&lt;/em&gt;,
   which is &amp;#8220;false.&amp;#8221;
&lt;/p&gt;
&lt;p&gt;
   The danger is in assuming that &lt;code&gt;a || b&lt;/code&gt; returns a Boolean when &lt;em&gt;a&lt;/em&gt; and &lt;em&gt;b&lt;/em&gt; are
   not Booleans themselves. For example:
&lt;/p&gt;
&lt;pre&gt;var hasItems = a &amp;amp;&amp;amp; a.getCount();
if (hasItems == true) // should be: if (hasItems)
&amp;nbsp; ...&lt;/pre&gt;
&lt;p&gt;
   Now, you shouldn&amp;#8217;t be comparing Booleans to true or false anyway, but if you
   did, you&amp;#8217;d find that &lt;em&gt;hasItems&lt;/em&gt; equals true only when &lt;em&gt;a.getCount()&lt;/em&gt; returns
   1 (and then only because 1 equals true in JavaScript). Furthermore, &lt;em&gt;hasItems&lt;/em&gt; equals
   false only when &lt;em&gt;a.getCount()&lt;/em&gt; returns 0 (because 0 equals false). If &lt;em&gt;a&lt;/em&gt; is
   null, &lt;em&gt;hasItems&lt;/em&gt; will be null, which equals neither true nor false. If &lt;em&gt;a.getCount()&lt;/em&gt; returns
   2, &lt;em&gt;hasItems&lt;/em&gt; equals 2, which, again, equals neither true nor false.
&lt;/p&gt;
&lt;p&gt;
   Be aware that the &lt;a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/js56jsoprand.asp"&gt;MSDN
   documentation&lt;/a&gt; is stunningly inaccurate here; it suggests that &amp;amp;&amp;amp; and ||
   always return true or false. (The &lt;a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/jscript7/html/jsoprand.asp"&gt;JScript.NET
   documentation&lt;/a&gt; is more accurate, thankfully.)
&lt;/p&gt;
&lt;p&gt;
   Why does JavaScript evaluates the binary Boolean operators this way? Well, a || b
   provides a great shortcut for a ? a : b that only evaluates a once. Similarly, a &amp;amp;&amp;amp;
   b provides a nice shortcut for a ? b : a. For example, instead of
&lt;/p&gt;
&lt;pre&gt;var pane = null;
if (view != null)
&amp;nbsp; pane = view.getPane();&lt;/pre&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
   or
&lt;/p&gt;
&lt;pre&gt;var pane = view == null ? null : view.getPane();&lt;/pre&gt;
&lt;p&gt;
   you can use
&lt;/p&gt;
&lt;pre&gt;var pane = view &amp;amp;&amp;amp; view.getPane();&lt;/pre&gt;
&lt;p&gt;
   You could argue that it&amp;#8217;s not as clear, of course, particularly to anyone that
   doesn&amp;#8217;t know about this feature of JavaScript, so take advantage of it at your
   own discretion.
&lt;/p&gt;
&lt;p&gt;
   I should also mention the unary Boolean operator of JavaScript. The &amp;#8220;not&amp;#8221;
   operator (!) is quite Boolean, because it always returns true or false. That is, !a
   evaluates to true if a is false, 0, NaN, "", null, or undefined; otherwise, !a evaluates
   to false. To explicitly convert a value to a Boolean, you could use a ? true : false,
   or you can simply use a double-not: !!a.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=d5c66b20-dd92-4b4a-9d67-c3fbeafd0e31" /&gt;</description>
      <comments>http://www.ejball.com/EdAtWork/CommentView,guid,d5c66b20-dd92-4b4a-9d67-c3fbeafd0e31.aspx</comments>
      <category>Code;JavaScript</category>
    </item>
    <item>
      <trackback:ping>http://www.ejball.com/EdAtWork/Trackback.aspx?guid=ed4e2113-b80b-4cc0-91cf-ca5fad876a67</trackback:ping>
      <pingback:server>http://www.ejball.com/EdAtWork/pingback.aspx</pingback:server>
      <pingback:target>http://www.ejball.com/EdAtWork/PermaLink,guid,ed4e2113-b80b-4cc0-91cf-ca5fad876a67.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.ejball.com/EdAtWork/CommentView,guid,ed4e2113-b80b-4cc0-91cf-ca5fad876a67.aspx</wfw:comment>
      <wfw:commentRss>http://www.ejball.com/EdAtWork/SyndicationService.asmx/GetEntryCommentsRss?guid=ed4e2113-b80b-4cc0-91cf-ca5fad876a67</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
      The <code>this</code> statement in JavaScript is important, particularly when
      writing “object oriented” code. What <code>this</code> is depends on when
      you ask.
   </p>
        <p>
      Outside of a function call, <code>this</code> is the global object. If your code is
      being hosted by a browser, <code>this</code> is the window object. Other script hosts
      provide their own global object.
   </p>
        <p>
      Inside of a function call, what <code>this</code> is depends on how the function was
      called. A function can be called in one of four ways:
   </p>
        <ul>
          <li>
            <code>F(arg1, arg2)</code>
          </li>
          <li>
            <code>obj.F(arg1, arg2)</code>
          </li>
          <li>
            <code>F.call(obj, arg1, arg2)</code>
          </li>
          <li>
            <code>F.apply(obj, args)</code>
          </li>
        </ul>
        <p>
      In the first case, any reference to <code>this</code> in the function definition will
      evaluate to the global object. In the second case, references to <code>this</code> evaluate
      to the specified object (<code>obj</code>), which is why <code>this</code> is so important
      to “object oriented” JavaScript code. In the third and fourth cases, references
      to <code>this</code> also evaluate to the object, unless <code>obj</code> is set to <code>undefined</code>,
      in which case <code>this</code> will evaluate to the global object, as with the first
      case.
   </p>
        <p>
      It’s interesting to consider the relative speed of each of the four ways to
      call a function. Unsurprisingly, the last is generally the slowest. Quite surprisingly,
      to me at least, under Internet Explorer, the second case is faster than the third.
      That’s right – calling a function property of a global object is faster
      than calling a global function. Only the <a href="http://weblogs.asp.net/ericlippert">Great
      Implementor</a> would know for sure, but it looks like the extra time in the first
      case is spent determining what <code>this</code> should be. In fact, the third case
      is also faster than the first case when the first argument to <code>call</code> is
      anything but <code>undefined</code>. (Thus, when performance is an issue, and I’ve
      got a function variable, I call it with the <code>call</code> method and specify an
      explicit <code>this</code>.)
   </p>
        <p>
          <strong>Update:</strong> I forgot to mention another useful use of <code>this</code>.
      When an HTML element raises an event, the event handler function can use <code>this</code> to
      access the element to which the event handler was attached. <code>window.event.srcElement</code> provides
      access to the element that raised the event. There's no difference between the two
      unless the event has bubbled to the element. For example, if you handle <code>onclick</code> in <code>document.body</code>, <code>window.event.srcElement</code> will
      be the actual descendant element that was clicked, but <code>this</code> will always
      be <code>document.body</code>.
   </p>
        <img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=ed4e2113-b80b-4cc0-91cf-ca5fad876a67" />
      </body>
      <title>JavaScript: What’s this?</title>
      <guid>http://www.ejball.com/EdAtWork/PermaLink,guid,ed4e2113-b80b-4cc0-91cf-ca5fad876a67.aspx</guid>
      <link>http://www.ejball.com/EdAtWork/2005/02/16/JavaScriptWhatsThis.aspx</link>
      <pubDate>Wed, 16 Feb 2005 17:23:08 GMT</pubDate>
      <description>&lt;p&gt;
   The &lt;code&gt;this&lt;/code&gt; statement in JavaScript is important, particularly&amp;nbsp;when
   writing &amp;#8220;object oriented&amp;#8221; code. What &lt;code&gt;this&lt;/code&gt; is depends on when
   you ask.
&lt;/p&gt;
&lt;p&gt;
   Outside of a function call, &lt;code&gt;this&lt;/code&gt; is the global object. If your code is
   being hosted by a browser, &lt;code&gt;this&lt;/code&gt; is the window object. Other script hosts
   provide their own global object.
&lt;/p&gt;
&lt;p&gt;
   Inside of a function call, what &lt;code&gt;this&lt;/code&gt; is depends on how the function was
   called. A function can be called in one of four ways:
&lt;/p&gt;
&lt;ul&gt;
   &lt;li&gt;
      &lt;code&gt;F(arg1, arg2)&lt;/code&gt; 
   &lt;li&gt;
      &lt;code&gt;obj.F(arg1, arg2)&lt;/code&gt; 
   &lt;li&gt;
      &lt;code&gt;F.call(obj, arg1, arg2)&lt;/code&gt; 
   &lt;li&gt;
      &lt;code&gt;F.apply(obj, args)&lt;/code&gt;
   &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
   In the first case, any reference to &lt;code&gt;this&lt;/code&gt; in the function definition will
   evaluate to the global object. In the second case, references to &lt;code&gt;this&lt;/code&gt; evaluate
   to the specified object (&lt;code&gt;obj&lt;/code&gt;), which is why &lt;code&gt;this&lt;/code&gt; is so important
   to &amp;#8220;object oriented&amp;#8221; JavaScript code. In the third and fourth cases, references
   to &lt;code&gt;this&lt;/code&gt; also evaluate to the object, unless &lt;code&gt;obj&lt;/code&gt; is set to &lt;code&gt;undefined&lt;/code&gt;,
   in which case &lt;code&gt;this&lt;/code&gt; will evaluate to the global object, as with the first
   case.
&lt;/p&gt;
&lt;p&gt;
   It&amp;#8217;s interesting to consider the relative speed of each of the four ways to
   call a function. Unsurprisingly, the last is generally the slowest. Quite surprisingly,
   to me at least, under Internet Explorer, the second case is faster than the third.
   That&amp;#8217;s right &amp;#8211; calling a function property of a global object is faster
   than calling a global function. Only the &lt;a href="http://weblogs.asp.net/ericlippert"&gt;Great
   Implementor&lt;/a&gt; would know for sure, but it looks like the extra time in the first
   case is spent determining what &lt;code&gt;this&lt;/code&gt; should be. In fact, the third case
   is also faster than the first case when the first argument to &lt;code&gt;call&lt;/code&gt; is
   anything but &lt;code&gt;undefined&lt;/code&gt;. (Thus, when performance is an issue, and I&amp;#8217;ve
   got a function variable, I call it with the &lt;code&gt;call&lt;/code&gt; method and specify an
   explicit &lt;code&gt;this&lt;/code&gt;.)
&lt;/p&gt;
&lt;p&gt;
   &lt;strong&gt;Update:&lt;/strong&gt; I forgot to mention another useful use of &lt;code&gt;this&lt;/code&gt;.
   When an HTML element raises an event, the event handler function can use &lt;code&gt;this&lt;/code&gt; to
   access the element to which the event handler was attached. &lt;code&gt;window.event.srcElement&lt;/code&gt; provides
   access to the element that raised the event. There's no difference between the two
   unless the event has bubbled to the element. For example, if you handle &lt;code&gt;onclick&lt;/code&gt; in &lt;code&gt;document.body&lt;/code&gt;, &lt;code&gt;window.event.srcElement&lt;/code&gt; will
   be the actual descendant element that was clicked, but &lt;code&gt;this&lt;/code&gt; will always
   be &lt;code&gt;document.body&lt;/code&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=ed4e2113-b80b-4cc0-91cf-ca5fad876a67" /&gt;</description>
      <comments>http://www.ejball.com/EdAtWork/CommentView,guid,ed4e2113-b80b-4cc0-91cf-ca5fad876a67.aspx</comments>
      <category>Code;JavaScript</category>
    </item>
    <item>
      <trackback:ping>http://www.ejball.com/EdAtWork/Trackback.aspx?guid=1a946f91-d37d-4104-a1d3-63e633afafba</trackback:ping>
      <pingback:server>http://www.ejball.com/EdAtWork/pingback.aspx</pingback:server>
      <pingback:target>http://www.ejball.com/EdAtWork/PermaLink,guid,1a946f91-d37d-4104-a1d3-63e633afafba.aspx</pingback:target>
      <dc:creator>
      </dc:creator>
      <wfw:comment>http://www.ejball.com/EdAtWork/CommentView,guid,1a946f91-d37d-4104-a1d3-63e633afafba.aspx</wfw:comment>
      <wfw:commentRss>http://www.ejball.com/EdAtWork/SyndicationService.asmx/GetEntryCommentsRss?guid=1a946f91-d37d-4104-a1d3-63e633afafba</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
      What is true in JavaScript? It depends on how you ask.
   </p>
        <p>
          <code>X === true</code> is true only if and only if X is a Boolean variable set to
      true.
   </p>
        <p>
      (What, you’ve never heard of the “triple-equals” operator? It’s
      actually called the “identity” operator, and <code>X === Y</code> when <code>typeof(X)
      == typeof(Y) &amp;&amp; X == Y</code>. There’s also <code>X !== Y</code>, which
      is the same as <code>!(X === Y)</code>. You’re probably familiar with the <code>typeof</code> operator
      – it returns “number”, “string”, “boolean”,
      “object”, “function”, or “undefined”. Notice that
      there’s no “integer” or “real”, so it is unsurprising
      (but dangerous, given the unpredictability of floating-point math) that <code>1 +
      1 === 0.5 + 1.5</code>. Anyway, back to what is true…)
   </p>
        <p>
          <code>X ? true : false</code> is true most of the time. It’s only false when
      X is the number 0, or the number NaN, or the empty string, or the false Boolean, or
      the null object, or undefined. (This is the same logic used by the <code>if</code> and <code>while</code> statements.)
   </p>
        <p>
      Now, equality gets really confusing. <code>X == true</code> whenever X can be directly
      converted to the Boolean true. The following meet that criteria: the true Boolean,
      the number 1, and strings that convert to the number 1, such as “1”, “1.0”,
      “1E0”, “0.1E1”, “ +1.0 ”, etc. Note that leading
      and trailing whitespace is ignored! Surprisingly, strings like “true”
      or “True” do not meet the criteria – so <code>"1" == true</code>,
      but <code>"true" != true</code>.
   </p>
        <p>
      In the case of equality, we must also talk about what is false. <code>X == false</code> whenever
      X can be directly converted to the Boolean false: the false Boolean, the number 0,
      and strings that convert to the number 0, such as “0”, “0.0”,
      “ -0E1”, etc. But wait; there’s more! The empty string (“”)
      is also “equal to” false, as well as any string that contains only whitespace!
      So <code>" \n\t\r\u2002" == false</code>! Who knew? However, a few things that you’d
      think might be “equal to” false aren’t: <code>"false" != false</code>, <code>NaN
      != false</code>, <code>null != false</code>, and <code>undefined != false</code>.
   </p>
        <p>
      What's particularly confusing is considering which of the following similar statements
      are true for any given X:
   </p>
        <ul>
          <li>
            <code>X == true</code>
          </li>
          <li>
            <code>X != false</code>
          </li>
          <li>
            <code>X ? true : false</code>
          </li>
        </ul>
        <p>
      If X is "1", they are all true. If X is "", none are true. But if X is null, only
      the second is true. If X is " ", only the last is true. And if X is "2", the last
      two are true. The funny thing is that it really does work as you’d expect, most
      of the time. The subtleties of JavaScript…
   </p>
        <p>
          <strong>Disclaimer:</strong> My experience is actually with Microsoft’s JScript,
      particularly as it is implemented inside Internet Explorer. I presume that this is
      all true for all JavaScript engines, but I haven’t actually tested it.
   </p>
        <p>
          <strong>Update:</strong> I replaced the second to last paragraph with something that
      is hopefully more interesting and more accurate. (Thanks, Bradley!)
   </p>
        <img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=1a946f91-d37d-4104-a1d3-63e633afafba" />
      </body>
      <title>JavaScript: What is true?</title>
      <guid>http://www.ejball.com/EdAtWork/PermaLink,guid,1a946f91-d37d-4104-a1d3-63e633afafba.aspx</guid>
      <link>http://www.ejball.com/EdAtWork/2005/02/15/JavaScriptWhatIsTrue.aspx</link>
      <pubDate>Tue, 15 Feb 2005 17:16:02 GMT</pubDate>
      <description>&lt;p&gt;
   What is true in JavaScript? It depends on how you ask.
&lt;/p&gt;
&lt;p&gt;
   &lt;code&gt;X === true&lt;/code&gt; is true only if and only if X is a Boolean variable set to
   true.
&lt;/p&gt;
&lt;p&gt;
   (What, you&amp;#8217;ve never heard of the &amp;#8220;triple-equals&amp;#8221; operator? It&amp;#8217;s
   actually called the &amp;#8220;identity&amp;#8221; operator, and &lt;code&gt;X === Y&lt;/code&gt; when &lt;code&gt;typeof(X)
   == typeof(Y) &amp;amp;&amp;amp; X == Y&lt;/code&gt;. There&amp;#8217;s also &lt;code&gt;X !== Y&lt;/code&gt;, which
   is the same as &lt;code&gt;!(X === Y)&lt;/code&gt;. You&amp;#8217;re probably familiar with the &lt;code&gt;typeof&lt;/code&gt; operator
   &amp;#8211; it returns &amp;#8220;number&amp;#8221;, &amp;#8220;string&amp;#8221;, &amp;#8220;boolean&amp;#8221;,
   &amp;#8220;object&amp;#8221;, &amp;#8220;function&amp;#8221;, or &amp;#8220;undefined&amp;#8221;. Notice that
   there&amp;#8217;s no &amp;#8220;integer&amp;#8221; or &amp;#8220;real&amp;#8221;, so it is unsurprising
   (but dangerous, given the unpredictability of floating-point math) that &lt;code&gt;1 +
   1 === 0.5 + 1.5&lt;/code&gt;. Anyway, back to what is true&amp;#8230;)
&lt;/p&gt;
&lt;p&gt;
   &lt;code&gt;X ? true : false&lt;/code&gt; is true most of the time. It&amp;#8217;s only false when
   X is the number 0, or the number NaN, or the empty string, or the false Boolean, or
   the null object, or undefined. (This is the same logic used by the &lt;code&gt;if&lt;/code&gt; and &lt;code&gt;while&lt;/code&gt; statements.)
&lt;/p&gt;
&lt;p&gt;
   Now, equality gets really confusing. &lt;code&gt;X == true&lt;/code&gt; whenever X can be directly
   converted to the Boolean true. The following meet that criteria: the true Boolean,
   the number 1, and strings that convert to the number 1, such as &amp;#8220;1&amp;#8221;, &amp;#8220;1.0&amp;#8221;,
   &amp;#8220;1E0&amp;#8221;, &amp;#8220;0.1E1&amp;#8221;, &amp;#8220; +1.0 &amp;#8221;, etc. Note that leading
   and trailing whitespace is ignored! Surprisingly, strings like &amp;#8220;true&amp;#8221;
   or &amp;#8220;True&amp;#8221; do not meet the criteria &amp;#8211; so &lt;code&gt;"1" == true&lt;/code&gt;,
   but &lt;code&gt;"true" != true&lt;/code&gt;.
&lt;/p&gt;
&lt;p&gt;
   In the case of equality, we must also talk about what is false. &lt;code&gt;X == false&lt;/code&gt; whenever
   X can be directly converted to the Boolean false: the false Boolean, the number 0,
   and strings that convert to the number 0, such as &amp;#8220;0&amp;#8221;, &amp;#8220;0.0&amp;#8221;,
   &amp;#8220; -0E1&amp;#8221;, etc. But wait; there&amp;#8217;s more! The empty string (&amp;#8220;&amp;#8221;)
   is also &amp;#8220;equal to&amp;#8221; false, as well as any string that contains only whitespace!
   So &lt;code&gt;" \n\t\r\u2002" == false&lt;/code&gt;! Who knew? However, a few things that you&amp;#8217;d
   think might be &amp;#8220;equal to&amp;#8221; false aren&amp;#8217;t: &lt;code&gt;"false" != false&lt;/code&gt;, &lt;code&gt;NaN
   != false&lt;/code&gt;, &lt;code&gt;null != false&lt;/code&gt;, and &lt;code&gt;undefined != false&lt;/code&gt;.
&lt;/p&gt;
&lt;p&gt;
   What's particularly confusing is considering which of the following similar statements
   are true for any given X:
&lt;/p&gt;
&lt;ul&gt;
   &lt;li&gt;
      &lt;code&gt;X == true&lt;/code&gt;
   &lt;/li&gt;
   &lt;li&gt;
      &lt;code&gt;X&amp;nbsp;!= false&lt;/code&gt;
   &lt;/li&gt;
   &lt;li&gt;
      &lt;code&gt;X ? true : false&lt;/code&gt;
   &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
   If X is "1", they are all true. If X is "", none are true. But if X is null, only
   the second is true. If X is " ", only the last is true. And if X is "2", the last
   two are true. The funny thing is that it really does work as you&amp;#8217;d expect, most
   of the time. The subtleties of JavaScript&amp;#8230;
&lt;/p&gt;
&lt;p&gt;
   &lt;strong&gt;Disclaimer:&lt;/strong&gt; My experience is actually with Microsoft&amp;#8217;s JScript,
   particularly as it is implemented inside Internet Explorer. I presume that this is
   all true for all JavaScript engines, but I haven&amp;#8217;t actually tested it.
&lt;/p&gt;
&lt;p&gt;
   &lt;strong&gt;Update:&lt;/strong&gt; I replaced the second to last paragraph with something that
   is hopefully more interesting and more accurate. (Thanks, Bradley!)
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.ejball.com/EdAtWork/aggbug.ashx?id=1a946f91-d37d-4104-a1d3-63e633afafba" /&gt;</description>
      <comments>http://www.ejball.com/EdAtWork/CommentView,guid,1a946f91-d37d-4104-a1d3-63e633afafba.aspx</comments>
      <category>Code;JavaScript</category>
    </item>
  </channel>
</rss>