Question

I am in need of understanding the below java script code, written by someone else. Can you please tell me what the below line means (particularly fourth line).? It is a single lengthy line (till ;). It is not a puzzle. It is a shopping application's code, practically in use (not altered).

function trackMetrics(a,b,c,d)
{
    var e=a,f=b,g=c,h=d;
    typeof a=="object"&&(a.type!=null&&(e=a.type),a.action!=null&&(e=a.action),a.data!=null&&f=a.data),a.map!=null&&(g=a.map),a.load!=null&&(g=a.load)),typeof f=="object"&&(f.data!=null&&(f=f.data),f.map!=null&&(g=f.map),f.load!=null&&(h=f.load)),typeof g=="object"&&(g.map!=null&&(g=g.map),g.load!=null&&(h=g.load));
Was it helpful?

Solution

Well, currently, it means a SyntaxError as it has an unmatched ) just before:

typeof f=="object"

But, it appears to be using the comma operator to group multiple statements (vs. ;) and is using &&'s short-circuiting as an alternative to an if statement.

if (typeof a == "object") {
    if (a.type != null)
        e = a.type;
    if (a.action != null)
        e = a.action;
    if (a.data != null)
        f = a.data;
}

if (a.map != null)
    g = a.map;

// etc.

OTHER TIPS

Just break it into pieces, understanding each by itself, then you can put together the meaning of the whole.

Note that the && operator will stop processing the following conditions when it reaches a false value (called short-circuiting). The comma operator will cause each of the expressions they separate to be executed regardless of the results. Together, they are used by this code to do a lot of logical testing and assignments in one line. (And it is definitely ok to say, "Yuck!" here.)

typeof a=="object"      // If a is of type "object"
&& (                    // then
    a.type!=null        //   if a.type != null
        &&(e=a.type)    //     then e = a.type
    ,a.action!=null     //   if a.action != null
        &&(e=a.action)  //     then e = a.action
    ,a.data!=null       // ... and so on ...
        &&f=a.data)
    ,a.map!=null
        &&(g=a.map)
    ,a.load!=null
        &&(g=a.load)
   )
,typeof f=="object"
    &&(
        f.data!=null
            &&(f=f.data)
       ,f.map!=null
            &&(g=f.map)
       ,f.load!=null
            &&(h=f.load)
      )
,typeof g=="object"
    &&(
        g.map!=null
            &&(g=g.map)
        ,g.load!=null
            &&(h=g.load)
      )
;

After looking it over, it would be tempting to assume that it does nothing, but there are assignments embedded in some of the conditions (like g=a.map). So, you'll need to process the logic (and hopefully understand the meaning) to see what conditions will cause which values to be set.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top