Junior
What is the difference between let and var?
sobes.tech AI
Answer from AI
var has function or global scope, can be redeclared and overwritten. It is subject to Hoisting, initialized as undefined.
let has block scope, can be overwritten but not redeclared in the same scope. Also subject to Hoisting, but is in the "temporal dead zone" until initialization.
Comparison table:
| Characteristic | var |
let |
|---|---|---|
| Scope | Function/Global | Block |
| Redeclaration | Yes | No |
| Overwrite | Yes | Yes |
| Hoisting | Yes | Yes |
| Initialization | undefined |
- (temporal dead zone) |
Example:
// var
function exampleVar() {
var x = 10;
if (true) {
var x = 20; // Redeclaration of x
console.log(x); // 20
}
console.log(x); // 20
}
// let
function exampleLet() {
let y = 10;
if (true) {
let y = 20; // New variable y in block scope
console.log(y); // 20
}
console.log(y); // 10
}
exampleVar();
exampleLet();