Recap JavaScript(lesson2): const in ES6

In lesson1 we went over let in ES6. In addition to let, ES6 has a new member called Const.

Const can also create block-scoped variables, but the value is fixed, that is, constant, and changes to its value will result in an error.

There are some notes about the use of const:

1. The declaration requires an assignment

const constTest;
Unexpected token = Unexpected token
Copy the code

2. The assignment cannot be modified

const constTest = 30;
constTest = 40;
// Error: "constTest" is read-only
Copy the code

3. The declared object reference cannot be changed, but the properties of the object can be modified

const constObj = {};
constObj = {name:"New_Name"}
// Error: "constObj" is read-only
Copy the code

As shown in the code above, an error occurs when a const constObj is declared, initialized as an empty object, and then assigned to another object. But we can change it to add or remove attributes to the object pointed to by constObj without error. Look at the code:

const constObj = {};
constObj.name = 'New_Name';
constObj.age = 18;
delete constObj.name;
console.log(constObj)
//{age: 18}
Copy the code

Here we declare constObj and initialize it as an empty object. Next, give constObj the name and age attributes, and then remove the name attribute, which are all legal operations.

When we declare an array using const, we have a similar situation:

const constArr = [];
constArr = [];
// Error message: "constArr" is read-only
Copy the code
const constArr = [];
constArr.push(1);
constArr.unshift(2);
console.log(constArr)
/ / (2, 1)
Copy the code

4. Variables created with const are valid only in block-level scope

if(true) {
  const maxItems = 5;
  console.log(maxItems)/ / 5
}
console.log(maxItems)//maxItems is not defined
Copy the code

As the code shows, maxItesms is declared in the if statement, so it is only accessible within it, not externally.

5. Relevant interview questions

Use ES5 to implement const functionality

function _const(key, value) {    
	const desc = {        
			value,        
			writable: false    
	}    
	Object.defineProperty(window, key, desc)
}

_const('obj', {a: 1})   / / define obj
obj.b = 2  // Obj attributes can be assigned normally
obj = {} / / an error
Copy the code

The object.defineProperty () method is used to change the attribute characteristics of an Object. This method takes three parameters: a description Object with an attribute Object, the attribute name, and the attribute characteristics. The code uses a custom _const function to declare an obj object as const. The reference code: mp.weixin.qq.com/s/aywCFgyDh…

Well, that’s all for today’s review. Please do not hesitate to correct any mistakes. Welcome to review old knowledge and climb new steps with me