Block Scope 1

Did you know that ES5.1 does not support function declarations inside blocks? Browsers do allow it but they do not agree on the semantics. For ES Harmony we are specifying the semantics for functions inside blocks. Functions inside block use let scope, which means that they are limited to the current block scope.

function f() { console.log('outer'); }

{
  function f() { console.log('inner'); }
  f();  // logs 'inner'
}
f();  // logs 'outer'

The block scoped bindings proposal also covers let and const. The let binding is like a var except that its scope is limited to the current block. const is like let but it requires an initializer and can only be written to once.

var functions = [];
for (var i = 0; i < 5; i++) {
  var x = i;
  functions.push(function() {
    alert(x);
  });
}
functions[0]();

The code above alerts 5 because that is what x is when the function is called. Now lets change the inner var to a let.

var functions = [];
for (var i = 0; i < 5; i++) {
  let x = i;
  functions.push(function() {
    alert(x);
  });
}
functions[0]();

This now alerts 0 since every iteration gets a fresh local variable.

const PI = 3.14159265;
// ...
PI = 'Apple Pie';  // throws because PI cannot be reassigned to.

To use these you currently need to use strict mode.

'use strict';
// ...

// or
function f() {
  'use strict';
  // ...
}