Variables defined with const and let are no longer properties on window; redeclaration with let will throw

Published: | Categories: JavaScript

Description

As part of the ECMAScript 2015 (ES6) compliance, the behaviour of the const and let statements has been changed to match the spec.

Previously, global variables defined with those statements could be accessed as properties on the global object (window or this in the global scope) like global variables defined with var. This no longer works, so both let x = 1; alert(window.x); and const y = 1; alert(window.y); will be undefined, while var z = 1; alert(window.z); still dumps 1. The easiest workaround here is to use var instead of const and let.

At the same time, redeclaration of global variables with let is now disallowed, therefore the following code snippets will no longer work:

<script>
  let a = 1;
  let a = 2; // raises TypeError
</script>
<script>
  let a = 1;
</script>
<script>
  let a = 2; // raises TypeError
</script>
<script src="let.js"></script>
<script>
  let a = 2; // raises TypeError if a is defined in let.js
</script>

Also, code evaluated with the eval method will no longer propagate global variables defined with let or const to the outer context, therefore this also doesn’t work:

<script>
  eval('let a = 1;');
  alert(a); // raises ReferenceError
</script>

Note that the let statement no longer requires an explicit JavaScript version.

Update: Starting with Firefox 46, redeclaration of variables will throw a SyntaxError instead of TypeError as per the spec.

References