[Javascript] Object Not Defined

Hassan Schroeder hassan at webtuitive.com
Fri Nov 11 13:13:35 CST 2011


On 11/11/11 10:15 AM, Brian L. Matthews wrote:

> The syntax works, but in the first case, if either a or a.data is undefined, it will result in a
> JavaScript error.

Ah, got it; how about

   var foo = function(a){
     try{ result=a.data.items }catch(err){ result=[] }; return result;
   }

Probably not much of an improvement over the original looks-wise :-)

Alternatively, I cheated a bit by writing the equivalent function
in CoffeeScript, which (like Ruby) allows specifying a default value
for arguments, and seeing what it got translated to:

   foo = ( a = {data: {}} ) -> a.data.items || []

which becomes this (compiled/pretty-printed) JavaScript:

   var foo;

   foo = function(a) {
     if (a == null) {
       a = {
         data: {}
       };
     }
     return a.data.items || [];
   };

( using http://jashkenas.github.com/coffee-script/ )

FWIW,
-- 
Hassan Schroeder ----------------------------- hassan at webtuitive.com
webtuitive design ===  (+1) 408-621-3445   === http://webtuitive.com
http://about.me/hassanschroeder
twitter: @hassan
                           dream.  code.


More information about the Javascript mailing list