views:

387

answers:

2

I use the jQuery Autocomplete plugin to display user info in the search box and I can't quite figure out the meaning of the syntax of the following parse function:

$("#UserSearchBox").autocomplete('FindUser.ashx', 
{
  minChars: 2,
  width: 400,
  max: 5,
  parse: function(data) 
  {
    return $.map(eval(data), function(row) 
    {
      return {
        data: row,
        value: row.UserID,
        result: "" 
    }
  });
},
formatItem: function(item) 
{
  return FormatUser(item);
});

The plugin works fine: it retrieves JSONified array of user info from an HTTP handler and displays formatted values with the help of the FormatUser function, but I'd really like to know what the following code does (I just copied it from the sample and adjusted for to user object):

return $.map(eval(data), function(row) 
{
  return {
    data: row,
    value: row.UserID,
    result: "" 
  }
});

Also, why does the opening brace of the second return must be on the same line as the return statement? If I change code to this:

return $.map(eval(data), function(row) 
{
  return 
  {
    data: row,
    value: row.UserID,
    result: "" 
  }
});

I get an error about an invalid label data. Any ideas? Thanks.

+2  A: 

That is because JavaScript inserts automatic semicolon.

Check http://stackoverflow.com/questions/1188551/common-programming-mistakes-for-javascript-developers-to-avoid/1188800#1188800

If you have code like

function test()
{
    int i = 5;


    return 
    {
        output : i
    };  
}

It is interpreted as:

function test()
{
    int i = 5;


    return; //automatic semicolon insertion by JavaScript the code below is dead code.
    {
        output : i
    };  
}

That's why you need the opening brace on the same line as 'return'.

SolutionYogi
Thank you. Did not know that. So for my first question, I assume the code returns an object with 3 properties: data, value, and result, right?
Alek Davis
Yes, that's correct. the anonymous function passed to the map method returns an object with 3 properties.
SolutionYogi
+1  A: 

JavaScript has some syntax rules about the semi-colon which cause things like this. If at the end of a line a semi-colon could be placed then it is placed. This is what allows you to forget to put them all sorts of places. It also causes this sort of thing because a return can be used on its own.

The parser sees this:

return $.map(eval(data), function(row) 
{
  return ;
  {
    data: row,
    value: row.UserID,
    result: "" 
  }
});
KayEss
Thank you. Did not know that.
Alek Davis