ECMAScript let const and 6 of command

let command and const

ES6 added letcommand and constcommand, used to declare variables.

1. let command

letCommand is used to declare variables. Variables declared it, only letvalid within a block command is located.

{
  let a = 10;
  var b = 1;
}

a; // ReferenceError: a is not defined.
b; // 1

letVariables 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 letand constvariable 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; 
}

letCommand 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

constDeclares 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

constVariable declarations may not change the value, that constonce you declare a variable, you must initialize immediately.

// 声明时必须立即初始化
const size; // Uncaught SyntaxError: Missing initializer in const declaration

constScope and letcommand 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

constConstant declarations, but also with letnot repeat the same statement.

const yyy = 12;
// 不能重复声明变量
const yyy = 36; // Uncaught SyntaxError: Identifier 'yyy' has already been declared

constThe 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, constcan 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]

Published 15 original articles · won praise 3 · Views 3658

Guess you like

Origin blog.csdn.net/qq_41863849/article/details/104424127