samuelgoto / proposal-block-params

A syntactical simplification in JS to enable DSLs
205 stars 8 forks source link

Scope of `var` in the block? #24

Open ljharb opened 6 years ago

ljharb commented 6 years ago

(related to #16 and #21)

var has function scope:

function foo() {
  console.log(bar, baz); // logs 3, 4

  var bar = 3;
  {
    var baz = 4;
  }
}

What happens when this is done inside a block param?:

function foo() {
  console.log(bar, baz); // logs 3, ??

  var bar = 3;
  something {
    var baz = 4;
  }
}

(and how does this change in strict vs sloppy mode?)

syg commented 6 years ago

The proposal as stands radically changes the scoping + hoisting mental model around { } and makes it even more confusing IMO.

syg commented 6 years ago

It also goes much more beyond var, if { } in control-structure-like expressions are suddenly function scopes, at least the following:

samuelgoto commented 6 years ago

All really good points, thanks for filling. As raised by Mark, would disallowing var inside block params mitigate some of these problems?

syg commented 6 years ago

As raised by Mark, would disallowing var inside block params mitigate some of these problems?

Making vars hoist to the nearest syntactically obvious function as dherman has suggested would work as well.

samuelgoto commented 6 years ago

Got it, thanks.

Fair to say that, if some of those are acceptable alternatives, we would still have the remaining challenge of:

Changes performance mental model of closures being allocated

But would address the following:

Changes variable captures Changes top-level function statement hoisting

syg commented 6 years ago

Indeed. More problematically, with TCP, the implementability of this proposal is prohibitively low. It would require very significant engineering to get correct and fast in current engines. Without TCP, would you still want to push for the feature?

samuelgoto commented 6 years ago

Without TCP, would you still want to push for the feature?

As a rule of thumb, no, I don't think I'd want this feature without TCP, but I'd want to look on a case by case basis to understand what the trade-offs are.