0

I am trying to document my javascript with JSDoc. However, it won't parse this code due to a "unexpected token error located in the 4th line of the following code. I've looked through the entire code block with luck.

/** Create a new sorter given a table element */
return
{
    create: function(table, initialSortedColumn, customDataAccessors)
    {
        var sorter = Object.create(sorterPrototype);
        sorter.init(table, initialSortedColumn, customDataAccessors);
        return sorter;
    }
};

1 Answers1

2

You have a new line after return, so according to the rules for Automatic Semicolon Insertion (ASI), it is treated as having ; in the end, so the return statement ends there.

Therefore, according to the parser you have the following unrelated code afterwards:

{
    create: function(table, initialSortedColumn, customDataAccessors)
    {
        var sorter = Object.create(sorterPrototype);
        sorter.init(table, initialSortedColumn, customDataAccessors);
        return sorter;
    }
};

This is interpreted as a code block starting with { on the first line and finishing with }; on the last line. Inside it, you have a label called create and a function statement with no name of the function. Having nameless function statements is illegal, hence why you get the error.

In effect, you have according to the JavaScript parsing rules, the following problematic code:

function(/* parameters */) { /* body */ }

In reality, your top level function will always return undefined due to ASI and the code after will never be reached but you still get an error from parsing it.

What you want to do is the following:

return {
    create: function(table, initialSortedColumn, customDataAccessors)
    {
        var sorter = Object.create(sorterPrototype);
        sorter.init(table, initialSortedColumn, customDataAccessors);
        return sorter;
    }
};

This way you are returning an object with a property called create an a function assigned to it.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • On a somewhat related note - I don't think having a JSDoc comment *inside* a function (before the `return` statement) will be parsed by JSDoc. I think you need that to be documenting the function that has the `return` statement itself. But I'm not sure - best to check the JSDoc manuals. – VLAZ Nov 04 '18 at 16:37
  • This is why, I believe, it's a best-practice in JavaScript to always, place the opening curly braces on the end of the line that they correlate to. – Scott Marcus Nov 04 '18 at 16:39
  • It's almost like we used semi-colons there for a reason. I can't believe this is a thing. – MrYellow Mar 10 '21 at 06:41