You Don T Know JS ES6 Beyond Kyle Simpson Download
You Don T Know JS ES6 Beyond Kyle Simpson Download
https://ebookfinal.com/download/you-don-t-know-js-es6-beyond-kyle-
simpson/
https://ebookfinal.com/download/debt-cures-they-don-t-want-you-to-
know-about-perseus/
https://ebookfinal.com/download/what-you-don-t-know-about-schools-1st-
edition-shirley-r-steinberg/
https://ebookfinal.com/download/climate-of-extremes-global-warming-
science-they-don-t-want-you-to-know-patrick-j-michaels/
https://ebookfinal.com/download/101-facts-you-didn-t-know-about-space-
mark-thompson/
Functional Light JavaScript Balanced Pragmatic FP in
JavaScript 1st Edition Kyle Simpson
https://ebookfinal.com/download/functional-light-javascript-balanced-
pragmatic-fp-in-javascript-1st-edition-kyle-simpson/
https://ebookfinal.com/download/finish-your-dissertation-don-t-let-it-
finish-you-1st-edition-joanne-broder-sumerson/
https://ebookfinal.com/download/don-t-suck-don-t-die-giving-up-vic-
chesnutt-first-edition-chesnutt/
Don t Spend Your Raise And 59 Other Money Rules You Can t
Afford to Break 1st Edition Dara Duguay
https://ebookfinal.com/download/don-t-spend-your-raise-and-59-other-
money-rules-you-can-t-afford-to-break-1st-edition-dara-duguay/
https://ebookfinal.com/download/you-don-t-look-sick-living-well-with-
invisible-chronic-illness-1st-edition-joy-h-selak/
You Don t Know JS ES6 Beyond Kyle Simpson Digital
Instant Download
Author(s): Kyle Simpson
ISBN(s): 9781491904244, 1491904240
Edition: Early Release
File Details: PDF, 5.90 MB
Year: 2015
Language: english
You Don’t Know JS: ES6 and
Beyond
Kyle Simpson
You Don’t Know JS: ES6 & Beyond
by Kyle Simpson
Copyright © FILL IN YEAR Getify Solutions, Inc.. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc. , 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles ( http://safaribooksonline.com ). For more information, contact our corporate/
institutional sales department: 800-998-9938 or [email protected] .
Editors: Simon St. Laurent and Brian MacDonald Cover Designer: Karen Montgomery
Interior Designer: David Futato Illustrator: Rebecca Demarest
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. You Don’t Know JS: ES6 & Beyond, the
cover image, and related trade dress are trademarks of O’Reilly Media, Inc.
While the publisher and the author(s) have used good faith efforts to ensure that the information and
instructions contained in this work are accurate, the publisher and the author(s) disclaim all responsibil‐
ity for errors or omissions, including without limitation responsibility for damages resulting from the use
of or reliance on this work. Use of the information and instructions contained in this work is at your own
risk. If any code samples or other technology this work contains or describes is subject to open source
licenses or the intellectual property rights of others, it is your responsibility to ensure that your use
thereof complies with such licenses and/or rights.
978-1-491-90424-4
[FILL IN]
Table of Contents
Foreword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
2. Syntax. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Block-Scoped Declarations 7
let Declarations 8
const Declarations 12
Spread / Rest 13
Default Parameter Values 15
Default Value Expressions 17
Destructuring 19
Object Property Assignment Pattern 20
Not Just Declarations 22
Too Many, Too Few, Just Enough 24
Default Value Assignment 26
Nested Destructuring 26
Destructuring Parameters 27
Object Literal Extensions 32
Concise Properties 32
Concise Methods 33
Computed Property Names 37
Setting [[Prototype]] 38
Object super 40
iii
Template Literals 40
Interpolated Expressions 42
Tagged Template Literals 43
Arrow Functions 46
Not Just Shorter Syntax, But this 49
for..of Loops 51
Regular Expressions 53
Unicode Flag 54
Sticky Flag 55
Regular Expression flags 60
Number Literal Extensions 61
Unicode 62
Unicode-Aware String Operations 63
Character Positioning 65
Unicode Identifier Names 67
Symbols 67
Symbol Registry 70
Symbols as Object Properties 71
Review 72
3. Organization. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Iterators 73
Interfaces 74
next() Iteration 75
Optional: return(..) and throw(..) 76
Iterator Loop 77
Custom Iterators 78
Iterator Consumption 82
Generators 83
Syntax 83
Iterator Control 89
Early Completion 92
Error Handling 94
Transpiling a Generator 96
Generator Uses 98
Modules 98
The Old Way 99
Moving Forward 99
The New Way 102
Circular Module Dependency 111
Module Loading 113
Classes 115
iv | Table of Contents
class 115
extends and super 117
new.target 122
static 122
Review 124
5. Collections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
Typed Arrays 139
Endianness 140
Multiple Views 141
Typed Array Constructors 142
Maps 143
Map Values 145
Map Keys 146
WeakMaps 146
Sets 147
Set Iterators 148
WeakSets 149
Review 149
Table of Contents | v
Object.setPrototypeOf(..) Static Function 162
Object.assign(..) Static Function 163
Math 164
Number 165
Static Properties 165
Number.isNaN(..) Static Function 166
Number.isFinite(..) Static Function 166
Integer-related Static Functions 167
String 168
Unicode Functions 168
String.raw(..) Static Function 169
repeat(..) Prototype Function 169
String Inspection Functions 169
Review 170
vi | Table of Contents
8. Beyond ES6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
`async function`s 208
Caveats 210
Object.observe(..) 211
Custom Change Events 213
Ending Observation 214
Exponentiation Operator 214
Objects Properties and ... 215
Array#includes(..) 215
SIMD 216
Review 217
ix
CHAPTER 1
ES? Now & Future
Before reading this book, I assume you have a solid working proficiency over Java‐
Script up to the most recent standard (at the time of this writing), which is commonly
called ES5 (technically ES 5.1). Here, we plan to talk squarely about the upcoming
ES6, as well as cast our vision beyond to understand how JS will evolve moving for‐
ward.
If you are still looking for confidence with JavaScript, I highly recommend you read
the other titles in this series first:
• “Up & Going”: Are you new to programming and JS? This is the roadmap you
need to consult as you start your learning journey.
• “Scope & Closures”: Did you know that JS lexical scope is based on compiler (not
interpreter!) semantics? Can you explain how closures are a direct result of lexi‐
cal scope and functions as values?
• “this & Object Prototypes”: Can you recite the four simple rules for how this is
bound? Have you been muddling through fake “classes” in JS instead of adopting
the simpler “behavior delegation” design pattern? Ever heard of OLOO?
• “Types & Grammar”: Do you know the built-in types in JS, and more importantly
do you know how to properly and safely use coercion between types? How com‐
fortable are you with the nuances of JS grammar/syntax?
• “Async & Performance”: Are you still using callbacks to manage your asynchrony?
Can you explain what a promise is and why/how it solves “callback hell”, and how
generators improve the legibility of async code? What exactly constitutes mature
optimization of JS programs and individual operations?
1
If you’ve read all those titles and you feel pretty comfortable with those topics, it’s
time we dive into the evolution of JS to explore all the changes coming not only soon
but farther over the horizon.
ES6 is not just a modest set of new APIs added to the langauge, as ES5 was. It incor‐
porates a whole slew of new syntactic forms, some of which may take quite a bit of
getting used to. There’s also a variety of new organization forms and new API helpers
for various data types.
ES6 is a radical jump forward for the language. Even if you think you do know JS in
ES5, ES6 is full of new stuff you don’t know yet, so get ready! This book will explore
all the major themes of ES6 that you need to get up to speed on, and even gaze at
future features you should be aware of that are coming down the track.
Versioning
The JavaScript standard is referred to officially as “ECMAScript” (abbreviated “ES”),
and up until just recently has been versioned entirely by ordinal number (i.e., “5” for
“5th edition”).
The earliest versions ES1 and ES2 were not widely known or implemented, but ES3
was the first widespread baseline for JavaScript. ES3 constitutes the JavaScript stan‐
dard for browsers like IE6-8 and older Android 2.x mobile browsers. For politicial
reasons beyond what we’ll cover here, the ill-fated ES4 never came about.
In 2009, ES5 was officially finalized (later ES5.1 in 2011), and settled as the wide‐
spread standard for JS for the modern revolution and explosion of browsers, such as
Firefox, Chrome, Opera, Safari, and many others.
Leading up to the expected next version of JS (slipped from 2013 to 2014 and then
2015), the obvious and common label in discourse has been ES6.
However, late into the ES6 specification timeline, suggestions have surfaced that ver‐
sioning may in the future switch to being year-based, such ES2016 (aka ES7) to refer
to whatever version of the specification is finalized before the end of 2016. Some disa‐
gree, but ES6 will likely maintain its dominant mindshare over the late change substi‐
tute ES2015. However ES2016 may in fact signal the new versioning scheme.
It has also been observed that the pace of JS evolution is much faster even than single-
year versioning. As soon as an idea begins to progress through standards discussions,
Transpiling
Made even worse by the rapid evolution of features, a problem arises for JS develop‐
ers who at once may both strongly desire to use new features while at the same time
being slapped with the reality that their sites/apps may need to support older brows‐
ers without such support.
The way ES5 appears to have played out in the broader industry, the typical mindset
was that code bases waited to adopt ES5 until most if not all pre-ES5 environments
had fallen out of their support spectrum. As a result, many are just recently (at the
time of this writing) starting to adopt things like strict mode which landed in ES5
five or more years ago.
This is widely considered to be a harmful approach for the future of the JS ecosystem,
to wait around and trail the specification by so many years. All those responsible for
evolving the language desire for developers to begin basing their code on the new fea‐
tures and patterns as soon as they stabilize in specification form and browsers have a
chance to implement them.
So how do we resolve this seeming contradiction? The answer is tooling, specifically a
technique called transpiling (transformation
compiling). Roughly, the idea is to use a special tool to transform your ES6 code into
equivalent (or close!) matches that work in ES5 environments.
For example, consider shorthand property definitions (see “Object Literal Exten‐
sions” in Chapter 2). Here’s the ES6 form:
var foo = [1,2,3];
var obj = {
foo // means `foo: foo`
};
obj.foo; // [1,2,3]
Transpiling | 3
But (roughly) here’s how that transpiles:
var foo = [1,2,3];
var obj = {
foo: foo
};
obj.foo; // [1,2,3]
This is a minor but pleasant transformation, that lets us shorten the foo: foo in an
object literal declaration to just foo, if the names are the same.
Transpilers perform these transformations for you, usually in a build workflow step
similar to how/when you perform linting, minification, etc.
Shims/Polyfills
Not all new ES6 features need a transpiler. Polyfills (aka shims) are a pattern for
defining equivalent behavior from a newer environment into an older environment,
when possible. Syntax cannot be polyfilled, but APIs often can be.
For example, Object.is(..) is a new utility for checking strict equality of two values
but without the nuanced exceptions that === has for NaN and -0 values. The polyfill
for Object.is(..) is pretty easy:
if (!Object.is) {
Object.is = function(v1, v2) {
// test for `-0`
if (v1 === 0 && v2 === 0) {
return 1 / v1 === 1 / v2;
}
// test for `NaN`
if (v1 !== v1) {
return v2 !== v2;
}
// everything else
return v1 === v2;
};
}
Review
ES6 (some may try to call it ES2015) is just landing as of the time of this writing, and
it has lots of new stuff you need to learn!
But it’s even more important to shift your mindset to align with the new way that
JavaScript is going to evolve. It’s not just waiting around for years for some official
document to get a vote of approval, as many have done in the past.
Now, JavaScript features land in browsers as they become ready, and it’s up to you
whether you’ll get on train early or whether you’ll be playing costly catch-up games
years from now.
Whatever labels that future JavaScript adopts, it’s going to move a lot quicker than it
ever has before. Transpilers and shims/polyfills are important tools to keep you on
the forefront of where the language is headed.
If there’s any narrative important to understand about the new reality for JavaScript,
it’s that all JS developers are strongly implored to move from the trailing edge of the
curve to the leading edge. And learning ES6 is where that all starts!
Review | 5
CHAPTER 2
Syntax
If you’ve been writing JS for any length of time, odds are the syntax is pretty familiar
to you. There are certainly many quirks, but overall it’s a fairly reasonable and
straightforward syntax that draws many similarities from other languages.
However, ES6 adds quite a few new syntactic forms which are going to take some get‐
ting used to. In this chapter we’ll tour through them to find out what’s in store.
At the time of this writing, some of the features in this book have
been implemented in various browsers (Firefox, Chrome, etc.), but
many others have not, or the features are only partially imple‐
mented. Your experience may be mixed trying these examples
directly. If so, try them out with transpilers, as most of these fea‐
tures are covered by those tools. ES6Fiddle (http://
www.es6fiddle.net/) is a great, easy-to-use playground for trying
out ES6, as is the online REPL for the Babel transpiler (http://
babeljs.io/repl/).
Block-Scoped Declarations
You’re probably aware that the fundamental unit of variable scoping in JavaScript has
always been the function. If you needed to create a block of scope, the most preva‐
lent way to do so was the IIFE (immediately invoked function expression), such as:
var a = 2;
(function IIFE(){
var a = 3;
console.log( a ); // 3
})();
7
console.log( a ); // 2
let Declarations
However, we can now create declarations which are bound to any block, called
(unsurprisingly) block scoping. This means all we need is a pair of { .. } to create a
scope. Instead of using var, which always declares variables attached to the enclosing
function (or global, if top level) scope, use let:
var a = 2;
{
let a = 3;
console.log( a ); // 3
}
console.log( a ); // 2
It’s not very common or idiomatic thus far in JS to use a standalone { .. } block as
shown there, but it’s always been totally valid. And developers from other languages
that have block scoping will readily recognize that pattern.
I’m going to suggest that I think this is the far better way to create block-scoped vari‐
ables, with a dedicated { .. } block. Moreover, I will also strongly suggest you
should always put the let declaration(s) at the very top of that block. If you have
more than one to declare, I’d recommend using just one let.
Stylistically, I even prefer to put the let on the same line as the opening {, to make it
clearer that this block is only for the purpose of declaring the scope for those vari‐
ables.
{ let a = 2, b, c;
// ..
}
Now, that’s going to look strange and it’s not likely going to match the recommenda‐
tions by most other ES6 literature. But I have reasons for my madness.
There’s another proposed form of the let declaration called the let-block, which
looks like:
let (a = 2, b, c) {
// ..
}
That form is what I’d called explicit block scoping, whereas the let .. declaration
form that mirrors var is more implicit, since it kind of hijacks whatever { .. } pair
it’s found in. Generally developers find explicit mechanisms a bit more preferable
than implicit mechanisms, and I claim this is one of those cases.
8 | Chapter 2: Syntax
If you compare the previous two snippet forms, they’re very similar, and in my opin‐
ion both qualify stylistically as explicit block scoping. Unfortunately, the let (..)
{ .. } form, the most explicit of the options, was not adopted in ES6. That may be
revisited post-ES6, but for now the former option is our best bet, I think.
To reinforce the implicit nature of let .. declarations, consider these usages:
let a = 2;
if (a > 1) {
let b = a * 3;
console.log( b ); // 6
let c = a + b;
console.log( c ); // 8
}
Quick quiz without looking back at that snippet: which variable(s) exist only inside
the if statement, and which variable(s) existing only inside the for loop?
The answers: the if statement contains b and c block-scoped variables, and the for
loop contains i and j block-scoped variables.
Did you have to think about it for a moment? Does it surprise you that i isn’t added
to the enclosing if statement scope? That mental pause and questioning — I call it a
“mental tax" — comes from the fact that this let mechanism is not only new to us,
but it’s also implicit.
There’s also hazard in the let c = .. declaration appearing so far down in the scope.
Unlike traditional var-declared variables, which are attached to the entire enclosing
function scope regardless of where they appear, let declarations attach to the block
scope but are not initialized until they appear in the block.
Accessing a let-declared variable earlier than its let .. declaration/initialization
causes an error, whereas with var declarations the ordering doesn’t matter (except
stylistically).
Consider:
{
console.log( a ); // undefined
console.log( b ); // ReferenceError!
var a;
Block-Scoped Declarations | 9
Another Random Scribd Document
with Unrelated Content
The text on this page is estimated to be only 29.29%
accurate
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookfinal.com