[ Web Proxy ]
URL:
Viewing: https://javascript.info/task/check-syntax [Back]  [Original]

Syntax check
EN

We want to make this open-source project available for people all around the world.

Help to translate the content of this tutorial to your language!

    Search on Javascript.info:
    Search in the tutorial:
    Light themeDark theme
    DanskEnglishEspaolFranaisIndonesiaItalianoTrkeOzbek
    back to the lesson

    Syntax check

    importance: 2

    What is the result of this code?

    let user = {
      name: "John",
      go: function() { alert(this.name) }
    }
    
    (user.go)()

    P.S. Theres a pitfall :)

    solution

    Error!

    Try it:

    let user = {
      name: "John",
      go: function() { alert(this.name) }
    }
    
    (user.go)() // error!

    The error message in most browsers does not give us much of a clue about what went wrong.

    The error appears because a semicolon is missing after user = {...}.

    JavaScript does not auto-insert a semicolon before a bracket (user.go)(), so it reads the code like:

    let user = { go:... }(user.go)()

    Then we can also see that such a joint expression is syntactically a call of the object { go: ... } as a function with the argument (user.go). And that also happens on the same line with let user, so the user object has not yet even been defined, hence the error.

    If we insert the semicolon, all is fine:

    let user = {
      name: "John",
      go: function() { alert(this.name) }
    };
    
    (user.go)() // John

    Please note that parentheses around (user.go) do nothing here. Usually they setup the order of operations, but here the dot . works first anyway, so theres no effect. Only the semicolon thing matters.


    Web Proxy Viewer  |  New URL  |  Original Page