What is the difference between let and var in JavaScript?
What is the difference between let and var in JavaScript?
The main diferences between let and var lie in scope, variable hoisting, redeclaration, and global object binding.
01 scope
The scope of var is function-level, while the scope of let is block-level.
var: Function scope. When declared inside a function, it’s only accessible within that function; outside, it becomes a global variable.let: Block scope. When declared inside{}, it’s only accessible within that block.
1
2
3
4
5
6
7
if(true) {
var a = 10
let b = 20
}
console.log(a) // 10
console.log(b) // ReferenceError: b is not defined
02 Hoisting
var: Declarations are hoisted to the top of scope and initlized asundefined.let: Also hoisted, but kept in “temporal dead zone(TDZ)”. It will cause an error if accessed beforehand.
1
2
3
4
5
console.log(a);
var a = 10; // undefined
console.log(b);
let b = 20; // ReferenceError: Cannot access 'b' before initialization
03 Redeclaration
var: Allows redeclaration within the same scope without any errors;let: Does not allow redeclaration within the same scope.
1
2
3
4
5
var a = 1;
var a = 2; // OK
let b = 1;
let b = 2; // SyntaxError: Identifier 'b' has already been declared
04 Global Object Binding
var: When declared in the global scope, it attaches to the global object(windowin broswers)let: Does not atttach to the global object.
1
2
3
4
5
var a = 10;
console.log(window.a) // 10
let b = 20;
console.log(window.b) // undefined
This post is licensed under CC BY 4.0 by the author.