OSDN Git Service

Regular updates
[twpd/master.git] / es6.md
1 ---
2 title: ES2015+
3 category: JavaScript
4 layout: 2017/sheet
5 tags: [Featured]
6 updated: 2019-11-14
7 weight: -10
8 intro: |
9   A quick overview of new JavaScript features in ES2015, ES2016, ES2017, ES2018 and beyond.
10 ---
11
12 ### Block scoping
13
14 #### Let
15
16 ```js
17 function fn () {
18   let x = 0
19   if (true) {
20     let x = 1 // only inside this `if`
21   }
22 }
23 ```
24 {: data-line="2,4"}
25
26 #### Const
27
28 ```js
29 const a = 1
30 ```
31
32 `let` is the new `var`. Constants work just like `let`, but can't be reassigned.
33 See: [Let and const](https://babeljs.io/learn-es2015/#let--const)
34
35 ### Backtick strings
36
37 #### Interpolation
38
39 ```js
40 const message = `Hello ${name}`
41 ```
42
43 #### Multiline strings
44
45 ```js
46 const str = `
47 hello
48 world
49 `
50 ```
51
52 Templates and multiline strings.
53 See: [Template strings](https://babeljs.io/learn-es2015/#template-strings)
54
55 ### Binary and octal literals
56
57 ```js
58 let bin = 0b1010010
59 let oct = 0o755
60 ```
61
62 See: [Binary and octal literals](https://babeljs.io/learn-es2015/#binary-and-octal-literals)
63
64 ### New methods
65
66 #### New string methods
67
68 ```js
69 "hello".repeat(3)
70 "hello".includes("ll")
71 "hello".startsWith("he")
72 "hello".padStart(8) // "   hello"
73 "hello".padEnd(8) // "hello   " 
74 "hello".padEnd(8, '!') // hello!!!
75 "\u1E9B\u0323".normalize("NFC")
76 ```
77
78 See: [New methods](https://babeljs.io/learn-es2015/#math--number--string--object-apis)
79
80 ### Classes
81
82 ```js
83 class Circle extends Shape {
84 ```
85
86 #### Constructor
87
88 ```js
89   constructor (radius) {
90     this.radius = radius
91   }
92 ```
93 {: data-line="1"}
94
95 #### Methods
96
97 ```js
98   getArea () {
99     return Math.PI * 2 * this.radius
100   }
101 ```
102 {: data-line="1"}
103
104 #### Calling superclass methods
105
106 ```js
107   expand (n) {
108     return super.expand(n) * Math.PI
109   }
110 ```
111 {: data-line="2"}
112
113 #### Static methods
114
115 ```js
116   static createFromDiameter(diameter) {
117     return new Circle(diameter / 2)
118   }
119 }
120 ```
121 {: data-line="1"}
122
123 Syntactic sugar for prototypes.
124 See: [Classes](https://babeljs.io/learn-es2015/#classes)
125
126 ### Exponent operator
127
128 ```js
129 const byte = 2 ** 8
130 // Same as: Math.pow(2, 8)
131 ```
132 {: data-line="1"}
133
134 Promises
135 --------
136 {: .-three-column}
137
138 ### Making promises
139
140 ```js
141 new Promise((resolve, reject) => {
142   if (ok) { resolve(result) }
143   else { reject(error) }
144 })
145 ```
146 {: data-line="1"}
147
148 For asynchronous programming.
149 See: [Promises](https://babeljs.io/learn-es2015/#promises)
150
151 ### Using promises
152
153 ```js
154 promise
155   .then((result) => { ··· })
156   .catch((error) => { ··· })
157 ```
158 {: data-line="2,3"}
159
160
161 ### Using promises with finally
162
163 ```js
164 promise
165   .then((result) => { ··· })
166   .catch((error) => { ··· })
167   .finally(() => { // logic independent of success/error })
168 ```
169 {: data-line="4"}
170
171 The handler is called when the promise is fulfilled or rejected.
172
173
174 ### Promise functions
175
176 ```js
177 Promise.all(···)
178 Promise.race(···)
179 Promise.reject(···)
180 Promise.resolve(···)
181 ```
182
183 ### Async-await
184
185 ```js
186 async function run () {
187   const user = await getUser()
188   const tweets = await getTweets(user)
189   return [user, tweets]
190 }
191 ```
192 {: data-line="2,3"}
193
194 `async` functions are another way of using functions.
195
196 See: [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)
197
198 Destructuring
199 -------------
200 {: .-three-column}
201
202 ### Destructuring assignment
203
204 #### Arrays
205
206 ```js
207 const [first, last] = ['Nikola', 'Tesla']
208 ```
209 {: data-line="1"}
210
211 #### Objects
212
213 ```js
214 let {title, author} = {
215   title: 'The Silkworm',
216   author: 'R. Galbraith'
217 }
218 ```
219 {: data-line="1"}
220
221 Supports for matching arrays and objects.
222 See: [Destructuring](https://babeljs.io/learn-es2015/#destructuring)
223
224 ### Default values
225
226 ```js
227 const scores = [22, 33]
228 const [math = 50, sci = 50, arts = 50] = scores
229 ```
230
231 ```js
232 // Result:
233 // math === 22, sci === 33, arts === 50
234 ```
235
236 Default values can be assigned while destructuring arrays or objects.
237
238 ### Function arguments
239
240 ```js
241 function greet({ name, greeting }) {
242   console.log(`${greeting}, ${name}!`)
243 }
244 ```
245 {: data-line="1"}
246
247 ```js
248 greet({ name: 'Larry', greeting: 'Ahoy' })
249 ```
250
251 Destructuring of objects and arrays can also be done in function arguments.
252
253 ### Default values
254
255 ```js
256 function greet({ name = 'Rauno' } = {}) {
257   console.log(`Hi ${name}!`);
258 }
259 ```
260 {: data-line="1"}
261
262 ```js
263 greet() // Hi Rauno!
264 greet({ name: 'Larry' }) // Hi Larry!
265 ```
266
267 ### Reassigning keys
268
269 ```js
270 function printCoordinates({ left: x, top: y }) {
271   console.log(`x: ${x}, y: ${y}`)
272 }
273 ```
274 {: data-line="1"}
275
276 ```js
277 printCoordinates({ left: 25, top: 90 })
278 ```
279
280 This example assigns `x` to the value of the `left` key.
281
282 ### Loops
283
284 ```js
285 for (let {title, artist} of songs) {
286   ···
287 }
288 ```
289 {: data-line="1"}
290
291 The assignment expressions work in loops, too.
292
293
294 ### Object destructuring
295
296 ```js
297 const { id, ...detail } = song;
298 ```
299 {: data-line="1"}
300
301 Extract some keys individually and remaining keys in the object using rest (...) operator
302
303
304 Spread
305 ------
306
307 ### Object spread
308
309 #### with Object spread
310
311 ```js
312 const options = {
313   ...defaults,
314   visible: true
315 }
316 ```
317 {: data-line="2"}
318
319 #### without Object spread
320
321 ```js
322 const options = Object.assign(
323   {}, defaults,
324   { visible: true })
325 ```
326
327 The Object spread operator lets you build new objects from other objects.
328
329 See: [Object spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator)
330
331 ### Array spread
332
333 #### with Array spread
334
335 ```js
336 const users = [
337   ...admins,
338   ...editors,
339   'rstacruz'
340 ]
341 ```
342 {: data-line="2,3"}
343
344 #### without Array spread
345
346 ```js
347 const users = admins
348   .concat(editors)
349   .concat([ 'rstacruz' ])
350 ```
351
352 The spread operator lets you build new arrays in the same way.
353
354 See: [Spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator)
355
356 Functions
357 ---------
358
359 ### Function arguments
360
361 #### Default arguments
362
363 ```js
364 function greet (name = 'Jerry') {
365   return `Hello ${name}`
366 }
367 ```
368 {: data-line="1"}
369
370 #### Rest arguments
371
372 ```js
373 function fn(x, ...y) {
374   // y is an Array
375   return x * y.length
376 }
377 ```
378 {: data-line="1"}
379
380 #### Spread
381
382 ```js
383 fn(...[1, 2, 3])
384 // same as fn(1, 2, 3)
385 ```
386 {: data-line="1"}
387
388 Default, rest, spread.
389 See: [Function arguments](https://babeljs.io/learn-es2015/#default--rest--spread)
390
391 ### Fat arrows
392
393 #### Fat arrows
394
395 ```js
396 setTimeout(() => {
397   ···
398 })
399 ```
400 {: data-line="1"}
401
402 #### With arguments
403
404 ```js
405 readFile('text.txt', (err, data) => {
406   ...
407 })
408 ```
409 {: data-line="1"}
410
411 #### Implicit return
412 ```js
413 numbers.map(n => n * 2)
414 // No curly braces = implicit return
415 // Same as: numbers.map(function (n) { return n * 2 })
416 numbers.map(n => ({
417   result: n * 2
418 }))
419 // Implicitly returning objects requires parentheses around the object
420 ```
421 {: data-line="1,4,5,6"}
422
423 Like functions but with `this` preserved.
424 See: [Fat arrows](https://babeljs.io/learn-es2015/#arrows-and-lexical-this)
425
426 Objects
427 -------
428
429 ### Shorthand syntax
430
431 ```js
432 module.exports = { hello, bye }
433 // Same as: module.exports = { hello: hello, bye: bye }
434 ```
435
436 See: [Object literal enhancements](https://babeljs.io/learn-es2015/#enhanced-object-literals)
437
438 ### Methods
439
440 ```js
441 const App = {
442   start () {
443     console.log('running')
444   }
445 }
446 // Same as: App = { start: function () {···} }
447 ```
448 {: data-line="2"}
449
450 See: [Object literal enhancements](https://babeljs.io/learn-es2015/#enhanced-object-literals)
451
452 ### Getters and setters
453
454 ```js
455 const App = {
456   get closed () {
457     return this.status === 'closed'
458   },
459   set closed (value) {
460     this.status = value ? 'closed' : 'open'
461   }
462 }
463 ```
464 {: data-line="2,5"}
465
466 See: [Object literal enhancements](https://babeljs.io/learn-es2015/#enhanced-object-literals)
467
468 ### Computed property names
469
470 ```js
471 let event = 'click'
472 let handlers = {
473   [`on${event}`]: true
474 }
475 // Same as: handlers = { 'onclick': true }
476 ```
477 {: data-line="3"}
478
479 See: [Object literal enhancements](https://babeljs.io/learn-es2015/#enhanced-object-literals)
480
481
482 ### Extract values
483
484 ```js
485 const fatherJS = { age: 57, name: "Brendan Eich" }
486
487 Object.values(fatherJS)
488 // [57, "Brendan Eich"]
489 Object.entries(fatherJS)
490 // [["age", 57], ["name", "Brendan Eich"]]
491 ```
492 {: data-line="3,5"}
493
494
495 Modules
496 -------
497
498 ### Imports
499
500 ```js
501 import 'helpers'
502 // aka: require('···')
503 ```
504
505 ```js
506 import Express from 'express'
507 // aka: const Express = require('···').default || require('···')
508 ```
509
510 ```js
511 import { indent } from 'helpers'
512 // aka: const indent = require('···').indent
513 ```
514
515 ```js
516 import * as Helpers from 'helpers'
517 // aka: const Helpers = require('···')
518 ```
519
520 ```js
521 import { indentSpaces as indent } from 'helpers'
522 // aka: const indent = require('···').indentSpaces
523 ```
524
525 `import` is the new `require()`.
526 See: [Module imports](https://babeljs.io/learn-es2015/#modules)
527
528 ### Exports
529
530 ```js
531 export default function () { ··· }
532 // aka: module.exports.default = ···
533 ```
534
535 ```js
536 export function mymethod () { ··· }
537 // aka: module.exports.mymethod = ···
538 ```
539
540 ```js
541 export const pi = 3.14159
542 // aka: module.exports.pi = ···
543 ```
544
545 `export` is the new `module.exports`.
546 See: [Module exports](https://babeljs.io/learn-es2015/#modules)
547
548 Generators
549 ----------
550
551 ### Generators
552
553 ```js
554 function* idMaker () {
555   let id = 0
556   while (true) { yield id++ }
557 }
558 ```
559
560 ```js
561 let gen = idMaker()
562 gen.next().value  // → 0
563 gen.next().value  // → 1
564 gen.next().value  // → 2
565 ```
566
567 It's complicated.
568 See: [Generators](https://babeljs.io/learn-es2015/#generators)
569
570 ### For..of iteration
571
572 ```js
573 for (let i of iterable) {
574   ···
575 }
576 ```
577
578 For iterating through generators and arrays.
579 See: [For..of iteration](https://babeljs.io/learn-es2015/#iterators--forof)