Search code examples
javascriptsyntax-errorreferenceerror

Why does the use of a colon in foo:bar() function call return ReferenceError instead of SyntaxError?


var foo = {
    bar: function() { return ""; }
}; 
foo:bar();

The above results in:

Uncaught ReferenceError: bar is not defined

Using it in this context console.log(foo:bar()); results in:

SyntaxError: missing ) after argument list

In some cases object colon object / function does SyntaxError but in this case it doesn't, why is this the case? I have tested this in both node.js and a couple browsers and this behavior is consistent, so I was curious as to what would not produce either error in the context of "foo:bar".

Don't remember how else I achieved a SyntaxError, but it had something to do with calling a function from an object using :


Solution

  • I'm not sure what you wanted to achieve with this.

    Having it as "foo:bar" it has nothing related to foo variable. Instead it declares label with name of 'foo'.

    Declaring label inside of console.log leads to SyntaxError since it break parsing the statesment.

    On the other side having it without console.log as you mentioned has correct syntax: it declares label 'foo' and tries to call the function 'bar' that does not exist. That's why it shows ReferenceError.

    Anyway Javascript expects dot(.) to access object members: foo.bar()