JavaScript tip 4: use let and const

ES6 (aka. ECMAScript 2015, 6th edition) introduced the let and const statements.

These are meant as alternatives to var and baring browser compatibility issues, I recommend that you should be using them over var.

Speaking of browser compatibility, modern browsers support them, the main pain point being IE version 10 and older. Sadly some of us (ahem… yours truly) still sometimes work on intranet applications that must support older browsers so I mention it.

The difference between let and var is that let is scoped to the current scope (function, block, expression) while var is scoped to it’s containing function or barring that globally.

Here are some examples of behaviour which people not used to var‘s scoping might find odd:

function test1() {
  var foo = 1;

  if (true) {
    var foo = 2;
  }

  console.log(foo);  
}

test1();

function test2() {
  let foo = 1;

  if (true) {
    let foo = 2;
  }

  console.log(foo);  
}

test2();

Here test1() returns 2 even though the second foo declaration was in an inner scope. test2() on the other hand returns 1 has the second foo is scoped to it’s containing if statement.

Here is another example:

function test3() {
  for (var i = 0; i < 10; i++) {
    var inner = i;  
  }
    
  console.log(inner);
}

test3();

function test4() {
  for (let i = 0; i <= 10; i++) {
    let inner = i;  
  }
  
  console.log(inner);
}

test4();

In test3(), the output is 9 which is the last value of i in the loop’s inner scope. test4() returns an inner is not defined error which is more appropriate.

const scoping rules work like let but:

  • You must assign a value at declaration
  • You cannot re-assign a new value later on

This behaviour is similar to readonly and const in other languages like C# and affords an extra level of security for values that cannot change.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s