DrillLab
第 47 / 105 道47 / 105 · #301

ES6 有哪些新特性

Name the new ES6 features

先自己答,再往下看Answer it yourself first

一句话:2015 年那一版改动最大, 十来个东西今天天天在用

按重要性排(面试挑五六个说清就够, 别背清单):

  • let / const—— 块作用域(#282)
  • 箭头函数—— 简写 + 词法 this(#285)
  • 模板字符串——`${x}`,支持多行
  • 解构——const { a, b } = objReact 里到处在用
  • 展开 / 剩余——...不可变更新的基础
  • 默认参数
  • Promise—— 异步的转折点(#306)
  • class—— 原型的语法糖(#302)
  • ES 模块——import / export(#308)
  • Map / Set(#286、#287)、Symbolfor…of 与迭代器、生成器

会追问:「ES6 之后还有什么好用的?」—— 这题答得出来会显得你在跟进:async/await(ES2017)、 可选链 ?. 和空值合并??(ES2020)、Object.entries(ES2017)、Array.flat(ES2019)、at(-1)(ES2022)、structuredClone
可选链和 ??这两个尤其值得提, 因为它们直接减少了大量防御式代码。

In one line: the 2015 edition changed the most, and a dozen or so of its additions are things you use every single day.

Ordered by weight — pick five or six and explain them properly, do not recite the list:

  • let / const — block scope (#282)
  • Arrow functions — shorter, plus a lexical this (#285)
  • Template literals`${x}`, and they span lines
  • Destructuring const { a, b } = obj, used everywhere in React
  • Spread and rest..., the basis of immutable updates
  • Default parameters
  • Promise — the turning point for async (#306)
  • class — sugar over prototypes (#302)
  • ES modulesimport / export (#308)
  • Map / Set (#286, #287), Symbol, for…of with iterators, generators

Follow-up: “What came after ES6 that you like?” — answering this makes you look like you keep up: async/await (ES2017), optional chaining ?. and nullish coalescing ?? (ES2020), Object.entries (ES2017), Array.flat (ES2019), at(-1) (ES2022), structuredClone.
Optional chaining and ?? are the two most worth naming, because they cut out a mountain of defensive code.