Search code examples
javascriptexpressionjavascript-objectscurly-brackets

Is the curly brackets object notation valid in any expression?


I'm currently analyzing the Javascript language a bit. It looks like you could group at lot of the concepts into a base type called expression. Even function arguments and definitions fit into that group, as well as strings, numbers and mathematical expressions. The only illogical exception was the curly bracket object notation in a nonsense alike context.

As functions consist of several expressions the following code is valid:

function valid(){
    /\W/;
    "ahll";
    var alpha;
    alpha;
    alpha={"first": 90, "second": 80};
    alpha;
    0, {"first": 90, "second": 80};
    [1,2,3];
    alpha;
    2+3;
    new RegExp("/\W/");
    return true;
}

By intention the following code should be valid too, but gets a "missing ; before statement" syntax error for the second line:

function invalid(){
    {"first": 90, "second": 80};
    return true;
}

The curly bracket object notation is accepted in every other case where expressions are accepted, except for these cases where a curly bracket code block would be allowed too.

Is the syntax error mentioned above caused by the implementation or the specification of javascript?

Is there a more precise name for such nonsense expression?


Solution

  • Is the syntax error mentioned above caused by the implementation or the specification of javascript?

    By the spec.

    Is there a more precise name for such nonsense expression

    You're looking for the term Expression Statement. As you say, Object literals are expressions (even primary expressions), just as most other things are. They can appear in many contexts, like function arguments, operands of an operator or inside brackets.

    However, a function body - code - does not consist of expressions, it does consist of statements. That means things like if-statements, loop statements or plain blocks. Or "expression statements", which are nothing but an expression to be evaluated (and with side effects, they mostly are not "nonsense").

    However, the spec mandates:

    ExpressionStatement: [lookahead ∉ {{, function}] Expression ;

    NOTE: An ExpressionStatement cannot start with an opening curly brace because that might make it ambiguous with a Block. Also, an ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration.