preface
It’s 2021, whether you’ve been working there for years or just starting out at the front end. ES6 grammars must be one of the most important weapons in your Arsenal. But the knowledge of ES6 syntax is vast, and we don’t have to know all of it, just a few that processes use frequently. This article is in line with the purpose of combing the common knowledge points in ES6 and set out.
What is a ES6? What’s the point of learning it?
Do you often hear people say ES6 but don’t know what it is? I’m sure there is, but what exactly is ES6?
Answer :ES6 is a new generation of language standard, upgrading and optimizing the core part of JS, standardizing the use of JS, adding JS native methods, making JS more standard, more elegant, more suitable for the development of large applications. Learning ES6 is a necessary step towards becoming a professional front-end.
What is the difference between ES6,ES5 and ES2015?
ES6 is a general concept, refers to the next generation language JS language standard, including ES2015,ES2017,ES2018 and so on.
ES2015 is a special reference, especially refers to the new generation of JS language standards released in 2015.
Currently, ES2015 is equivalent to ES6 by default in most scenarios.
ES5 generally refers to the previous generation of language standards. ES2015 is the time demarcation between ES5 and ES6.
Var, let, the difference between const
Let,const was introduced to solve ES5’s lack of block-level scope. The lack of block-level scope can cause problems such as for loop var variable leakage, variable overwriting, etc. While let,const, has its own scope. And solved the problem of var variable promotion.
Var, let,const
- Let,const variables declared have their own block-level scope.
- Let, a variable declared by const, cannot be used before the variable declaration. There are temporary dead zones.
- Let,const declared variables do not have variable promotion.
- Variables declared by let and const cannot be declared twice.
- Let,const global variables declared do not hang below the top-level object.
Let vs. const
- Variables declared by const need to be assigned immediately; let does not.
- Const variables statement if it is a basic data types, after the assignment cannot be changed, if it is the reference data type can change the internal data direct assignment but can not be changed.
String changes in ES6
Template string
In ES6, a string template is added. When concatenating large strings, backslash (‘) is used instead of adding strings. All Spaces and newlines are preserved, making string concatenation more intuitive and elegant.
The new method
ES6 adds an includes() method to the String prototype, replacing the traditional method of using only indexOf to find characters. In addition, startsWith(), endsWith(), padStart(),padEnd(),repeat() and other methods are added, which can be conveniently used to find and complete strings.
Number changes in ES6
The new method
ES6 has added isFinite(), an isNaN() method to the Number prototype to replace the traditional global isFinite() method, which detects whether a value isFinite and NaN. The isFinite() and isNaN() methods of ES5 will first convert non-numeric parameters to Number. This is not reasonable and will cause isNaN(‘NaN’) === true. But isNaN says this isNaN. Number.isfinite () and number.isnan () do not have this problem (number.isnan (‘NaN’) === false). (isFinite()
Array changes in ES6
Array structure assignment
ES6 allows you to extract values from arrays and objects and assign values to variables in a pattern called Destructuring.
Previously, to assign a value to a variable, you had to specify a value directly.
let a = 1;
let b = 2;
let c = 3;
Copy the code
ES6 allows you to write it like this.
let [a, b, c] = [1, 2, 3];
Copy the code
The above code shows that you can extract values from an array and assign values to variables in their respective locations.
When declaring a lot of variables, there is no need to write a lot of let(VAR), and the mapping relationship is clear, and the default value is supported.
Extended operator
ES6’s new extension operators make it easy to convert arrays and loose sequences from one another. Can replace arguments object and apply method to easily obtain the set of arguments when the number of arguments is unknown.
2. The extension operator can also easily implement array copy.
The new method
ES6 added the find() method to the Array prototype to replace the traditional method of using only indexOf to find items containing an Array, and fixed a bug where indexOf could not find NaN ([NaN].indexof (NaN) === -1). In addition, methods such as includes() and flat() are added, which can be easily used for searching, completing and converting strings.
Object changes in ES6
A concise representation of the property
ES6 allows variables and functions to be written directly as properties and methods of objects. It’s much more concise.
var foo = 'bar'; var baz = {foo}; Baz // {foo: "bar"} // equivalent to var baz = {foo: foo};Copy the code
In addition to property abbreviations, methods can also be abbreviated.
var o = { method() { return "Hello!" ; }}; Var o = {method: function() {return "Hello! ; }};Copy the code
Structure assignment
Object deconstruction differs from arrays in one important way. The elements of an array are arranged in order, and the value of a variable is determined by its position. The attributes of an object have no order, and variables must have the same name as the attributes to get the correct value.
let { bar, foo } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"
let { baz } = { foo: "aaa", bar: "bbb" };
baz // undefined
Copy the code
Extended operator
Object extension operator (…) . The use of extension operators for ES6 objects is not fundamentally different from the use of array extension operators, since arrays are just special objects. One of the most common and useful uses of object extension operators is to easily extract all or part of the traversable properties of a target object to merge and decompose the object.
let {apple, orange, ... otherFruits} = {apple: 'red apple', orange: 'yellow orange', grape: 'purple grape', peach: 'sweet peach'}; // otherFruits {grape: 'purple grape', peach: 'sweet peach'} Let moreFruits = {ripe: 'nice ripe '}; let allFruits = {apple, orange, ... otherFruits, ... moreFruits};Copy the code
The new method
A. ES6 added is() method to the Object prototype to make an equal comparison between two target objects to improve the ‘===’ method. Object. Is fixed a minor bug where NaN === NaN //false in the ‘=== =’ method was actually unreasonable. (Object.is(NaN, NaN) // true)
B. ES6 adds a new assign() method to the Object prototype, which can be used to add attributes to objects or merge multiple objects.
Note: The merged assign object only merges its own attributes in source1 and source2. It does not merge inherited attributes in source1 and source2. It also does not merge non-enumerable attributes.
C. ES6 adds getPrototypeOf() and setPrototypeOf() methods to get or set the prototype of the current Object. The meaning of this method is that in ES5, the __proto__ attribute is achieved through the __proto__ attribute. However, the __proto__ attribute is not explicitly specified in the ES specification, but is added by the browser manufacturers by default because it is applicable to a wide range of properties. This is not always available in a non-browser environment, so to be on the safe side, use the new ES6 standard usage when getting or setting the current object’s Prototype object.
D. ES6 also added object.keys (), object.values (), object.entries () methods to the Object prototype, which are used to obtain all keys, all values and all key-value pairs arrays of objects.
Function changes in ES6
Arrow function
Arrow function is one of the core upgrade items of ES6, arrow function does not have its own this, which changes the JS function in the past the most difficult to understand this operation mechanism.
The this in the arrow function refers to the object on which the function was defined, not the object on which the function was executed
In A. ES5 functions, this always points to the object where the function is executed, which makes it difficult to understand the direction of this in many cases, especially in non-strict mode, this sometimes points to global objects, which can even be attributed to one of the language level bugs. The arrow function in ES6 optimizes this by not having its own this inside, which results in this always pointing to this at the upper level. If the upper level is still an arrow function, it continues pointing up until it points to a function with its own this as its own this.
B. The arrow function cannot be used as a constructor because it does not have its own this and cannot be instantiated.
C. Arrow functions do not have their own this, so there are no arguments objects in arrow functions. (You can use the extension operator instead.)
The function is assigned by default
The function is assigned by default. Before ES6, function parameters could not be given default values and could only be implemented inside functions by workarounds. ES6 does default function assignment in a cleaner and more explicit way.
function es6Fuc (x, y = 'default') {
console.log(x, y);
}
es6Fuc(4) // 4, default
Copy the code
The new method
ES6 adds the double colon operators to replace bind, call, and apply. (Not supported by browser, Babel already supports transcoding)
foo::bar; // Equivalent to bar.bind(foo); foo::bar(... arguments); // equivalent to bar.apply(foo, arguments);Copy the code
New data structure Set
Set is a new collection data structure in ES6. Similar to an array, but with unique values for its members. This feature makes array de-duplication easy. MDN Definition of Set
The Set object allows you to store a unique value of any type, either a primitive value or an object reference.
New data structure weakSet
WeakSet is similar to Set and also contains non-repeating members, but there are two differences from Set.
First, WeakSet members can only be objects, not other types of values.
Secondly, the objects in WeakSet are weak references, that is, garbage collection mechanism does not consider WeakSet’s reference to the object, that is to say, if other objects no longer reference the object, then garbage collection mechanism will automatically recover the memory occupied by the object, not considering the object still exists in WeakSet. This feature means that a WeakSet member cannot be referenced, so a WeakSet is not traversal.
Added data structure Map
A Map is similar to an Object, except that the key of an Object can only be a string, whereas the key of a Map can be any data type. Can describe the properties of the object more comprehensively.
MDN Definition of Map
The Map object holds key-value pairs and can remember the original insertion order of the keys. Any value (object or raw value) can be a key or a value.
New data structure WeakMap
WeakMap structure is similar to Map structure and is also used to generate a set of key-value pairs
First point :WeakMap members can only be iterable objects, not other types of data.
Second point: Objects in a WeakMap are weak references
Promise
Promise is a new object introduced in ES6. Its main purpose is to solve the “callback hell” caused by the callback mechanism in JS asynchronous mechanism. It’s not a breakthrough API, but it encapsulates the asynchronous callback form, making it more elegant to write, more readable, and chainable to call.
Iterator
Iterator is an important concept in ES6. It is not an object, nor is it any data type. ES6 adds a Set and Map type, which is similar to Array and Object. Array and Object can be traversed, but neither Set nor Map can be traversed with a for loop. There are two solutions to solve this problem: one is to add a separate API for traversing Set and Map. The other option is to add a unified traversal API for sets, Maps, arrays, and Objects. Obviously, the second option is better, and ES6 naturally needs a design standard to unify the traversal of all traversable types. Iterator is just such a standard. Or a normative idea.
iterable
To be an iterable, an object must implement the @@iterator method. This means that the object (or an object in its prototype chain) must have a property with a key of @@iterator, accessible through the constant symbol. iterator:
How do YOU tell if a type is an iterable
let someString = "hi";
typeof someString[Symbol.iterator]; // "function"
Copy the code
- Common iterables include Array, Map, Set, String,TypeArray, and arguments
- You can determine whether the current variable is an iterable by judging symbol. iterator
for… In and for.. The difference of
Let’s look at it directly from a piece of code
console.log(this.length); } var myArray=[1,2,4,5,6,7] myarray. name=" array "for (var index in myArray) {console.log(myArray[index]); }Copy the code
- Index retrieves the index
- The order of traversal may not be sequential
- Using for in iterates through all enumerable properties of a set of numbers, including stereotypes. For example, method and name above are traversed
- For in is better for traversing objects, rather than using for in to traverse groups of numbers
Array.prototype.method=function(){ console.log(this.length); } var myArray=[1,2,4,5,6,7] myarray. name=" array "; for (var value of myArray) { console.log(value); }Copy the code
- The for of syntax iterates over the value of an array element
- For in traverses the index
- For of traverses only the elements of the array, excluding the array’s prototype property Method and index name
summary
- for.. Of is applicable to iterators such as numbers/array objects/strings/maps/sets that have iterator objects. Objects cannot be iterated over because there are no iterators. Unlike forEach(), it responds correctly to break, continue, and return statements.
- For in iterates through an ordinary object, which is essentially what it does. For in iterates through stereotypes and enumerable properties, and in the best case, hasOwnProperty to determine if it is an instance property.