Download Exploring Es6 PDF

TitleExploring Es6
File Size4.1 MB
Total Pages555
Table of Contents
                            Table of Contents
What you need to know about this book
	Audience: JavaScript programmers
	Why should I read this book?
	How to read this book
	Glossary and conventions
		Documenting classes
		Capitalization
	Demo code on GitHub
	Sidebars
	Footnotes
Preface
Acknowledgements
I Background
	About ECMAScript 6 (ES6)
		TC39 (Ecma Technical Committee 39)
		How ECMAScript 6 was designed
			The design process after ES6
		JavaScript versus ECMAScript
		Upgrading to ES6
		Goals for ES6
			Goal: Be a better language
			Goal: Improve interoperation
			Goal: Versioning
		An overview of ES6 features
		A brief history of ECMAScript
			The early years: ECMAScript 1–3
			ECMAScript 4 (abandoned in July 2008)
			ECMAScript Harmony
	FAQ: ECMAScript 6
		Isn’t ECMAScript 6 now called ECMAScript 2015?
		How much of ES6 is supported natively by current engines?
		How do I migrate my ECMAScript 5 code to ECMAScript 6?
		Does it still make sense to learn ECMAScript 5?
		Is ES6 bloated?
		Isn’t the ES6 specification very big?
		Does ES6 have array comprehensions?
		Is ES6 statically typed?
		Should I avoid classes?
		Does ES6 have traits or mixins?
		Why are there “fat” arrow functions (=>) in ES6, but no “thin” arrow functions (->)?
		Where can I find more ES6 resources?
	One JavaScript: avoiding versioning in ECMAScript 6
		Versioning
			Evolution without versioning
		Strict mode and ECMAScript 6
			Supporting sloppy (non-strict) mode
			let declarations in sloppy mode
			Block-level function declarations in sloppy mode
			Other keywords
			Implicit strict mode
			Things that can’t be fixed
		Conclusion
		Further reading
	First steps with ECMAScript 6
		Trying out ECMAScript 6
			The Babel REPL
			babel-node
		From var to let/const
		From IIFEs to blocks
		From concatenating strings to template literals
			String interpolation
			Multi-line strings
		From function expressions to arrow functions
		Handling multiple return values
			Multiple return values via arrays
			Multiple return values via objects
		From for to forEach() to for-of
		Handling parameter default values
		Handling named parameters
			Making the parameter optional
		From arguments to rest parameters
		From apply() to the spread operator (...)
			Math.max()
			Array.prototype.push()
		From concat() to the spread operator (...)
		From constructors to classes
			Base classes
			Derived classes
		From custom error constructors to subclasses of Error
		From function expressions in object literals to method definitions
		From objects to Maps
		From CommonJS modules to ES6 modules
			Multiple exports
			Single exports
		What to do next
	Deploying ECMAScript 6
		Using ECMAScript 6 today
			Using ECMAScript 6 natively
		Transpilation tools
			Choosing a transpiler
			Choosing a package manager
			Choosing a module system
		Other useful ES6 tools and libraries
		ES6 REPLs
		Are there ES6 features that can’t be transpiled to ES5?
			Better syntax for existing features
			New functionality in the standard library
			Completely new features
		Example transpilation setups
		Example setup: Client-side ES6 via webpack and Babel
			webpack features
			Installing webpack
			Using webpack and ES6 in a project
		Example setup: Dynamically transpiled ES6 on Node.js via Babel
			Running normal Node.js code via Babel
			Running Jasmine unit tests via Babel
		Example setup: Statically transpiled ES6 on Node.js via Babel and gulp
			Installation
			Source maps
			The gulp file
			Transpilation
			Running the transpiled code
II Data
	New number and Math features
		Overview
		New integer literals
			Use case for octal literals: Unix-style file permissions
			parseInt() and the new integer literals
		New static Number properties
			Previously global functions
			Number.EPSILON
			Number.isInteger(number)
			Safe Integers
		Math
			Various numerical functionality
			Using 0 instead of 1 with exponentiation and logarithm
			Logarithms to base 2 and 10
			Support for compiling to JavaScript
			Bitwise operations
			Trigonometric methods
		FAQ: numbers
			How can I use integers beyond JavaScript’s 53 bit range?
	New string features
		Overview
		Unicode code point escapes
		String interpolation, multi-line string literals and raw string literals
		Iterating over strings
			Iteration honors Unicode code points
			Counting code points
			Reversing strings with non-BMP code points
		Numeric values of code points
		Checking for containment and repeating strings
		All new string methods
	Symbols
		Overview
			Use case 1: unique property keys
			Use case 2: constants representing concepts
		A new primitive type
			Symbols as property keys
			Enumerating own property keys
		Using symbols to represent concepts
		Symbols as keys of properties
			Symbols as keys of internal properties
			Symbols as keys of meta-level properties
		Crossing realms with symbols
		Wrapper objects for symbols
			Property access via [ ]
		Converting symbols to other primitive types
			Pitfall: coercion to string
			Making sense of the coercion rules
			Explicit and implicit conversion in the spec
		JSON and symbols
			Generating JSON via JSON.stringify()
			Parsing JSON via JSON.parse()
		FAQ: symbols
			Can I use symbols to define private properties?
			Are symbols primitives or objects?
			Do we really need symbols? Aren’t strings enough?
			Are JavaScript’s symbols like Ruby’s symbols?
		The symbol API
			The function Symbol
			Well-known symbols
			Global symbol registry
	Template literals and tagged templates
		Overview
		Introduction
			Template literals
			Tagged templates
		Examples of using tagged templates
			Raw strings
			Escaping parts of a regular expression
			Tagged templates for more powerful regular expressions
			Query languages
			React JSX via tagged templates
			Text localization (L10N)
		Implementing tag functions
			Escaping in tagged templates: cooked vs. raw
			Example: implementing a tag function for HTML templating
			Example: quoting parts of regular expressions
		FAQ: template literals and tagged templates
			Where do template literals and tagged literals come from?
			What is the difference between macros and tagged templates?
			Can I load a template literal from an external source?
			Why are backticks the delimiters for template literals and tagged templates?
			Weren’t template literals once called template strings?
	Variables and scoping
		Overview
			let
			const
			Ways of declaring variables
		Block scoping via let and const
		const creates immutable variables
			Pitfall: const does not make the value immutable
			const in loop bodies
		The temporal dead zone
			typeof and the temporal dead zone
		let and const in loop heads
			for loop
			for-of loop and for-in loop
		Parameters
			Parameters versus local variables
			Parameter default values and the temporal dead zone
			Parameter default values don’t see the scope of the body
		The global object
		Function declarations and class declarations
		Coding style: var vs. let vs. const
	Destructuring
		Overview
		Background: Constructing data (object and Array literals) vs. extracting data (destructuring)
		Patterns
			Pick what you need
		How do patterns access the innards of values?
			Object patterns coerce values to objects
			Array patterns work with iterables
		If a part has no match
			Default values
		More object destructuring features
			Property value shorthands
			Computed property keys
		More Array destructuring features
			Elision
			Rest operator (...)
		You can assign to more than just variables
		Pitfalls of destructuring
			Don’t start a statement with a curly brace
			You can’t mix declaring and assigning to existing variables
		Examples of destructuring
			Destructuring return values
			Multiple return values
		The destructuring algorithm
			The algorithm
			Applying the algorithm
			Conclusion
	Parameter handling
		Overview
			Spread operator (...)
		Parameter handling as destructuring
		Parameter default values
			Why does undefined trigger default values?
			Referring to other parameters in default values
			Referring to “inner” variables in default values
		Rest parameters
			No more arguments!
		Simulating named parameters
			Named Parameters as Descriptions
			Optional Named Parameters
			Simulating Named Parameters in JavaScript
		Examples of destructuring in parameter handling
			Reminder: parentheses around single parameters of arrow functions
			forEach() and destructuring
			Transforming Maps
			Handling an Array returned via a Promise
		Coding style tips
			Optional parameters
			Required parameters
			Enforcing a maximum arity
		The spread operator (...)
			Spreading into function and method calls
			Spreading into constructors
			Spreading into Arrays
III Modularity
	Callable entities in ECMAScript 6
		Callable entities in ES6
			Ways of calling in ES6
			Traditional functions
			Generator functions
			Method definitions
			Generator method definitions
			Arrow functions
			Classes
		Thoughts on style
			Prefer arrow functions as callbacks
			Be careful with function declarations
			Prefer method definitions for methods
			Methods versus callbacks
			Avoid IIFEs in ES6
			Use classes
		Dispatched and direct method calls in ECMAScript 5 and 6
			Background: prototype chains
			Dispatched method calls
			Direct method calls
			Use cases for direct method calls
			Abbreviations for Object.prototype and Array.prototype
	Arrow functions
		Overview
		Traditional functions are bad non-method functions, due to this
			Solution 1: that = this
			Solution 2: specifying a value for this
			Solution 3: bind(this)
			ECMAScript 6 solution: arrow functions
		Arrow function syntax
		Lexical variables
			Sources of variable values: static versus dynamic
			Variables that are lexical in arrow functions
		Syntax pitfalls
			Arrow functions bind very loosely
			Immediately-invoked arrow functions
			Omitting parentheses around single parameters
			You can’t use statements as expression bodies
			Returning an object literal
		Arrow functions versus normal functions
	New OOP features besides classes
		Overview
			New object literal features
			New methods in Object
		New features of object literals
			Method definitions
			Property value shorthands
			Computed property keys
		New methods of Object
			Object.assign(target, source_1, source_2, ···)
			Object.getOwnPropertySymbols(obj)
			Object.is(value1, value2)
			Object.setPrototypeOf(obj, proto)
		Iterating over property keys in ES6
			Iteration order of property keys
		FAQ: object literals
			Can I use super in object literals?
	Classes
		Overview
		The essentials
			Base classes
			Inside the body of a class definition
			Subclassing
		The details of classes
			Various checks
			Attributes of properties
		The details of subclassing
			Prototype chains
			Allocating and initializing instances
			Why can’t you subclass built-in constructors in ES5?
			Referring to super-properties in methods
		Constructor calls explained via JavaScript code
			Internal variables and properties
			Environments
			Constructor calls
			Super-constructor calls
		The species pattern
			The standard species pattern
			The species pattern for Arrays
			The species pattern in static methods
			Overriding the default species in subclasses
		FAQ: classes
			Why can’t classes be function-called?
			How do instantiate a class, given an Array of arguments?
			How do I manage private data for classes?
			What is next for classes?
		The pros and cons of classes
			Complaint: ES6 classes obscure the true nature of JavaScript inheritance
			Complaint: Classes provide only single inheritance
			Complaint: Classes lock you in, due to mandatory new
		Further reading
	Modules
		Overview
			Multiple named exports
			Single default export
			Browsers: scripts versus modules
		Modules in JavaScript
			ECMAScript 5 module systems
			ECMAScript 6 modules
		The basics of ES6 modules
			Named exports (several per module)
			Default exports (one per module)
			Imports are hoisted
			Imports are read-only views on exports
			Support for cyclic dependencies
			Module files are normal JavaScript files
			Be careful with ES6 transpilers
		Importing and exporting in detail
			Importing styles
			Exporting styles: inline versus clause
			Re-exporting
			All exporting styles
			Having both named exports and a default export in a module
		The ECMAScript 6 module loader API
			Loaders
			Loader method: importing modules
			More loader methods
			Configuring module loading
		Using ES6 modules in browsers
			Browsers: asynchronous modules versus synchronous scripts
			Bundling
		Details: imports as views on exports
			In CommonJS, imports are copies of exported values
			In ES6, imports are live read-only views on exported values
			Implementing views
			Imports as views in the spec
		Design goals for ES6 modules
			Default exports are favored
			Static module structure
			Support for both synchronous and asynchronous loading
			Support for cyclic dependencies between modules
		FAQ: modules
			Can I use a variable to specify from which module I want to import?
			Can I import a module conditionally or on demand?
			Can I use destructuring in an import statement?
			Are named exports necessary? Why not default-export objects?
			Can I eval() modules?
		Benefits of ECMAScript 6 modules
		Further reading
IV Collections
	New Array features
		Overview
		New static Array methods
			Array.from(arrayLike, mapFunc?, thisArg?)
			Array.of(...items)
		New Array.prototype methods
			Iterating over Arrays
			Searching for Array elements
			Array.prototype.copyWithin()
			Array.prototype.fill()
	Maps and Sets
		Overview
			Maps
			Sets
			WeakMaps
		Map
			Basic operations
			Setting up a Map
			Keys
			Iterating
			Looping over entries
			Mapping and filtering Maps
			Combining Maps
			Map API
		WeakMap
			Using WeakMaps for private data
			WeakMap API
		Set
			Basic operations
			Setting up a Set
			Comparing Set elements
			Iterating
			Mapping and filtering
			Union, intersection, difference
			Set API
		WeakSet
			WeakSet API
		FAQ: Maps and Sets
			Why do Maps and Sets have the property size and not length?
			Why can’t I configure how Maps and Sets compare keys and values?
			Is there a way to specify a default value when getting something out of a Map?
			When should I use a Map, when an object?
	Typed Arrays
		Overview
		Introduction
			Element types
			Handling overflow and underflow
			Endianness
			Negative indices
		ArrayBuffers
			ArrayBuffer constructor
			Static ArrayBuffer methods
			ArrayBuffer.prototype properties
		Typed Arrays
			Typed Arrays versus normal Arrays
			Typed Arrays are iterable
			Converting Typed Arrays to and from normal Arrays
			The Species pattern for Typed Arrays
			The inheritance hierarchy of Typed Arrays
			Static TypedArray methods
			TypedArray.prototype properties
			«ElementType»Array constructor
			Static «ElementType»Array properties
			«ElementType»Array.prototype properties
			Concatenating Typed Arrays
		DataViews
			DataView constructor
			DataView.prototype properties
		Browser APIs that support Typed Arrays
			File API
			XMLHttpRequest
			Fetch API
			Canvas
			WebSockets
			Other APIs
		Extended example: JPEG SOF0 decoder
			The JPEG file format
			The JavaScript code
		Availability
	Iterables and iterators
		Overview
		Iterability
		Iterable data sources
			Arrays
			Strings
			Maps
			Sets
			arguments
			DOM data structures
			Iterable computed data
			Plain objects are not iterable
		Iterating language constructs
			Destructuring via an Array pattern
			The for-of loop
			Array.from()
			The spread operator (...)
			Maps and Sets
			Promises
			yield*
		Implementing iterables
			Iterators that are iterable
			Optional iterator methods: return() and throw()
		More examples of iterables
			Tool functions that return iterables
			Combinators for iterables
			Infinite iterables
		FAQ: iterables and iterators
			Isn’t the iteration protocol slow?
			Can I reuse the same object several times?
			Why doesn’t ECMAScript 6 have iterable combinators?
			Aren’t iterables difficult to implement?
		The ECMAScript 6 iteration protocol in depth
			Iteration
			Closing iterators
			Checklist
	Generators
		Overview
			Implementing iterables via generators
			Blocking on asynchronous function calls
		What are generators?
			Ways of creating generators
			Roles played by generators
		Generators as iterators (data production)
			Ways of iterating over a generator
			Returning from a generator
			Example: iterating over properties
			You can only yield in generators
			Recursion via yield* (for output)
		Generators as observers (data consumption)
			Sending values via next()
			yield binds loosely
			return() and throw()
			return() terminates the generator
			throw() signals an error
			Example: processing asynchronously pushed data
			yield*: the full story
		Generators as coroutines (cooperative multitasking)
			The full generator interface
			Cooperative multitasking
			The limitations of cooperative multitasking via generators
		Examples of generators
			Implementing iterables via generators
			Generators for lazy evaluation
			Cooperative multi-tasking via generators
		Inheritance within the iteration API (including generators)
			IteratorPrototype
			The value of this in generators
		Style consideration: whitespace before and after the asterisk
			Generator function declarations and expressions
			Generator method definitions
			Formatting recursive yield
			Documenting generator functions and methods
		Conclusion
		Further reading
V Standard library
	New regular expression features
		Overview
		New flag /y (sticky)
			RegExp.prototype.exec(str)
			RegExp.prototype.test(str)
			String.prototype.search(regex)
			String.prototype.match(regex)
			String.prototype.split(separator, limit)
			String.prototype.replace(search, replacement)
			Example: using sticky matching for tokenizing
			Example: manually implementing sticky matching
		New flag /u (unicode)
			Consequence: lone surrogates in the regular expression only match lone surrogates
			Consequence: you can put code points in character classes
			Consequence: the dot operator (.) matches code points, not code units
			Consequence: quantifiers apply to code points, not code units
		New data property flags
		RegExp() can be used as a copy constructor
		String methods using regular expressions delegate to regular expression methods
	Asynchronous programming (background)
		The JavaScript call stack
		The browser event loop
			Timers
			Displaying DOM changes
			Run-to-completion semantics
			Blocking the event loop
			Avoiding blocking
		Receiving results asynchronously
			Asynchronous results via events
			Asynchronous results via callbacks
			Continuation-passing style
			Composing code in CPS
			Pros and cons of callbacks
		Looking ahead
		Further reading
	Promises for asynchronous programming
		Overview
			Handling Arrays of Promises
		Promises
		A first example
		Creating and using Promises
			Producing a Promise
			Consuming a Promise
			Only handling fulfillments or rejections
		Examples
			Example: promisifying fs.readFile()
			Example: promisifying XMLHttpRequest
			Example: delaying an activity
			Example: timing out a Promise
		Chaining Promises
			Resolving Q with normal values
			Resolving Q with thenables
			Resolving Q from onRejected
			Rejecting Q by throwing exceptions
			Exceptions in executors
			Chaining errors
		Composition
			map() via Promise.all()
			Timing out via Promise.race()
		Promises are always async
		Cheat sheet: the ECMAScript 6 Promise API
			Glossary: Promises
			Promise constructor
			Static Promise methods
			Promise.prototype methods
		Pros and cons of Promises
			The pros
			The cons
		Promises and generators
		Debugging Promises
		The internals of Promises
			A stand-alone Promise
			Chaining
			Flattening
			Promise states in more detail
			Exceptions
			Revealing constructor pattern
		Two useful additional Promise methods
			done()
			finally()
		ES6-compatible Promise libraries
		Interfacing with legacy asynchronous code
			Interfacing with Node.js
			Interfacing with jQuery
		Further reading
VI Miscellaneous
	Unicode in ES6
		Unicode is better supported in ES6
		Escape sequences in ES6
			Where can escape sequences be used?
			Escape sequences in the ES6 spec
	Tail call optimization
		What is tail call optimization?
			Normal execution
			Tail call optimization
		Checking whether a function call is in a tail position
			Tail calls in expressions
			Tail calls in statements
			Tail call optimization can only be made in strict mode
			Pitfall: solo function calls are never in tail position
		Tail-recursive functions
			Tail-recursive loops
	Meta programming with proxies
		Overview
		Programming versus meta programming
			Kinds of meta programming
		A first look at proxies
			Function-specific traps
			Revocable proxies
			Proxies as prototypes
			Forwarding intercepted operations
		Use cases for proxies
			Implementing the DOM in JavaScript
			Accessing a restful web service
			Tracing property accesses
			Warning about unknown properties
			Negative Array indices
			Data binding
			Revocable references
			Other use cases
		The design of the proxy API
			Stratification: keeping base level and meta level separate
			Virtual objects versus wrappers
			Transparent virtualization and handler encapsulation
			The meta object protocol and proxy traps
			Enforcing invariants for proxies
		Reference: the proxy API
			Creating proxies
			Handler methods
			Invariants of handler methods
			Operations that affect the prototype chain
			Reflect
		Conclusion
		Further reading
	Coding style tips for ECMAScript 6
                        
Document Text Contents
Page 2

Exploring ES6
Upgrade to the next version of JavaScript

Axel Rauschmayer

This book is for sale at http://leanpub.com/exploring-es6

This version was published on 2015-10-03

This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing
process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and
many iterations to get reader feedback, pivot until you have the right book and build traction once
you do.

©2015 Axel Rauschmayer (cover by Fran Caye)

http://leanpub.com/exploring-es6
http://leanpub.com

Page 278

Modules 251

17.3.2.1.1 Why anonymous function declarations and not anonymous function expressions?
When you look at the previous two lines of code, you’d expect the operands of export default
to be expressions. They are only declarations for reasons of consistency: operands can be named
declarations, interpreting their anonymous versions as expressions would be confusing (even more
so than introducing new kinds of declarations).

If you want the operands to be interpreted as expressions, you need to use parentheses:

export default (function () {});
export default (class {});

17.3.2.2 Default export style 2: directly default-exporting values

The values are produced via expressions:

export default 'abc';
export default foo();
export default /^xyz$/;
export default { no: false, yes: true };
export default 5 * 7;

Each of these default exports has the following structure.

export default «expression»;

That is equivalent to:

const __default__ = «expression»;
export { __default__ as default }; // (A)

The statement in line A is an export clause (which is explained in a later section).

17.3.2.2.1 Why two default export styles? The second default export style was introduced
because variable declarations can’t be meaningfully turned into default exports if they declare
multiple variables:

export default const foo = 1, bar = 2, baz = 3; // not legal JavaScript!

Which one of the three variables foo, bar and baz would be the default export?

17.3.3 Imports are hoisted

Module imports are hoisted (internally moved to the beginning of the current scope). Therefore, it
doesn’t matter where you mention them in a module and the following code works without any
problems:

Page 554

29. Coding style tips for ECMAScript 6
This chapter lists a few ideas related to ES6 coding style:

• var versus let versus const (details are explained in the chapter on variables)
– Use const only for things that are completely immutable: mutable objects aren’t, but
primitives and (completely) frozen objects are.

– Use let for all other things.
– Avoid var.

• Arrow functions work best if they fit into a single line:

readFilePromisified(filename)
.then(text => console.log(text))

For multi-line functions, I often prefer traditional functions:

readFilePromisified(filename)
.then(function (text) {

let obj = JSON.parse(text);
console.log(JSON.stringify(obj, null, 4));

});

Single-line functions tend to be throw-away. If a function isn’t then a traditional function has
the advantage that you can name it, which is useful for documentation and debugging.

• Modules: don’t mix default exports and named exports. Your module should either specialize
on a single thing or export multiple, named, things. Details are explained in the chapter on
modules.

• Format generators as follows:

// Generator function declaration
function* genFunc() { ··· }

// Generator function expression
const genFunc = function* () { ··· };

// Generator method definition in an object literal
let obj = {

* generatorMethod() {
···

527

Page 555

Coding style tips for ECMAScript 6 528

}
};

// Generator method definition in a class definition
class MyClass {

* generatorMethod() {
···

}
}

Details are explained in the chapter on generators.
• The chapter on parameter handling has style tips for function signatures:

// Mark optional parameters via the parameter default value `undefined`
function foo(optional = undefined) { ··· }

// Mark required parameters via a function that throws an exception
function foo(required = throwException()) { ··· }

// Enforcing a maximum arity (variant 1 of 2)
function f(x, y, ...empty) { // max arity: 2

if (empty.length > 0) {
throw new Error();

}
}
// Enforcing a maximum arity (variant 2 of 2)
function f(x, y) { // max arity: 2

if (arguments.length > 2) {
throw new Error();

}
}

• The whole chapter on callable entities (traditional functions, arrow functions, classes, etc.) is
about style tips: when to use which one, etc.

• Use classes: They are not perfect, but I still recommend to use them (where appropriate!),
because they have several objective benefits. Details are explained in the chapter on classes.

Additionally, the ES5 coding style tips¹ in “Speaking JavaScript” are still relevant for ES6.

¹http://speakingjs.com/es5/ch26.html

http://speakingjs.com/es5/ch26.html
http://speakingjs.com/es5/ch26.html

Similer Documents