I just came across one use case that I had to use var
over let
to introduce new variable. Here's a case:
I want to create a new variable with dynamic variable names.
let variableName = 'a';
eval("let " + variableName + '= 10;');
console.log(a); // this doesn't work
var variableName = 'a';
eval("var " + variableName + '= 10;');
console.log(a); // this works
The above code doesn't work because eval
introduces a new block of code. The declaration using var
will declare a variable outside of this block of code since var
declares a variable in the function scope.
let
, on the other hand, declares a variable in a block scope. So, a
variable will only be visible in eval
block.