Comprehensive ES6 Knowledge Q&A Summary
This article provides a detailed question‑and‑answer overview of ES6, covering its definition, differences from ES5/ES2015, Babel, let, string/array/number/Object enhancements, new data structures like Symbol, Set, Map, Proxy, Reflect, Promise, Iterator, generators, async/await, classes, modules, and practical coding recommendations for modern front‑end development.
1. What is ES6 and why learn it?
ES6 is the new generation JavaScript standard that upgrades the core language, adds native methods, and makes code more standardized, elegant, and suitable for large‑scale applications. Learning ES6 is essential for professional front‑end developers; without it you can still code but only as a "guerrilla".
2. Difference between ES5, ES6 and ES2015
ES2015 refers specifically to the 2015 release of the new JavaScript standard; ES6 is a broader term that includes ES2015, ES2016, ES2017, etc. In most scenarios ES2015 is treated as ES6. ES5 denotes the previous generation.
3. What is Babel?
Babel is an ES6 transpiler that converts ES6 code to ES5 so it can run on platforms that do not yet support ES6.
4. Why use let instead of var?
Before ES6, only var could declare variables, which lacks block scope and causes issues such as variable leakage in loops. let provides block‑level scope and fixes variable‑hoisting problems.
5. String enhancements in ES6
ES6 adds template literals (using backticks) for clearer multi‑line string concatenation, and new methods such as includes() , startsWith() , endsWith() , padStart() , padEnd() , and repeat() for easier searching and manipulation.
6. Array enhancements in ES6
Optimizations:
Destructuring assignment: let [a,b,c] = [1,2,3]
Spread operator: let a = [2,3,4]; let b = [...a]
Upgrades:
find() replaces indexOf and fixes the NaN bug ( [NaN].indexOf(NaN) === -1 ).
Additional methods: copyWithin() , includes() , fill() , flat() .
7. Number enhancements in ES6
New methods on Number : Number.isFinite() and Number.isNaN() avoid the coercion problems of the global isFinite() and isNaN() (e.g., Number.isNaN('NaN') === false ).
8. Object enhancements in ES6
Optimizations:
Property shorthand: let myFruits = {apple, orange} instead of explicit key‑value pairs.
Object destructuring: let {keys, values, entries} = Object;
Object spread: let {apple, orange, ...otherFruits} = {apple:'red', orange:'yellow', grape:'purple', peach:'sweet'};
Super keyword for accessing prototype methods.
Upgrades:
Object.is() for correct NaN comparison.
Object.assign() for shallow merging of objects.
Object.getOwnPropertyDescriptors() , Object.getPrototypeOf() , Object.setPrototypeOf() , Object.keys() , Object.values() , Object.entries() .
9. Function enhancements in ES6
Optimizations:
Arrow functions: lexical this , no own arguments .
Default parameters: function es6Fuc(x, y = 'default') { console.log(x, y); } es6Fuc(4); // 4, default
Upgrade:
Double‑colon operator (stage‑2 proposal) as a shorthand for bind , call , and apply (e.g., foo::bar ).
10. Symbol
Symbols are unique primitive values that prevent property name collisions; they are not enumerated by for...in .
11. Set
Set is a collection of unique values, useful for deduplication.
12. Map
Map is a key‑value collection where keys can be any value (including objects), offering a richer alternative to plain objects.
13. Proxy
Proxy allows interception of fundamental operations (e.g., get , set ) to customize behavior. Example:
function createMyOwnObj() {
return new Proxy({}, {
get(target, propKey) {
return new Promise((resolve, reject) => {
setTimeout(() => {
const ok = Math.random() > 0.5;
const msg = `你的${propKey}运气${ok ? '不错' : '不行'},${ok ? '成功了' : '失败了'}`;
ok ? resolve(msg) : reject(msg);
}, 1000);
});
}
});
}
let myOwnObj = createMyOwnObj();
myOwnObj.hahaha.then(console.log).catch(console.error);14. Reflect
Reflect groups scattered Object/Function methods (e.g., apply , deleteProperty ) into a single namespace and serves as a reliable fallback when Proxy overrides native APIs.
15. Promise
Promise simplifies asynchronous code, avoiding callback hell and enabling chaining.
16. Iterator
Iterator defines a standard protocol for traversable objects via a [Symbol.iterator] method that returns an object with a next() method.
let obj = {
data: ['hello', 'world'],
[Symbol.iterator]() {
const self = this;
let index = 0;
return {
next() {
if (index < self.data.length) {
return { value: self.data[index++], done: false };
}
return { value: undefined, done: true };
}
};
}
};Built‑in collections (Array, String, Set, Map) already implement this protocol.
17. for...in vs for...of
for...of iterates over any object that implements the Iterator protocol, while for...in only enumerates an object's own enumerable properties.
18. Generator functions
Generators are a concrete way to implement the Iterator protocol; each yield corresponds to a next() call and can receive values via next(value) .
19. async functions
async functions are syntactic sugar over generators and Promises, providing a concise way to write asynchronous code.
20. Class and extends
ES6 class is syntactic sugar for constructor functions, offering clearer syntax, inheritance via extends , and non‑enumerable methods.
// ES5
function ES5Fun(x, y) { this.x = x; this.y = y; }
ES5Fun.prototype.toString = function() { return '(' + this.x + ', ' + this.y + ')'; };
var p = new ES5Fun(1,3);
// ES6
class ES6Fun {
constructor(x, y) { this.x = x; this.y = y; }
toString() { return '(' + this.x + ', ' + this.y + ')'; }
}
Object.keys(ES5Fun.prototype); // ['toString']
Object.keys(ES6Fun.prototype); // []21. module, export, import
ES6 modules provide a standardized way to organize code. import is statically resolved at compile time, and imported bindings are live (dynamic) references.
22. Practical ES6 refactoring tips for daily front‑end development
Replace var self = this with arrow functions.
Prefer let / const over var .
Use destructuring for arrays and objects.
Use template literals for multi‑line strings.
Adopt class instead of traditional constructor functions.
Structure code with ES6 modules ( import / export ).
Source: StevenLikeWatermelon – https://juejin.cn/post/6844903734464495623
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.