# es6 **Repository Path**: william533036/es6 ## Basic Information - **Project Name**: es6 - **Description**: :star2: ES6 Overview in 350 Bullet Points - **Primary Language**: Unknown - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2020-04-18 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # ES6 Overview in 350 Bullet Points My [ES6 in Depth][39] series consists of 24 articles covering most syntax changes and features coming in ES6. This article aims to summarize all of those, providing you with practical insight into most of ES6, so that you can quickly get started. I've also linked to the articles in ES6 in Depth so that you can easily go deeper on any topic you're interested in. I heard you like bullet points, so I made an article containing hundreds of those bad boys. To kick things off, here's a table of contents with all the topics covered. It has bullet points in it -- **obviously**. Note that if you want these concepts to permeate your brain, you'll have a much better time learning the subject by going through the [in-depth series][39] and playing around, experimenting with ES6 code yourself. ![It's showtime!][40] # Table of Contents - [Introduction](#introduction) - [Tooling](#tooling) - [Assignment Destructuring](#assignment-destructuring) - [Spread Operator and Rest Parameters](#spread-operator-and-rest-parameters) - [Arrow Functions](#arrow-functions) - [Template Literals](#template-literals) - [Object Literals](#object-literals) - [Classes](#classes) - [Let and Const](#let-and-const) - [Symbols](#symbols) - [Iterators](#iterators) - [Generators](#generators) - [Promises](#promises) - [Maps](#maps) - [WeakMaps](#weakmaps) - [Sets](#sets) - [WeakSets](#weaksets) - [Proxies](#proxies) - [Reflection](#reflection) - [`Number`](#number) - [`Math`](#math) - [`Array`](#array) - [`Object`](#object) - [Strings and Unicode](#strings-and-unicode) - [Modules](#modules) Apologies about that long table of contents, and here we go. # Introduction - ES6 -- also known as Harmony, `es-next`, ES2015 -- is the latest finalized specification of the language - The ES6 specification was finalized in **June 2015**, _(hence ES2015)_ - Future versions of the specification will follow the `ES[YYYY]` pattern, e.g ES2016 for ES7 - **Yearly release schedule**, features that don't make the cut take the next train - Since ES6 pre-dates that decision, most of us still call it ES6 - Starting with ES2016 (ES7), we should start using the `ES[YYYY]` pattern to refer to newer versions - Top reason for naming scheme is to pressure browser vendors into quickly implementing newest features [(back to table of contents)](#table-of-contents) # Tooling - To get ES6 working today, you need a **JavaScript-to-JavaScript** _transpiler_ - Transpilers are here to stay - They allow you to compile code in the latest version into older versions of the language - As browser support gets better, we'll transpile ES2016 and ES2017 into ES6 and beyond - We'll need better source mapping functionality - They're the most reliable way to run ES6 source code in production today _(although browsers get ES5)_ - Babel _(a transpiler)_ has a killer feature: **human-readable output** - Use [`babel`][1] to transpile ES6 into ES5 for static builds - Use [`babelify`][2] to incorporate `babel` into your [Gulp, Grunt, or `npm run`][26] build process - Use Node.js `v4.x.x` or greater as they have decent ES6 support baked in, thanks to `v8` - Use `babel-node` with any version of `node`, as it transpiles modules into ES5 - Babel has a thriving ecosystem that already supports some of ES2016 and has plugin support - Read [A Brief History of ES6 Tooling][25] [(back to table of contents)](#table-of-contents) # Assignment Destructuring - `var {foo} = pony` is equivalent to `var foo = pony.foo` - `var {foo: baz} = pony` is equivalent to `var baz = pony.foo` - You can provide default values, `var {foo='bar'} = baz` yields `foo: 'bar'` if `baz.foo` is `undefined` - You can pull as many properties as you like, aliased or not - `var {foo, bar: baz} = {foo: 0, bar: 1}` gets you `foo: 0` and `baz: 1` - You can go deeper. `var {foo: {bar}} = { foo: { bar: 'baz' } }` gets you `bar: 'baz'` - You can alias that too. `var {foo: {bar: deep}} = { foo: { bar: 'baz' } }` gets you `deep: 'baz'` - Properties that aren't found yield `undefined` as usual, e.g: `var {foo} = {}` - Deeply nested properties that aren't found yield an error, e.g: `var {foo: {bar}} = {}` - It also works for arrays, `var [a, b] = [0, 1]` yields `a: 0` and `b: 1` - You can skip items in an array, `var [a, , b] = [0, 1, 2]`, getting `a: 0` and `b: 2` - You can swap without an _"aux"_ variable, `[a, b] = [b, a]` - You can also use destructuring in function parameters - Assign default values like `function foo (bar=2) {}` - Those defaults can be objects, too `function foo (bar={ a: 1, b: 2 }) {}` - Destructure `bar` completely, like `function foo ({ a=1, b=2 }) {}` - Default to an empty object if nothing is provided, like `function foo ({ a=1, b=2 } = {}) {}` - Read [ES6 JavaScript Destructuring in Depth][3] [(back to table of contents)](#table-of-contents) # Spread Operator and Rest Parameters - Rest parameters is a better `arguments` - You declare it in the method signature like `function foo (...everything) {}` - `everything` is an array with all parameters passed to `foo` - You can name a few parameters before `...everything`, like `function foo (bar, ...rest) {}` - Named parameters are excluded from `...rest` - `...rest` must be the last parameter in the list - Spread operator is better than magic, also denoted with `...` syntax - Avoids `.apply` when calling methods, `fn(...[1, 2, 3])` is equivalent to `fn(1, 2, 3)` - Easier concatenation `[1, 2, ...[3, 4, 5], 6, 7]` - Casts array-likes or iterables into an array, e.g `[...document.querySelectorAll('img')]` - Useful when [destructuring](#assignment-destructuring) too, `[a, , ...rest] = [1, 2, 3, 4, 5]` yields `a: 1` and `rest: [3, 4, 5]` - Makes `new` + `.apply` effortless, `new Date(...[2015, 31, 8])` - Read [ES6 Spread and Butter in Depth][6] [(back to table of contents)](#table-of-contents) # Arrow Functions - Terse way to declare a function like `param => returnValue` - Useful when doing functional stuff like `[1, 2].map(x => x * 2)` - Several flavors are available, might take you some getting used to - `p1 => expr` is okay for a single parameter - `p1 => expr` has an implicit `return` statement for the provided `expr` expression - To return an object implicitly, wrap it in parenthesis `() => ({ foo: 'bar' })` or you'll get **an error** - Parenthesis are demanded when you have zero, two, or more parameters, `() => expr` or `(p1, p2) => expr` - Brackets in the right-hand side represent a code block that can have multiple statements, `() => {}` - When using a code block, there's no implicit `return`, you'll have to provide it -- `() => { return 'foo' }` - You can't name arrow functions statically, but runtimes are now much better at inferring names for most methods - Arrow functions are bound to their lexical scope - `this` is the same `this` context as in the parent scope - `this` can't be modified with `.call`, `.apply`, or similar _"reflection"-type_ methods - `arguments` is also lexically scoped to the nearest normal function; use `(...args)` for local arguments - Read [ES6 Arrow Functions in Depth][5] [(back to table of contents)](#table-of-contents) # Template Literals - You can declare strings with `` ` `` (backticks), in addition to `"` and `'` - Strings wrapped in backticks are _template literals_ - Template literals can be multiline - Template literals allow interpolation like `` `ponyfoo.com is ${rating}` `` where `rating` is a variable - You can use any valid JavaScript expressions in the interpolation, such as `` `${2 * 3}` `` or `` `${foo()}` `` - You can use tagged templates to change how expressions are interpolated - Add a `fn` prefix to ``fn`foo, ${bar} and ${baz}` `` - `fn` is called once with `template, ...expressions` - `template` is `['foo, ', ' and ', '']` and `expressions` is `[bar, baz]` - The result of `fn` becomes the value of the template literal - Possible use cases include input sanitization of expressions, parameter parsing, etc. - Template literals are almost strictly better than strings wrapped in single or double quotes - Read [ES6 Template Literals in Depth][4] [(back to table of contents)](#table-of-contents) # Object Literals - Instead of `{ foo: foo }`, you can just do `{ foo }` -- known as a _property value shorthand_ - Computed property names, `{ [prefix + 'Foo']: 'bar' }`, where `prefix: 'moz'`, yields `{ mozFoo: 'bar' }` - You can't combine computed property names and property value shorthands, `{ [foo] }` is invalid - Method definitions in an object literal can be declared using an alternative, more terse syntax, `{ foo () {} }` - See also [`Object`](#object) section - Read [ES6 Object Literal Features in Depth][7] [(back to table of contents)](#table-of-contents) # Classes - Not _"traditional"_ classes, syntax sugar on top of prototypal inheritance - Syntax similar to declaring objects, `class Foo {}` - Instance methods _-- `new Foo().bar` --_ are declared using the short [object literal](#object-literals) syntax, `class Foo { bar () {} }` - Static methods _-- `Foo.isPonyFoo()` --_ need a `static` keyword prefix, `class Foo { static isPonyFoo () {} }` - Constructor method `class Foo { constructor () { /* initialize instance */ } }` - Prototypal inheritance with a simple syntax `class PonyFoo extends Foo {}` - Read [ES6 Classes in Depth][8] [(back to table of contents)](#table-of-contents) # Let and Const - `let` and `const` are alternatives to `var` when declaring variables - `let` is block-scoped instead of lexically scoped to a `function` - `let` is [hoisted][27] to the top of the block, while `var` declarations are hoisted to top of the function - "Temporal Dead Zone" -- TDZ for short - Starts at the beginning of the block where `let foo` was declared - Ends where the `let foo` statement was placed in user code _(hoisiting is irrelevant here)_ - Attempts to access or assign to `foo` within the TDZ _(before the `let foo` statement is reached)_ result in an error - Helps prevent mysterious bugs when a variable is manipulated before its declaration is reached - `const` is also block-scoped, hoisted, and constrained by TDZ semantics - `const` variables must be declared using an initializer, `const foo = 'bar'` - Assigning to `const` after initialization fails silently (or **loudly** _-- with an exception --_ under strict mode) - `const` variables don’t make the assigned value immutable - `const foo = { bar: 'baz' }` means `foo` will always reference the right-hand side object - `const foo = { bar: 'baz' }; foo.bar = 'boo'` won't throw - Declaration of a variable by the same name will throw - Meant to fix mistakes where you reassign a variable and lose a reference that was passed along somewhere else - In ES6, **functions are block scoped** - Prevents leaking block-scoped secrets through hoisting, `{ let _foo = 'secret', bar = () => _foo; }` - Doesn't break user code in most situations, and typically what you wanted anyways - Read [ES6 Let, Const and the “Temporal Dead Zone” (TDZ) in Depth][9] [(back to table of contents)](#table-of-contents) # Symbols - A new primitive type in ES6 - You can create your own symbols using `var symbol = Symbol()` - You can add a description for debugging purposes, like `Symbol('ponyfoo')` - Symbols are immutable and unique. `Symbol()`, `Symbol()`, `Symbol('foo')` and `Symbol('foo')` are all different - Symbols are of type `symbol`, thus: `typeof Symbol() === 'symbol'` - You can also create global symbols with `Symbol.for(key)` - If a symbol with the provided `key` already existed, you get that one back - Otherwise, a new symbol is created, using `key` as its description as well - `Symbol.keyFor(symbol)` is the inverse function, taking a `symbol` and returning its `key` - Global symbols are **as global as it gets**, or _cross-realm_. Single registry used to look up these symbols across the runtime - `window` context - `eval` context - `