You Don’t Know JS: Types & Grammar
by Kyle Simpson
Copyright © 2015 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 ([Link] For
more information, contact our corporate/institutional sales department:
800-998-9938 or corporate@[Link].
Editors: Simon St. Laurent and Brian Proofreader: Charles Roumeliotis
MacDonald Interior Designer: David Futato
Production Editor: Kristen Brown Cover Designer: Ellie Volckhausen
Copyeditor: Christina Edwards
February 2015: First Edition
Revision History for the First Edition
2015-01-23: First Release
See [Link] for release details.
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. You Don’t Know
JS: Types & Grammar, the cover image, and related trade dress are trademarks of
O’Reilly Media, Inc.
While the publisher and the author 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 responsibility 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 sub‐
ject 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-90419-0
[LSI]
[Link]
Table of Contents
Foreword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii
1. Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
A Type by Any Other Name… 2
Built-in Types 3
Values as Types 5
Review 10
2. Values. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Arrays 11
Strings 14
Numbers 16
Special Values 24
Value Versus Reference 33
Review 37
3. Natives. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Internal [[Class]] 41
Boxing Wrappers 42
Unboxing 43
Natives as Constructors 44
Review 55
4. Coercion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Converting Values 57
iii
[Link]
Abstract Value Operations 59
Explicit Coercion 71
Implicit Coercion 85
Loose Equals Versus Strict Equals 99
Abstract Relational Comparison 116
Review 119
5. Grammar. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Statements & Expressions 121
Operator Precedence 137
Automatic Semicolons 146
Errors 149
Function Arguments 151
try..finally 154
switch 157
Review 160
A. Mixed Environment JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
B. Acknowledgments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
iv | Table of Contents
[Link]
Foreword
It was once said, “JavaScript is the only language developers don’t
learn to use before using it.”
I laugh each time I hear that quote because it was true for me and I
suspect it was for many other developers. JavaScript, and maybe
even CSS and HTML, were not among the core computer science
languages taught at college in the Internet’s early days, so personal
development was very much based on the budding developer’s
search and “view source” abilities to piece together these basic web
languages.
I still remember my first high school website project. The task was
to create any type of web store, and me being a James Bond fan, I
decided to create a Goldeneye store. It had everything: the Golden‐
eye MIDI theme song playing in the background, JavaScript-
powered crosshairs following the mouse around the screen, and a
gunshot sound that played upon every click. Q would have been
proud of this masterpiece of a website.
I tell that story because I did back then what many developers are
doing today: I copied-and-pasted chunks of JavaScript code into my
project without having a clue about what’s actually happening. The
widespread use of JavaScript toolkits like jQuery have, in their own
small way, perpetuated this pattern of not learning of core Java‐
Script.
I’m not disparaging JavaScript toolkit use; after all, I’m a member of
the MooTools JavaScript team! But the reason JavaScript toolkits are
as powerful as they are is because their developers know the funda‐
mentals, and their “gotchas,” and apply them magnificently. As use‐
ful as these toolkits are, it’s still incredibly important to know the
[Link]
basics of the language, and with books like Kyle Simpson’s You Don’t
Know JS series, there’s no excuse not to learn them.
Types & Grammar, the third installment of the series, is an excellent
look at the core JavaScript fundamentals that copy-and-paste and
JavaScript toolkits don’t and could never teach you. Coercion and its
pitfalls, natives as constructors, and the whole gamut of JavaScript
basics are thoroughly explained with focused code examples. Like
the other books in this series, Kyle cuts straight to the point, with no
fluff and wordsmithing—exactly the type of tech book I love.
Enjoy Types & Grammar and don’t let it get too far away from your
desk!
—David Walsh ([Link]
Senior Web Developer at Mozilla
vi | Foreword
[Link]
Preface
I’m sure you noticed, but “JS” in the series title is not an abbrevia‐
tion for words used to curse about JavaScript, though cursing at the
language’s quirks is something we can probably all identify with!
From the earliest days of the Web, JavaScript has been a founda‐
tional technology that drives interactive experience around the con‐
tent we consume. While flickering mouse trails and annoying pop-
up prompts may be where JavaScript started, nearly two decades
later, the technology and capability of JavaScript has grown many
orders of magnitude, and few doubt its importance at the heart of
the world’s most widely available software platform: the Web.
But as a language, it has perpetually been a target for a great deal of
criticism, owing partly to its heritage but even more to its design
philosophy. Even the name evokes, as Brendan Eich once put it,
“dumb kid brother” status next to its more mature older brother
Java. But the name is merely an accident of politics and marketing.
The two languages are vastly different in many important ways.
“JavaScript” is as related to “Java” as “Carnival” is to “Car.”
Because JavaScript borrows concepts and syntax idioms from sev‐
eral languages, including proud C-style procedural roots as well as
subtle, less obvious Scheme/Lisp-style functional roots, it is exceed‐
ingly approachable to a broad audience of developers, even those
with little to no programming experience. The “Hello World” of
JavaScript is so simple that the language is inviting and easy to get
comfortable with in early exposure.
While JavaScript is perhaps one of the easiest languages to get up
and running with, its eccentricities make solid mastery of the lan‐
guage a vastly less common occurrence than in many other lan‐
vii
[Link]
guages. Where it takes a pretty in-depth knowledge of a language
like C or C++ to write a full-scale program, full-scale production
JavaScript can, and often does, barely scratch the surface of what the
language can do.
Sophisticated concepts that are deeply rooted into the language tend
instead to surface themselves in seemingly simplistic ways, such as
passing around functions as callbacks, which encourages the Java‐
Script developer to just use the language as-is and not worry too
much about what’s going on under the hood.
It is simultaneously a simple, easy-to-use language that has broad
appeal, and a complex and nuanced collection of language mechan‐
ics that without careful study will elude true understanding even for
the most seasoned of JavaScript developers.
Therein lies the paradox of JavaScript, the Achilles’ heel of the lan‐
guage, the challenge we are presently addressing. Because JavaScript
can be used without understanding, the understanding of the lan‐
guage is often never attained.
Mission
If at every point that you encounter a surprise or frustration in Java‐
Script, your response is to add it to the blacklist (as some are accus‐
tomed to doing), you soon will be relegated to a hollow shell of the
richness of JavaScript.
While this subset has been famously dubbed “The Good Parts,” I
would implore you, dear reader, to instead consider it the “The Easy
Parts,” “The Safe Parts,” or even “The Incomplete Parts.”
This You Don’t Know JS series offers a contrary challenge: learn and
deeply understand all of JavaScript, even and especially “The Tough
Parts.”
Here, we address head-on the tendency of JS developers to learn
“just enough” to get by, without ever forcing themselves to learn
exactly how and why the language behaves the way it does. Further‐
more, we eschew the common advice to retreat when the road gets
rough.
I am not content, nor should you be, at stopping once something
just works and not really knowing why. I gently challenge you to
journey down that bumpy “road less traveled” and embrace all that
viii | Preface
[Link]
JavaScript is and can do. With that knowledge, no technique, no
framework, no popular buzzword acronym of the week will be
beyond your understanding.
These books each take on specific core parts of the language that are
most commonly misunderstood or under-understood, and dive very
deep and exhaustively into them. You should come away from read‐
ing with a firm confidence in your understanding, not just of the
theoretical, but the practical “what you need to know” bits.
The JavaScript you know right now is probably parts handed down
to you by others who’ve been burned by incomplete understanding.
That JavaScript is but a shadow of the true language. You don’t really
know JavaScript, yet, but if you dig into this series, you will. Read
on, my friends. JavaScript awaits you.
Review
JavaScript is awesome. It’s easy to learn partially, and much harder to
learn completely (or even sufficiently). When developers encounter
confusion, they usually blame the language instead of their lack of
understanding. These books aim to fix that, inspiring a strong
appreciation for the language you can now, and should, deeply know.
Many of the examples in this book assume
modern (and future-reaching) JavaScript engine
environments, such as ES6. Some code may not
work as described if run in older (pre-ES6)
engines.
Conventions Used in This Book
The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and file
extensions.
Constant width
Used for program listings, as well as within paragraphs to refer
to program elements such as variable or function names, data‐
bases, data types, environment variables, statements, and key‐
words.
Preface | ix
[Link]
Constant width bold
Shows commands or other text that should be typed literally by
the user.
Constant width italic
Shows text that should be replaced with user-supplied values or
by values determined by context.
This element signifies a tip or suggestion.
This element signifies a general note.
This element indicates a warning or caution.
Using Code Examples
Supplemental material (code examples, exercises, etc.) is available
for download at [Link]
This book is here to help you get your job done. In general, if exam‐
ple code is offered with this book, you may use it in your programs
and documentation. You do not need to contact us for permission
unless you’re reproducing a significant portion of the code. For
example, writing a program that uses several chunks of code from
this book does not require permission. Selling or distributing a CD-
ROM of examples from O’Reilly books does require permission.
Answering a question by citing this book and quoting example code
does not require permission. Incorporating a significant amount of
example code from this book into your product’s documentation
does require permission.
x | Preface
[Link]
We appreciate, but do not require, attribution. An attribution usu‐
ally includes the title, author, publisher, and ISBN. For example:
“You Don’t Know JavaScript: Types & Grammar by Kyle Simpson
(O’Reilly). Copyright 2015 Getify Solutions, Inc.,
978-1-491-90419-0.”
If you feel your use of code examples falls outside fair use or the per‐
mission given above, feel free to contact us at permis‐
sions@[Link].
Safari® Books Online
Safari Books Online is an on-demand digital
library that delivers expert content in both
book and video form from the world’s lead‐
ing authors in technology and business.
Technology professionals, software developers, web designers, and
business and creative professionals use Safari Books Online as their
primary resource for research, problem solving, learning, and certif‐
ication training.
Safari Books Online offers a range of plans and pricing for enter‐
prise, government, education, and individuals.
Members have access to thousands of books, training videos, and
prepublication manuscripts in one fully searchable database from
publishers like O’Reilly Media, Prentice Hall Professional, Addison-
Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press,
Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan
Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress,
Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Tech‐
nology, and hundreds more. For more information about Safari
Books Online, please visit us online.
Preface | xi
[Link]
How to Contact Us
Please address comments and questions concerning this book to the
publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
We have a web page for this book, where we list errata, examples,
and any additional information. You can access this page at http://
[Link]/ydkjs_types-and-grammar.
To comment or ask technical questions about this book, send email
to bookquestions@[Link].
For more information about our books, courses, conferences, and
news, see our website at [Link]
Find us on Facebook: [Link]
Follow us on Twitter: [Link]
Watch us on YouTube: [Link]
xii | Preface
[Link]