Why let Beats var in JavaScript: Scope, Hoisting, and Performance
This article compares JavaScript's var and let declarations, showing how let provides block scope, avoids hoisting pitfalls, and delivers noticeable performance gains in loops, illustrated with clear code examples and benchmark results.
When reviewing foreign front‑end code, ES6 features such as let are already widely used.
Although let and var share similar syntax, let improves both semantics and performance. The article compares them in two aspects.
Syntax
Example 1
for(var i = 0; i < 2; i++){
console.log('outer i: ' + i);
for(var i = 0; i < 2; i++){
console.log('inner i: ' + i);
}
}The nested loops share the same i variable, so the outer loop is affected by the inner loop’s changes.
Replacing var with let isolates the block scope:
for(let i = 0; i < 2; i++){
console.log('outer i: ' + i);
for(let i = 0; i < 2; i++){
console.log('inner i: ' + i);
}
}The output shows that the outer and inner loops no longer interfere because each let declaration is limited to its own block.
Example 2
console.log(a);
var a = 'hi';This logs undefined because JavaScript hoists the var declaration to the top, effectively executing as:
var a;
console.log(a);
a = 'hi';Using let instead throws a ReferenceError since the variable is not hoisted.
console.log(a);
let a = 'hi';Performance
A simple benchmark compares var and let in a loop of one million iterations.
// var version
var start = +new Date();
for(var i = 0; i < 1000000; i++){
var num = 123;
var str = 'abc';
var obj = {key:'value'};
var arr = ['bill','dell'];
}
var end = +new Date();
console.log(end - start);In Firefox the average runtime is about 53 ms .
// let version
'use strict';
var start = +new Date();
for(var i = 0; i < 1000000; i++){
let num = 123;
let str = 'abc';
let obj = {key:'value'};
let arr = ['bill','dell'];
}
var end = +new Date();
console.log(end - start);The let version averages roughly 5 ms , demonstrating a clear speed improvement.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
