Javascript: rounded parentheses containing comma separated expressions

While playing on the JS console, I came across a curious syntax. I wonder if anyone can tell me more about this.

Try the following:

>( 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 var token

Thus, expressions separated by commas inside brackets are evaluated, assignments are against the global scope, but links to function declarations remain trapped inside, like closing More ... placing this line inside a function declaration with a new one:

 function C(){ ( function f(){console.log('i am f')} , (function x(){console.log('i am x')})() , y=2 , console.log('hello') ) } 

and then the instance:

 >var c=new C() i am x hello undefined >cy undefined >this.y 2 

It happens exactly the same as on a global scale!

What is the use / purpose of this design?

Another:

 >( function f(){console.log('i am f')} , f() ) ReferenceError: f is not defined 

Thus, in the named function, you cannot refer inside the brackets.

+4
source share
2 answers

Named functions are not "locked inside" because they are not function declarations (using function as a statement ), they are actually functional expressions (using function as an operator ). This means that their names do not become references to themselves in the current namespace.


Some keywords / tokens can only be used as operators, such as var , so an error occurs if you try to use them in conditions that the interpreter expects to be an expression.


As for y === 2 , this is because you are not var y; inside C , so y = 2 sets window.y in the global scope this === window .


What is the use / purpose of this design?

  • The comma operator allows you to execute multiple expressions on the same line. Functional Expressions
  • useful for a lot of things, whether it be immediate access to them, so you have to close or store them inside variables, etc.
+5
source

The code in parentheses forces it to be parsed as an expression.

The var keyword only acts as an operator, so this creates a syntax error.

Function declarations can be either operations (that create an upstream variable) or expressions (that don't create any variable).

Thus, wrapping a function in parentheses turns it into a function expression that does not create an external visible name.

For more information see here .

+4
source

Source: https://habr.com/ru/post/1497703/


All Articles