Search code examples
javascriptecmascript-6es6-modulesvariable-declaration

Are there any contexts / situations in ES6 Modules where it wouldn't work to update var to let?


For some time now, I've used const to declare most variables.

If I don't absolutely know for certain that a new variable will always hold the same value, I will declare the new variable with let.

I almost never use var.

That's me.

However, any other individual writing javascript will have their own preferred variable declaration conventions and, if I am accepting user-generated-content such as User Written ES6 Modules there's no way predict with confidence what those conventions might be.


Leaving aside const for the moment...

var can be overwritten by var:

I know that the following:

  • var myString = 'My String declared with var';
  • var myFunction = function() {console.log('My Function declared with var')};

can be overwritten with identically named variables declared with var.

Example:

var myString = 'My String declared with var';
var myFunction = function() {console.log('My Function declared with var')};

var myString = 'My Overwriting String declared with var';
var myFunction = function() {console.log('My Overwriting Function declared with var')};

console.log(myString);
myFunction();

let cannot be overwritten by var:

I also know that if myString and myFunction are declared with let

  • let myString = 'My String declared with let';
  • let myFunction = function() {console.log('My Function declared with let')};

they cannot subsequently be overwritten with var, let, or const.

Example:

let myString = 'My String declared with let';
let myFunction = function() {console.log('My Function declared with let')};

var myString = 'My Overwriting String declared with var';
var myFunction = function() {console.log('My Overwriting Function declared with var')};

console.log(myString);
myFunction();

So, knowing both these things, is it a reasonable safeguard to convert any var declarations to let declarations (either at compile time or at runtime) in all User Submitted ES6 Modules?

Are there any conceivable contexts / situations in ES6 Modules where it wouldn't work to update var to let?


Solution

  • If a user wrote a function like this, changing var to let would fail:

    function run() {
      for (var i = 0; i < 3; i++) {
        console.log(i);
      }
      console.log('final i', i);
    }
    
    console.log('starting run');
    run();
    
    function runLet() {
      for (let i = 0; i < 3; i++) {
        console.log(i);
      }
      console.log('final i', i);
    }
    
    console.log('starting runLet');
    runLet();

    the runLet function errors because i is undefined.