Do you know these properties in ES6

ES6, also known as esmascript 2015, has added many easy-to-use features

Variable declaration

Before ES6, var was used to define variables. ES6 added two variable declaration methods, const and let, respectively. Const was used to define constants and let was used to define variables, making up for the vulnerability of using var to define variables.

  • var has variable promotion. All variables defined in the global / function will be promoted to the top of the global / function, and the value is undefined
  • var does not have the concept of block level scope. Variables defined through if / for /switch will be promoted to the global level
  • let defines variables that can be modified and cannot be declared repeatedly. It has a block level scope
  • const defines a constant. It needs to be assigned a value during definition. It cannot be modified or declared repeatedly. It has a block level scope

Their main differences are as follows

Assignment required for initializationVariable promotionRepeat declarationReassignBlock level scopeCross block accessCross function access
var×××
let×××××
const×××××

let and const save variables to the variable environment before definition, but they are not accessible.

let userName = 'alice'
if (true) {
  console.log(userName)
  let userName = 'kiki'
}

The execution result of the above code is as follows

In the above code, there is a userName variable in the block level function created through if. Although there is also a userName variable in the global, at this time, the block has been saved to the variable environment of the block through let definition, and will be obtained directly from the block, but it is still inaccessible before assignment, so there is a problem of [temporary dead zone]

Literal enhancement

In objects, attributes are defined in a more concise way.

  • When the attribute key and value defined in the object are consistent, they can be merged
  • The function declaration can be removed from the method abbreviation
  • Properties in the object can define non string variables through []
var name = 'alice'
var age = 18
var info = 'hobby'

var user = {
  name: name,
  age: age,
  eating: function () {
    console.log('user eating~')
  }
}
user[info + 's'] = 'swimming'

const person = {
  name,
  age,
  eating() {
    console.log('person eating~')
  },
  [info + 's']: 'swimming'
}

console.log(user)
console.log(person)

The final effect of the above two methods of defining objects is the same

deconstruction

Array deconstruction

When we want to obtain the elements of the array, we often use the subscript value. es6 provides us with a way of deconstruction to obtain each element through the one-to-one correspondence of the subscript value

//Get element by subscript value
var names = ['alice', 'kiki', 'macus']
var x = names[0]
var y = names[1]
var z = names[2]
console.log(x, y, z)

// deconstruction
var [a, b, c] = names
console.log(a, b, c)

// When only the last two elements are needed, the first element is empty
var [, m, n] = names
console.log(m,n)

// When there is only one element, the remaining parameters are placed in an array
var [x, ...list] = names
console.log(x, list)

The results are as follows

By compiling es6 code into es5 code through babel, it can be found that array deconstruction still obtains elements through subscript values

Object deconstruction

When obtaining the value of an object, we usually use. Key or [key]. es6 also provides a simpler way to deconstruct the object. Note that the deconstructed variables should correspond to the key value

var user = {
  name: 'alice',
  age: 20
}
console.log(user.name, user.age)

var { name, age } = user
console.log(name, age)

The results of the above two methods of obtaining attribute values are consistent

By compiling es6 code into es5 code through babel, it can be found that the principle of object deconstruction is still in the form of object and attribute name

Template string

Before there is no template string, you need to use quotation marks ("") to splice strings and variables. The readability of the code is relatively weak. After adding template characters, you can directly write strings in ` ` and embed dynamic contents through ${expression}

const name = 'aclie'
const age = 18
const user = 'My name is ' + name + ' and i am ' + age + ' years old.'
const person = `My name is ${name} and i am ${age} years old.`

console.log(user)
console.log(person)

The results of the above two ways of defining variables are consistent

``You can also splice the execution results of functions

function getAnimalName(){
  return 'cat'
}
const animal = 'This is a ' + getAnimalName()
const pet = `This is a ${getAnimalName()}`

console.log(animal)
console.log(pet)

Splicing through the + sign is the same as the template string

``It can also be used to call functions to split parameters through template strings

const name = 'aclie'
const age = 18
function foo(a, b, c, d) {
  console.log(a)
  console.log(b)
  console.log(c)
  console.log(d)
}
foo`1${name}2${age}3${100}`

The data in each template string corresponds to a parameter of the incoming function, and the remaining data divided form an array as the parameter

The template string to es5 code is spliced through the concat method of string

Default arguments to functions

Before es6, you need to judge whether the function has an input parameter. If not, assign the variable of the input parameter to an initialized value

function getUserInfo(name, age){
  name = name || 'kiki'
  age = age || 18
  console.log(name,age)
}
getUserInfo('', 0)

function getPersonInfo(name = 'alice', age = 18){
  console.log(name, age)
}
getPersonInfo('alice', 0)

If there is a | operator, when the incoming parameter is an empty string or 0, it will be considered false and the code after the | operator will be executed

You can also deconstruct objects using the default parameters of the function

function getUserInfo({ name, age } = { name: 'kiki', age: 18 }) {
  console.log(name, age)
}
getUserInfo()

function getPersonInfo({name = 'kiki', age = 18} = {}){
  console.log(name, age)
}
getPersonInfo()

The results of deconstruction in the two ways are the same

The default parameter discovery of the function compiled by babel is processed by arguments

Remaining parameters

Before es6, all the input parameters of the function can be obtained through arguments. es6 adds the syntax of the remaining parameters to refer to the arguments that are not corresponding to the formal parameters

function foo(a, b, ...rest) {
  console.log('arguments', arguments)
  console.log(a, b, rest)
}
foo(1, 2, 3, 4, 5, 6)

Get the remaining parameters through the operator of

There are some differences between arguments and the remaining parameters

  • All arguments can be obtained through arguments, while the remaining parameters can only obtain arguments that are not corresponding to formal parameters, and there are no arguments in the arrow function
  • The data structure of arguments is like an array, but it is not a real array. You can't use the array method directly, and the remaining parameters are an array. You can use the array method directly

When the remaining parameters are compiled into browser compatible es5 syntax through babel, the data obtained through arguments is added one by one by creating an array

Expand syntax

Expansion syntax is also used to operate data through... And there are three application scenarios for expansion syntax

  • Function call
  • Array construction
  • When building object literals (ES9 syntax)
const array = [1, 2, 3]
const obj = { name: 'alice', age: 20}
const name = 'kiki'

// function call
function foo(a, b, c){
  console.log(a, b, c)
}
foo(...array)
foo(...name)

// Array construction
const newArr = [...array, 4, 5]
console.log(newArr)

// Build object literal
const newObj = {...obj, name: 'kiki'}
console.log(newObj)

You can expand objects, arrays, and strings by expanding syntax

It should be noted that the expansion syntax is actually a shallow copy

const user = { name: 'alice', favorite: { sport: 'tennis'}}
const newUser = {...user}
newUser.name = 'kiki'
newUser.favorite.sport = 'football'
console.log(user)

The favorite attribute in user is an object. The newUser object created by user through expanding syntax modifies the attributes in the object, and the favorite attribute of the original user object will also be changed

Their performance in memory is shown in the following figure

The expansion syntax of arrays and functions is relatively simple through babel compilation. The characteristics of arrays can be passed through the concat method and the second parameter of apply respectively. The expansion syntax of objects is more complex. There are some function encapsulation and logical judgment, so there is no screenshot

Representation of values

Specifies the representation of hexadecimal

  • Binary data, starting with 0b, the maximum value of each digit is 1
  • Octal data, starting with 0o, the maximum value of each digit is 7
  • Hexadecimal data, starting with 0x, A-F represents numbers 10-15, and the maximum value of each digit is f
const a = 0b100
const b = 0o100
const c = 0x100

console.log(a, b, c)

Finally, it will be converted to decimal data

Symbol

Symbol represents a unique value. It is a new data type. Before that, the key value in the object can only use string. If the key value is the same, it will be overwritten, but if you use symbol, it will not be overwritten.

There are also some considerations when defining symbols

  • For variables declared through Symbol, a description can be defined in parentheses and obtained through description (added by ES10)
  • Even if the variables defined by Symbol have the same descriptor, they will not be repeated
  • The variables defined by Symbol.for are global and can be found through Symbol.keyFor. When there is the same description, they point to the same element
  • When Symbol is used as the key value in the object, it needs to use [], and. Cannot be used for assignment
const a = Symbol('hello')
const b = Symbol('hello')
const c = Symbol.for('alice')
const d = Symbol.for('alice')

const obj = {
  [a]: 'alice'
}
obj[b] = 'kiki'
Object.defineProperty(obj, c, {
  value: 'macus'
})

console.log(a)
console.log(a.description)
console.log(a === b)
console.log(c === d)
console.log(Symbol.keyFor(a), Symbol.keyFor(c))
console.log(obj[a], obj[b], obj[c])

The results are as follows

Set and WeakSet

Set

Set means a collection, similar to an array, but the elements it stores cannot be repeated.

Set has these properties and methods

  • size: returns the number of elements in a Set
  • add(value): adds an element and returns the Set object itself
  • delete(value): deletes the element equal to this value from the set and returns the boolean type
  • has(value): judge whether there is an element in the set, and return the boolean type
  • clear(): clear all elements in set without return value
  • forEach(callback, [, thisArg]): traverse the set through forEach
  • Support for / for of traversal
const arr = [{ name: "alice" }, 2, 3, 4, 5, 4, 3, 2, 1]
const set = new Set(arr)

set.add(0)
set.delete(3)

console.log(set.size)
console.log(set.has(1))
console.log(set)
console.log([...set])
console.log(Array.from(set))

for (let item of set) {
  console.log(item)
}
set.forEach(item => {
  console.log(item)
})

The results are as follows

WeakSet

Another data structure similar to Set is called WeakSet, which is different from Set in that

  • The WeakSet can only store object types, not basic data types
  • The WeakSet is a weak reference to an element. If there is no other reference to an object, the garbage collector (GC) can recycle the object

It has these methods

  • add(value): add an element and return the WeakSet object itself
  • delete(value): deletes the element equal to this value from the WeakSet and returns the boolean type
  • has(value): judge whether there is an element in the WeakSet and return the boolean type
const student = { grade: 4 }
let person = { hobby: 'running' }
const arr = [student, person]
const weakSet = new WeakSet(arr)

weakSet.add({ grade: 4 })
weakSet.delete(student)
console.log(weakSet.has(student))
console.log(weakSet)

Because the WeakSet is a weak reference to the element, the introduced content may be recycled by the GC, so it is not possible to traverse and use the toString() method to obtain the element

When the object stored in set is changed from memory address 0x100 to null, the original memory address 0x100 will not be recycled by the garbage collector because there is a strong reference in set, and when the object stored in weakMap is changed from memory address 0x200 to null, the original memory address 0x200 will be recycled by the garbage collector because there is a strong reference in weakSet

Map and WeakMap

Map

Map represents the dictionary storage mapping relationship, which is similar to the object, but the Key data type in the object can only be string or Symbol, which is not limited in map

Common attributes and methods of Map

  • size: returns the number of elements in the Map
  • set(key, value): adds key and value to the Map and returns the entire Map object
  • get(key): get the value in the Map according to the key
  • has(key): determines whether a key is included and returns the Boolean type
  • delete(key): deletes a key value pair according to the key and returns the Boolean type
  • clear(): clear all elements
  • forEach(callback, [, thisArg]): traverse the Map through forEach
  • You can traverse through for of
const user = { name: 'alice' }
const info = { message: 'hello' }
const map = new Map()
map.set(user, info)

// map.clear()
console.log(map.size)
console.log(map.has(user))
console.log(map.get(user))
console.log(map)

map.forEach((value, key)=>{
  console.log(value, key)
})

for(let [key, value] of map){
  console.log('item', key, value)
}

The results are as follows

WeakMap

Similar to Map, but with some differences (similar to those in set and WeakSet)

  • The key of WeakMap can only use objects and does not accept other types as keys
  • The reference of the WeakMap key to the object is a weak reference. If no other reference references the object, the garbage collector (GC) can recycle the object

It has these methods

  • set(key, value): adds key and value to the Map and returns the entire Map object
  • get(key): get the value in the Map according to the key
  • has(key): determines whether a key is included and returns the Boolean type
  • delete(key): deletes a key value pair according to the key and returns the Boolean type

Because the WeakMap is a weak reference to the element, the introduced content may be recycled by the GC, so it is not possible to traverse and use the toString() method to obtain the element

The above are most of the attributes contained in ES6. There are still many places that developers need to master about js advanced. You can see other blog posts I wrote and keep updating~

Tags: Javascript Front-end ECMAScript

Posted on Sun, 28 Nov 2021 09:51:30 -0500 by aliasneo86