Author:Kyle Simpson
No description
Tags
Support Statistics
¥.00 ·
0times
Text Preview (First 20 pages)
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
Page
1
“An excellent look at the core JavaScript fundamentals that copy and paste and JavaScript toolkits don’t and could never teach you.” —DAVID WALSH, Senior Web Developer, Mozilla THE YOU DON’T KNOW JS SERIES INCLUDES: Up & Going Scope & Closures this & Object Prototypes Types & Grammar Async & Performance ES6 & Beyond YOU DON ’T KN OW JAVASCRIPT KYLE SIM PSON TYPES & G RA M M A R JAVA SCRIPT Twitter: @oreillymedia facebook.com/oreilly No matter how much experience you have with JavaScript, odds are you don’t fully understand the language. As part of the You Don’t Know JS series, this compact guide explores JavaScript types in greater depth than previous treatments by looking at type coercion problems, demonstrating why types work, and showing you how to take advantage of these features. Like other books in this series, You Don’t Know JS: Types & Grammar dives into trickier parts of the language that many JavaScript programmers simply avoid or assume don’t exist (like types). Armed with this knowledge, you can achieve true JavaScript mastery. WITH THIS BOOK YOU WILL: ■ Get acquainted with JavaScript’s seven types: null, undefined, boolean, number, string, object, and symbol ■ Understand why JavaScript’s unique array, string, and number characteristics may delight or confound you ■ Learn how natives provide object wrappers around primitive values ■ Dive into the coercion controversy—and learn why this feature is useful in many cases ■ Explore various nuances in JavaScript syntax, involving statements, expressions, and other features KYLE SIMPSON is an Open Web evangelist who’s passionate about all things JavaScript. He’s an author, workshop trainer, tech speaker, and OSS contributor/leader. oreilly.com YouDontKnowJS.com TYPES &I GRAMMAR ISBN: 978-1-491-90419-0 US $24.99 CAN $28.99 JAVASCRIPT TYPES &I GRAMMAR KYLE SIMPSON
Page
2
“An excellent look at the core JavaScript fundamentals that copy and paste and JavaScript toolkits don’t and could never teach you.” —DAVID WALSH, Senior Web Developer, Mozilla THE YOU DON’T KNOW JS SERIES INCLUDES: Up & Going Scope & Closures this & Object Prototypes Types & Grammar Async & Performance ES6 & Beyond YOU DON ’T KN OW JAVASCRIPT KYLE SIM PSON TYPES & G RA M M A R JAVA SCRIPT Twitter: @oreillymedia facebook.com/oreilly No matter how much experience you have with JavaScript, odds are you don’t fully understand the language. As part of the You Don’t Know JS series, this compact guide explores JavaScript types in greater depth than previous treatments by looking at type coercion problems, demonstrating why types work, and showing you how to take advantage of these features. Like other books in this series, You Don’t Know JS: Types & Grammar dives into trickier parts of the language that many JavaScript programmers simply avoid or assume don’t exist (like types). Armed with this knowledge, you can achieve true JavaScript mastery. WITH THIS BOOK YOU WILL: ■ Get acquainted with JavaScript’s seven types: null, undefined, boolean, number, string, object, and symbol ■ Understand why JavaScript’s unique array, string, and number characteristics may delight or confound you ■ Learn how natives provide object wrappers around primitive values ■ Dive into the coercion controversy—and learn why this feature is useful in many cases ■ Explore various nuances in JavaScript syntax, involving statements, expressions, and other features KYLE SIMPSON is an Open Web evangelist who’s passionate about all things JavaScript. He’s an author, workshop trainer, tech speaker, and OSS contributor/leader. oreilly.com YouDontKnowJS.com TYPES &I GRAMMAR ISBN: 978-1-491-90419-0 US $24.99 CAN $28.99 JAVASCRIPT TYPES & I GRAMMAR KYLE SIMPSON
Page
3
Kyle Simpson Types & Grammar
Page
4
978-1-491-90419-0 [LSI] 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 (http://safaribooksonline.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Editors: Simon St. Laurent and Brian MacDonald Production Editor: Kristen Brown Copyeditor: Christina Edwards Proofreader: Charles Roumeliotis Interior Designer: David Futato Cover Designer: Ellie Volckhausen February 2015: First Edition Revision History for the First Edition 2015-01-23: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781491904190 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.
Page
5
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
Page
6
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
Page
7
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 v
Page
8
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 (http://davidwalsh.name), Senior Web Developer at Mozilla vi | Foreword
Page
9
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
Page
10
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
Page
11
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
Page
12
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 http://bit.ly/ydkjs-types-code. 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
Page
13
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@oreilly.com. 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
Page
14
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:// bit.ly/ydkjs_types-and-grammar. To comment or ask technical questions about this book, send email to bookquestions@oreilly.com. For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com. Find us on Facebook: http://facebook.com/oreilly Follow us on Twitter: http://twitter.com/oreillymedia Watch us on YouTube: http://www.youtube.com/oreillymedia xii | Preface
Page
15
CHAPTER 1 Types Most developers would say that a dynamic language (like JS) does not have types. Let’s see what the ES5.1 specification has to say on the topic: Algorithms within this specification manipulate values each of which has an associated type. The possible value types are exactly those defined in this clause. Types are further sub-classified into ECMAScript language types and specification types. An ECMAScript language type corresponds to values that are directly manipulated by an ECMAScript programmer using the ECMAScript language. The ECMAScript language types are Unde‐ fined, Null, Boolean, String, Number, and Object. Now, if you’re a fan of strongly typed (statically typed) languages, you may object to this usage of the word “type.” In those languages, “type” means a whole lot more than it does here in JS. Some people say JS shouldn’t claim to have “types,” and they should instead be called “tags” or perhaps “subtypes.” Bah! We’re going to use this rough definition (the same one that seems to drive the wording of the spec): a type is an intrinsic, built- in set of characteristics that uniquely identifies the behavior of a par‐ ticular value and distinguishes it from other values, both to the engine and to the developer. In other words, if both the engine and the developer treat value 42 (the number) differently than they treat value "42" (the string), then those two values have different types—number and string, respec‐ 1
Page
16
tively. When you use 42, you are intending to do something numeric, like math. But when you use "42", you are intending to do some‐ thing string’ish, like outputting to the page, etc. These two values have different types. That’s by no means a perfect definition. But it’s good enough for this discussion. And it’s consistent with how JS describes itself. A Type by Any Other Name… Beyond academic definition disagreements, why does it matter if JavaScript has types or not? Having a proper understanding of each type and its intrinsic behav‐ ior is absolutely essential to understanding how to properly and accurately convert values to different types (see Chapter 4). Nearly every JS program ever written will need to handle value coercion in some shape or form, so it’s important you do so responsibly and with confidence. If you have the number value 42, but you want to treat it like a string, such as pulling out the "2" as a character in position 1, you obviously must first convert (coerce) the value from number to string. That seems simple enough. But there are many different ways that such coercion can happen. Some of these ways are explicit, easy to reason about, and reliable. But if you’re not careful, coercion can happen in very strange and surprising ways. Coercion confusion is perhaps one of the most profound frustra‐ tions for JavaScript developers. It has often been criticized as being so dangerous as to be considered a flaw in the design of the language, to be shunned and avoided. Armed with a full understanding of JavaScript types, we’re aiming to illustrate why coercion’s bad reputation is largely overhyped and somewhat undeserved—to flip your perspective so you see coer‐ cion’s power and usefulness. But first, we have to get a much better grip on values and types. 2 | Chapter 1: Types
Page
17
Built-in Types JavaScript defines seven built-in types: • null • undefined • boolean • number • string • object • symbol—added in ES6! All of these types except object are called “primitives.” The typeof operator inspects the type of the given value, and always returns one of seven string values—surprisingly, there’s not an exact 1-to-1 match with the seven built-in types we just listed: typeof undefined === "undefined"; // true typeof true === "boolean"; // true typeof 42 === "number"; // true typeof "42" === "string"; // true typeof { life: 42 } === "object"; // true // added in ES6! typeof Symbol() === "symbol"; // true These six listed types have values of the corresponding type and return a string value of the same name, as shown. Symbol is a new data type as of ES6, and will be covered in Chapter 3. As you may have noticed, I excluded null from the above listing. It’s special—special in the sense that it’s buggy when combined with the typeof operator: typeof null === "object"; // true It would have been nice (and correct!) if it returned "null", but this original bug in JS has persisted for nearly two decades, and will Built-in Types | 3
Page
18
likely never be fixed because there’s so much existing web content that relies on its buggy behavior that “fixing” the bug would create more “bugs” and break a lot of web software. If you want to test for a null value using its type, you need a com‐ pound condition: var a = null; (!a && typeof a === "object"); // true null is the only primitive value that is “falsy” (aka false-like; see Chapter 4) but which also returns "object" from the typeof check. So what’s the seventh string value that typeof can return? typeof function a(){ /* .. */ } === "function"; // true It’s easy to think that function would be a top-level built-in type in JS, especially given this behavior of the typeof operator. However, if you read the spec, you’ll see it’s actually somewhat of a “subtype” of object. Specifically, a function is referred to as a “callable object”— an object that has an internal [[Call]] property that allows it to be invoked. The fact that functions are actually objects is quite useful. Most importantly, they can have properties. For example: function a(b,c) { /* .. */ } The function object has a length property set to the number of for‐ mal parameters it is declared with: a.length; // 2 Since you declared the function with two formal named parameters (b and c), the “length of the function” is 2. What about arrays? They’re native to JS, so are they a special type? typeof [1,2,3] === "object"; // true Nope, just objects. It’s most appropriate to think of them also as a “subtype” of object (see Chapter 3), in this case with the additional characteristics of being numerically indexed (as opposed to just being string-keyed like plain objects) and maintaining an automati‐ cally updated .length property. 4 | Chapter 1: Types
Page
19
Values as Types In JavaScript, variables don’t have types—values have types. Variables can hold any value, at any time. Another way to think about JS types is that JS doesn’t have “type enforcement,” in that the engine doesn’t insist that a variable always holds values of the same initial type that it starts out with. A variable can, in one assignment statement, hold a string, and in the next hold a number, and so on. The value 42 has an intrinsic type of number, and its type cannot be changed. Another value, like "42" with the string type, can be cre‐ ated from the number value 42 through a process called coercion (see Chapter 4). If you use typeof against a variable, it’s not asking “What’s the type of the variable?” as it may seem, since JS variables have no types. Instead, it’s asking “What’s the type of the value in the variable?” var a = 42; typeof a; // "number" a = true; typeof a; // "boolean" The typeof operator always returns a string. So: typeof typeof 42; // "string" The first typeof 42 returns "number", and typeof "number" is "string". undefined Versus “undeclared” Variables that have no value currently actually have the undefined value. Calling typeof against such variables will return "unde fined": var a; typeof a; // "undefined" var b = 42; var c; // later b = c; Values as Types | 5
Page
20
typeof b; // "undefined" typeof c; // "undefined" It’s tempting for most developers to think of the word “undefined” as a synonym for “undeclared.” However, in JS, these two concepts are quite different. An “undefined” variable is one that has been declared in the accessi‐ ble scope, but at the moment has no other value in it. By contrast, an “undeclared” variable is one that has not been formally declared in the accessible scope. Consider: var a; a; // undefined b; // ReferenceError: b is not defined An annoying confusion is the error message that browsers assign to this condition. As you can see, the message is “b is not defined,” which is of course very easy and reasonable to confuse with “b is undefined.” Yet again, “undefined” and “is not defined” are very dif‐ ferent things. It’d be nice if the browsers said something like “b is not found” or “b is not declared” to reduce the confusion! There’s also a special behavior associated with typeof as it relates to undeclared variables that even further reinforces the confusion. Consider: var a; typeof a; // "undefined" typeof b; // "undefined" The typeof operator returns "undefined" even for “undeclared” (or “not defined”) variables. Notice that there was no error thrown when we executed typeof b, even though b is an undeclared vari‐ able. This is a special safety guard in the behavior of typeof. Similar to above, it would have been nice if typeof used with an undeclared variable returned “undeclared” instead of conflating the result value with the different “undefined” case. 6 | Chapter 1: Types
Comments 0
Loading comments...
Reply to Comment
Edit Comment