let command and const
ES6 added let
command and const
command, used to declare variables.
1. let command
let
Command is used to declare variables. Variables declared it, only let
valid within a block command is located.
{
let a = 10;
var b = 1;
}
a; // ReferenceError: a is not defined.
b; // 1
let
Variables command statement, does not appear "变量提升"
the phenomenon.
// var声明的变量会出现变量提升
console.log(foo); // 'undefined'
var foo = 2;
// let声明的变量不会出现变量提升
console.log(bar); // 报错ReferenceError
let bar = 2;
ES6 provides for a block let
and const
variable declarations command, will form a closed scope. Those who would use these variables in a statement before the error is reported.
{
// 变量未声明就使用,报错。
x= 'abc'; // Uncaught ReferenceError: Cannot access 'mm' before initialization
let x;
}
let
Command does not allow the same scope, the statement repeated the same variable.
function func() {
let a = 10;
let a = 1; // Uncaught SyntaxError: Identifier 'a' has already been declared
}
2. const command
const
Declares a read-only constant. Once declared, the value of the constant can not be changed.
const PI = 3.1415926;
PI // 3.1415926
// 不能再次赋值
PI = 3; // VM1846:4 Uncaught TypeError: Assignment to constant variable
const
Variable declarations may not change the value, that const
once you declare a variable, you must initialize immediately.
// 声明时必须立即初始化
const size; // Uncaught SyntaxError: Missing initializer in const declaration
const
Scope and let
command the same: block-level role only in the region where it is declared effective.
if (true) {
// 只在本作用域内有效
const MAX = 5;
}
MAX // Uncaught ReferenceError: MAX is not defined
const
Constant declarations, but also with let
not repeat the same statement.
const yyy = 12;
// 不能重复声明变量
const yyy = 36; // Uncaught SyntaxError: Identifier 'yyy' has already been declared
const
The value of the variable declaration command can not be changed, in fact, that address memory variable points to the saved data may not be changed. For simple types of data, the value stored at that memory address pointed to by the variable, and therefore equal to the constant. However, for complex data types, variable points to the memory address, a pointer to save only the actual data, const
can ensure that this pointer is fixed, as it points to the data structure is not variable, is not affected.
// 声明一个变量并赋值
const example = {};
// 为 example 添加一个属性,可以成功
example.x = 123;
// 将 example 指向另一个对象,就会报错
example= []; // Uncaught TypeError: Assignment to constant variable
3. Description
I am a beginner, this is their own study notes, any questions, please point out! E-mail: [email protected]