Playing on JS console I faced a curious syntax. I wonder if someone can tell me more on that..
Try this:
>( function f(){console.log('i am f')} , (function x(){console.log('i am x')})() , y=2 , console.log('hello') )
i am x
hello
undefined
>f()
ReferenceError: f is not defined
>this.y
2
This will fail:
( var c=2 ) SyntaxError: Unexpected token var
So comma separated expressions inside parentheses are evaluated, assignments happens to be against global scope, but named function declarations references stay trapped inside just like a closure more... putting that line inside a function declaration called with new:
function C(){
( function f(){console.log('i am f')} , (function x(){console.log('i am x')})() , y=2 , console.log('hello') )
}
and then instantiating:
>var c=new C()
i am x
hello
undefined
>c.y
undefined
>this.y
2
Happens exactly the same, just as executed in the global scope!
What's the usage / purpose of this construct?
One more:
>( function f(){console.log('i am f')} , f() )
ReferenceError: f is not defined
So the named function can't be referenced neither inside brackets.
The named functions aren't "trapped inside", because they're not function declarations (using function as a statement), they are in fact function expressions (using function as an operator). This means that their names do not become references to themselves in the current namespace.
Certain keyword/tokens can only be used as statements, such as var, hence an error is thrown if you try to use them in conditions which the interpreter expects to be an expression.
As for the y === 2, this is because you did not var y; inside C, so y = 2 sets window.y, and in the global scope this === window.
whats the usage / purpose of this construct?
, lets you do multiple expressions on one line.Wrapping code in parentheses forces it to be parsed as an expression.
The var keyword is only valid as a statement, so this creates a syntax error.
Function declarations can either be statements (which create a hoisted variable) or expressions (which do not create any variable).
Thus, wrapping the function in parentheses turns it into a function expression, which does not create an externally-visible name.
For more information, see here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With