where
Var variable declaration can be re-defined and re-assignment
var price = 100; //var声明的变量可重新赋值和重复定义
price = 200;
console.log(price);
var price = 100; //var声明的变量可重新赋值和重复定义
var price = 200;
console.log(price);
Ends are 200 codes above results in the console display
- var scope: function scope (var variable var variables created in a function can only function in the role, was not created in a function all global variables)
var price = 100;
var count = 10;
if (count > 5) {
var discount = price * 0.6;
console.log(`The discount is ${discount}`);
}
Results console: 60
Note: In this case the value of the discount directly accessible external braces, because at this time it does not belong to any function, so the global variables
let
- let Scope: block scope (block-level scope, i.e., let variable declarations in curly braces only within the braces)
var price = 100;
var count = 10;
if (count > 5) {
let discount = price * 0.6;
console.log(`The discount is ${discount}`);
}
At this time, the value of the discount is not directly accessible outside
var price = 100;
var count = 10;
let discount = 90;
if (count > 5) {
let discount = price * 0.6;
}
When the console access discount, find a value of 90. Because if statement let the outside is a global variable, we have direct access to the global variables.
- But can not be reassigned repeat the same scope statement
let discount = 90;
discount = 100;
At this time, the console access discount, a value of 100
const
- Scope with let
var price = 100;
var count = 10;
if (count > 5) {
count discount = price * 0.6;
console.log(`The discount is ${discount}`);
}
At this time, the value of the discount is not directly accessible outside
- Unrepeatable declaration space and can not be reassigned in the same role, but if as an object, you can change the properties of which
const person = {
name: 'Jelly',
age:20
}
person.age = 21;
Enter the person in the console, get
{name: "Jelly", age: 21}
If the attribute is not supposed to change, ES5 may be used in Object.freeze () method
const person = {
name: 'Jelly',
age:20
}
Object.freeze(person)
person.age = 21;
In the console input person, get
{name: "Jelly", age: 20}