let

var Variables in JavaScript are function scoped. This is different from many other languages (C# / Java etc.) where the variables are block scoped. If you bring a block scoped mindset to JavaScript, you would expect the following to print 123, instead it will print 456:

  1. var foo = 123;
  2. if (true) {
  3. var foo = 456;
  4. }
  5. console.log(foo); // 456

This is because { does not create a new variable scope. The variable foo is the same inside the if block as it is outside the if block. This is a common source of errors in JavaScript programming. This is why TypeScript (and ES6) introduces the let keyword to allow you to define variables with true block scope. That is if you use let instead of var you get a true unique element disconnected from what you might have defined outside the scope. The same example is demonstrated with let:

  1. let foo = 123;
  2. if (true) {
  3. let foo = 456;
  4. }
  5. console.log(foo); // 123

Another place where let would save you from errors is loops.

  1. var index = 0;
  2. var array = [1, 2, 3];
  3. for (let index = 0; index < array.length; index++) {
  4. console.log(array[index]);
  5. }
  6. console.log(index); // 0

In all sincerity we find it better to use let whenever possible as it leads to lesser surprises for new and existing multi-lingual developers.

Functions create a new scope

Since we mentioned it, we’d like to demonstrate that functions create a new variable scope in JavaScript. Consider the following:

  1. var foo = 123;
  2. function test() {
  3. var foo = 456;
  4. }
  5. test();
  6. console.log(foo); // 123

This behaves as you would expect. Without this it would be very difficult to write code in JavaScript.

Generated JS

The JS generated by TypeScript is simple renaming of the let variable if a similar name already exists in the surrounding scope. E.g. the following is generated as is with a simple replacement of var with let:

  1. if (true) {
  2. let foo = 123;
  3. }
  4. // becomes //
  5. if (true) {
  6. var foo = 123;
  7. }

However if the variable name is already taken by the surrounding scope then a new variable name is generated as shown (notice _foo):

  1. var foo = '123';
  2. if (true) {
  3. let foo = 123;
  4. }
  5. // becomes //
  6. var foo = '123';
  7. if (true) {
  8. var _foo = 123; // Renamed
  9. }

Switch

You can wrap your case bodies in {} to reuse variable names reliably in different case statement as shown below:

  1. switch (name) {
  2. case 'x': {
  3. let x = 5;
  4. // ...
  5. break;
  6. }
  7. case 'y': {
  8. let x = 10;
  9. // ...
  10. break;
  11. }
  12. }

let in closures

A common programming interview question for a JavaScript developer is what is the log of this simple file:

  1. var funcs = [];
  2. // create a bunch of functions
  3. for (var i = 0; i < 3; i++) {
  4. funcs.push(function() {
  5. console.log(i);
  6. })
  7. }
  8. // call them
  9. for (var j = 0; j < 3; j++) {
  10. funcs[j]();
  11. }

One would have expected it to be 0,1,2. Surprisingly it is going to be 3 for all three functions. Reason is that all three functions are using the variable i from the outer scope and at the time we execute them (in the second loop) the value of i will be 3 (that’s the termination condition for the first loop).

A fix would be to create a new variable in each loop specific to that loop iteration. As we’ve learnt before we can create a new variable scope by creating a new function and immediately executing it (i.e. the IIFE pattern from classes (function() { /* body */ })();) as shown below:

  1. var funcs = [];
  2. // create a bunch of functions
  3. for (var i = 0; i < 3; i++) {
  4. (function() {
  5. var local = i;
  6. funcs.push(function() {
  7. console.log(local);
  8. })
  9. })();
  10. }
  11. // call them
  12. for (var j = 0; j < 3; j++) {
  13. funcs[j]();
  14. }

Here the functions close over (hence called a closure) the local variable (conveniently named local) and use that instead of the loop variable i.

Note that closures come with a performance impact (they need to store the surrounding state).

The ES6 let keyword in a loop would have the same behavior as the previous example:

  1. var funcs = [];
  2. // create a bunch of functions
  3. for (let i = 0; i < 3; i++) { // Note the use of let
  4. funcs.push(function() {
  5. console.log(i);
  6. })
  7. }
  8. // call them
  9. for (var j = 0; j < 3; j++) {
  10. funcs[j]();
  11. }

Using a let instead of var creates a variable i unique to each loop iteration.

Summary

let is extremely useful to have for the vast majority of code. It can greatly enhance your code readability and decrease the chance of a programming error.