Self-reflection on var, let and const
In fact, I have always had a simple understanding of var, let and const. When the interviewer asked me the difference between var and let, I answered that the difference was that let could not be improved by variable. I did not even answer that they could not repeat the statement. This also cost me a lot in the interview. So I decided to figure him out once and for all… Come and see me perform
var
Var, let, and const variables cannot be deleted. If you do not use them, you can delete them and free space.
d = 1;var a =1;let b =2;const c =3;
delete a; // Print false
delete b; // Print false
delete c; // Print false
delete d; // Print ture
console.log(d) //Uncaught ReferenceError: D is not defined indicates that the space of D is freed
Copy the code
The declared variable is a property of the window object. The declared variable is also a property of the window object.
a = 1;
var b = 2;
console.log(window.a) / / 1
console.log(window.b) / / 2
Copy the code
Used in strict mode
'use strict'
a = 1; // Uncaught ReferenceError: a is not defined
Copy the code
let
- Allows arbitrary nesting of block-level scopes
- The outer scope cannot read variables from the inner scope
- The inner scope can define variables of the same name for the outer scope
- The scope of a function itself is within its block-level scope
'use strict'
function fn(){console.log('123')}
(function(){
if(true) {function fn(){
console.log('456')
}
})()
fn(); }} {123}}} {123}};
Copy the code
Note: Let declares a block-scoped variable that disappears after a ‘} ‘result
const
It defines a constant that differs from let in that it cannot be reassigned and will report an error
Var&let &const
- The variable defined by VAR does not have the concept of block, can be accessed across fast, cannot be accessed across functions, variable promotion, can be repeatedly declared
- Variables defined by let can only be accessed in block scope, not across fast or function, without variable promotion and cannot be declared repeatedly.
- A variable declared by a LET is only valid in the block-level scope. There is no promotion of the variable, but it is bound to a temporary dead zone, or let variable promotion. However, the variable cannot be used before the let declaration.