scope - Javascript: rounded parentheses surrounding comma separated expressions -


playing on js console faced curious syntax. wonder if can tell me more on that..

try this:

>( function f(){console.log('i f')} , (function x(){console.log('i x')})() , y=2 , console.log('hello') ) x hello undefined >f() referenceerror: f not defined >this.y 2 

this fail:

( var c=2 ) syntaxerror: unexpected token var

so comma separated expressions inside parentheses evaluated, assignments happens against global scope, named function declarations references stay trapped inside closure more... putting line inside function declaration called new:

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

and instantiating:

>var c=new c() x hello undefined >c.y undefined >this.y 2 

happens same, executed in global scope!

what's usage / purpose of construct?

one more:

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

so named function can't referenced neither inside brackets.

the named functions aren't "trapped inside", because they're not function declarations (using function statement), in fact function expressions (using function operator). means names not become references in current namespace.


certain keyword/tokens can used statements, such var, hence error thrown if try use them in conditions interpreter expects expression.


as y === 2, because did not var y; inside c, y = 2 sets window.y, , in global scope this === window.


whats usage / purpose of construct?

  • the comma operator , lets multiple expressions on 1 line.
  • function expressions useful great many things, invoking them have closure, or storing them inside variables, etc.

Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo