What are the differences in the usage of var let const in JavaScript
- 2021-11-29 06:03:36
- OfStack
STEP 1 Repeat declarations
var supports duplicate declarations, while let and const do not.
1.1 var
var a = 1;
var a = 2;
console.log(a);
Output:
2
1.2 let
let b = 3;
let b = 4;
console.log(b);
Output:
Uncaught SyntaxError: Identifier 'b' has already been declared
1.3 const
const c = 5;
const c = 6;
console.log(c);
Output:
Uncaught SyntaxError: Identifier 'c' has already been declared
2. Variable promotion
var supports variable promotion, but only the promotion declaration does not promote the value. let and const do not support variable elevation.
2.1 var
a=2;
console.log(a);
var a = 1;
Output:
2
2.2 let
a=2;
console.log(a);
let a = 1;
Output:
Uncaught ReferenceError: Cannot access 'a' before initialization at index.html:28
2.3 const
a=2;
console.log(a);
const a = 1;
Output:
Uncaught ReferenceError: Cannot access 'a' before initialization at index.html:28
3. Temporary dead zone
There is no temporary dead zone in var, but there are temporary dead zones in let and const.
As long as let and const exist in the scope, the variables or constants they declare are automatically "bound" in this area and are no longer affected by the external scope.
3.1 var
var a = 1;
function fun() {
console.log(a);
var a = 2;
}
fun();
Output:
undefined
3.2 let
let a = 1;
function fun() {
console.log(a);
let a = 2;
}
fun();
Output:
Uncaught ReferenceError: Cannot access 'a' before initialization
3.3 conset
let a = 1;
function fun() {
console.log(a);
const a = 2;
}
fun();
Output:
Uncaught ReferenceError: Cannot access 'a' before initialization
4. Properties and methods of window objects
In global scope, variables declared by var, through functions declared by function, automatically become properties and methods of window objects.
var a = 1;
function add() { };
console.log(window.a === a);
console.log(window.add === add);
Output:
true
true
5. Block-level scope
var has no block-level scope, while let and const have block-level scope.
Use
var
Define the variable i in the for loop:
let b = 3;
let b = 4;
console.log(b);
0
Output:
3
Use
let
Define the variable i in the for loop:
let b = 3;
let b = 4;
console.log(b);
1
Output:
Uncaught ReferenceError: i is not defined