├── .gitignore ├── .travis.yml ├── up & going ├── cover.jpg ├── fig1.png ├── fig2.png ├── fig3.png ├── fig4.png ├── fig5.png ├── fig6.png ├── README.md ├── toc.md ├── foreword.md ├── apA.md └── ch3.md ├── es6 & beyond ├── cover.jpg ├── fig1.png ├── README.md ├── toc.md ├── foreword.md ├── apA.md ├── ch1.md └── ch4.md ├── scope & closures ├── fig1.png ├── fig2.png ├── cover.jpg ├── README.md ├── toc.md ├── apA.md ├── apC.md ├── apB.md ├── ch4.md ├── apD.md └── ch2.md ├── types & grammar ├── cover.jpg ├── fig1.png ├── README.md ├── toc.md ├── foreword.md ├── apB.md └── ch1.md ├── async & performance ├── cover.jpg ├── README.md ├── toc.md ├── foreword.md └── apC.md ├── this & object prototypes ├── cover.jpg ├── fig1.png ├── fig2.png ├── fig3.png ├── fig4.png ├── fig5.png ├── fig6.png ├── README.md ├── toc.md ├── foreword.md ├── apB.md ├── ch1.md └── apA.md ├── package.json ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md ├── CONTRIBUTING.md ├── README.md └── preface.md /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "6" 4 | -------------------------------------------------------------------------------- /up & going/cover.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devSchacht/You-Dont-Know-JS/HEAD/up & going/cover.jpg -------------------------------------------------------------------------------- /up & going/fig1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devSchacht/You-Dont-Know-JS/HEAD/up & going/fig1.png -------------------------------------------------------------------------------- /up & going/fig2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devSchacht/You-Dont-Know-JS/HEAD/up & going/fig2.png -------------------------------------------------------------------------------- /up & going/fig3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devSchacht/You-Dont-Know-JS/HEAD/up & going/fig3.png -------------------------------------------------------------------------------- /up & going/fig4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devSchacht/You-Dont-Know-JS/HEAD/up & going/fig4.png -------------------------------------------------------------------------------- /up & going/fig5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devSchacht/You-Dont-Know-JS/HEAD/up & going/fig5.png -------------------------------------------------------------------------------- /up & going/fig6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devSchacht/You-Dont-Know-JS/HEAD/up & going/fig6.png -------------------------------------------------------------------------------- /es6 & beyond/cover.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devSchacht/You-Dont-Know-JS/HEAD/es6 & beyond/cover.jpg -------------------------------------------------------------------------------- /es6 & beyond/fig1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devSchacht/You-Dont-Know-JS/HEAD/es6 & beyond/fig1.png -------------------------------------------------------------------------------- /scope & closures/fig1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devSchacht/You-Dont-Know-JS/HEAD/scope & closures/fig1.png -------------------------------------------------------------------------------- /scope & closures/fig2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devSchacht/You-Dont-Know-JS/HEAD/scope & closures/fig2.png -------------------------------------------------------------------------------- /types & grammar/cover.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devSchacht/You-Dont-Know-JS/HEAD/types & grammar/cover.jpg -------------------------------------------------------------------------------- /types & grammar/fig1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devSchacht/You-Dont-Know-JS/HEAD/types & grammar/fig1.png -------------------------------------------------------------------------------- /scope & closures/cover.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devSchacht/You-Dont-Know-JS/HEAD/scope & closures/cover.jpg -------------------------------------------------------------------------------- /async & performance/cover.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devSchacht/You-Dont-Know-JS/HEAD/async & performance/cover.jpg -------------------------------------------------------------------------------- /this & object prototypes/cover.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devSchacht/You-Dont-Know-JS/HEAD/this & object prototypes/cover.jpg -------------------------------------------------------------------------------- /this & object prototypes/fig1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devSchacht/You-Dont-Know-JS/HEAD/this & object prototypes/fig1.png -------------------------------------------------------------------------------- /this & object prototypes/fig2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devSchacht/You-Dont-Know-JS/HEAD/this & object prototypes/fig2.png -------------------------------------------------------------------------------- /this & object prototypes/fig3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devSchacht/You-Dont-Know-JS/HEAD/this & object prototypes/fig3.png -------------------------------------------------------------------------------- /this & object prototypes/fig4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devSchacht/You-Dont-Know-JS/HEAD/this & object prototypes/fig4.png -------------------------------------------------------------------------------- /this & object prototypes/fig5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devSchacht/You-Dont-Know-JS/HEAD/this & object prototypes/fig5.png -------------------------------------------------------------------------------- /this & object prototypes/fig6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devSchacht/You-Dont-Know-JS/HEAD/this & object prototypes/fig6.png -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "scripts": { 4 | "test": "yaspeller . -e '.md'" 5 | }, 6 | "dependencies": { 7 | "yaspeller": "^4.0.3" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | **Yes, I promise I've read the [Contributions Guidelines](https://github.com/getify/You-Dont-Know-JS/blob/master/CONTRIBUTING.md)** (please feel free to remove this line). 2 | -------------------------------------------------------------------------------- /PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | **Yes, I promise I've read the [Contributions Guidelines](https://github.com/getify/You-Dont-Know-JS/blob/master/CONTRIBUTING.md)** (please feel free to remove this line). 2 | -------------------------------------------------------------------------------- /up & going/README.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: Up & Going 2 | 3 | 4 | 5 | ----- 6 | 7 | **[Purchase digital/print copy from O'Reilly](http://shop.oreilly.com/product/0636920039303.do)** 8 | 9 | ----- 10 | 11 | [Table of Contents](toc.md) 12 | 13 | * [Foreword](foreword.md) (by [Jenn Lukas](http://jennlukas.com)) 14 | * [Preface](../preface.md) 15 | * [Chapter 1: Into Programming](ch1.md) 16 | * [Chapter 2: Into JavaScript](ch2.md) 17 | * [Chapter 3: Into YDKJS](ch3.md) 18 | * [Appendix A: Thank You's!](apA.md) 19 | -------------------------------------------------------------------------------- /types & grammar/README.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: Types & Grammar 2 | 3 | 4 | 5 | ----- 6 | 7 | **[Purchase digital/print copy from O'Reilly](http://shop.oreilly.com/product/0636920033745.do)** 8 | 9 | ----- 10 | 11 | [Table of Contents](toc.md) 12 | 13 | * [Foreword](foreword.md) (by [David Walsh](http://davidwalsh.name)) 14 | * [Preface](../preface.md) 15 | * [Chapter 1: Types](ch1.md) 16 | * [Chapter 2: Values](ch2.md) 17 | * [Chapter 3: Natives](ch3.md) 18 | * [Chapter 4: Coercion](ch4.md) 19 | * [Chapter 5: Grammar](ch5.md) 20 | * [Appendix A: Mixed Environment JavaScript](apA.md) 21 | * [Appendix B: Thank You's!](apB.md) 22 | -------------------------------------------------------------------------------- /up & going/toc.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: Up & Going 2 | 3 | ## Table of Contents 4 | 5 | * Foreword 6 | * Preface 7 | * Chapter 1: Into Programming 8 | * Code 9 | * Try It Yourself 10 | * Operators 11 | * Values & Types 12 | * Code Comments 13 | * Variables 14 | * Blocks 15 | * Conditionals 16 | * Loops 17 | * Functions 18 | * Practice 19 | * Chapter 2: Into JavaScript 20 | * Values & Types 21 | * Variables 22 | * Conditionals 23 | * Strict Mode 24 | * Functions As Values 25 | * `this` Keyword 26 | * Prototypes 27 | * Old & New 28 | * Non-JavaScript 29 | * Chapter 3: Into YDKJS 30 | * Scope & Closures 31 | * this & Object Prototypes 32 | * Types & Grammar 33 | * Async & Performance 34 | * ES6 & Beyond 35 | * Appendix A: Acknowledgments 36 | -------------------------------------------------------------------------------- /this & object prototypes/README.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: *this* & Object Prototypes 2 | 3 | 4 | 5 | ----- 6 | 7 | **[Purchase digital/print copy from O'Reilly](http://shop.oreilly.com/product/0636920033738.do)** 8 | 9 | ----- 10 | 11 | [Table of Contents](toc.md) 12 | 13 | * [Foreword](foreword.md) (by [Nick Berardi](https://github.com/nberardi)) 14 | * [Preface](../preface.md) 15 | * [Chapter 1: *this* Or That?](ch1.md) 16 | * [Chapter 2: *this* All Makes Sense Now!](ch2.md) 17 | * [Chapter 3: Objects](ch3.md) 18 | * [Chapter 4: Mixing (Up) "Class" Objects](ch4.md) 19 | * [Chapter 5: Prototypes](ch5.md) 20 | * [Chapter 6: Behavior Delegation](ch6.md) 21 | * [Appendix A: ES6 *class*](apA.md) 22 | * [Appendix B: Thank You's!](apB.md) 23 | -------------------------------------------------------------------------------- /es6 & beyond/README.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: ES6 & Beyond 2 | 3 | 4 | 5 | ----- 6 | 7 | **[Purchase digital/print copy from O'Reilly](http://shop.oreilly.com/product/0636920033769.do)** 8 | 9 | ----- 10 | 11 | [Table of Contents](toc.md) 12 | 13 | * [Foreword](foreword.md) (by [Rick Waldron](http://bocoup.com/weblog/author/rick-waldron/)) 14 | * [Preface](../preface.md) 15 | * [Chapter 1: ES? Now & Future](ch1.md) 16 | * [Chapter 2: Syntax](ch2.md) 17 | * [Chapter 3: Organization](ch3.md) 18 | * [Chapter 4: Async Flow Control](ch4.md) 19 | * [Chapter 5: Collections](ch5.md) 20 | * [Chapter 6: API Additions](ch6.md) 21 | * [Chapter 7: Meta Programming](ch7.md) 22 | * [Chapter 8: Beyond ES6](ch8.md) 23 | * [Appendix A: Thank You's!](apA.md) 24 | -------------------------------------------------------------------------------- /async & performance/README.md: -------------------------------------------------------------------------------- 1 | # Вы не знаете JS: Асинхронность и Производительность 2 | 3 | 4 | 5 | ----- 6 | 7 | **[Purchase digital/print copy from O'Reilly](http://shop.oreilly.com/product/0636920033752.do)** 8 | 9 | ----- 10 | 11 | [Table of Contents](toc.md) 12 | 13 | * [Foreword](foreword.md) (by [Jake Archibald](http://jakearchibald.com)) 14 | * [Preface](../preface.md) 15 | * [Глава 1: Асинхронность: Сейчас и Потом](ch1.md) 16 | * [Глава 2: Колбэки](ch2.md) 17 | * [Chapter 3: Promises](ch3.md) 18 | * [Chapter 4: Generators](ch4.md) 19 | * [Chapter 5: Program Performance](ch5.md) 20 | * [Chapter 6: Benchmarking & Tuning](ch6.md) 21 | * [Appendix A: Library: asynquence](apA.md) 22 | * [Appendix B: Advanced Async Patterns](apB.md) 23 | * [Appendix C: Thank You's!](apC.md) 24 | -------------------------------------------------------------------------------- /scope & closures/README.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: Scope & Closures 2 | 3 | 4 | 5 | ----- 6 | 7 | **[Purchase digital/print copy from O'Reilly](http://shop.oreilly.com/product/0636920026327.do)** 8 | 9 | ----- 10 | 11 | [Table of Contents](toc.md) 12 | 13 | * [Foreword](https://shanehudson.net/2014/06/03/foreword-dont-know-js/) (by [Shane Hudson](https://github.com/shanehudson)) 14 | * [Preface](../preface.md) 15 | * [Chapter 1: What is Scope?](ch1.md) 16 | * [Chapter 2: Lexical Scope](ch2.md) 17 | * [Chapter 3: Function vs. Block Scope](ch3.md) 18 | * [Chapter 4: Hoisting](ch4.md) 19 | * [Chapter 5: Scope Closures](ch5.md) 20 | * [Appendix A: Dynamic Scope](apA.md) 21 | * [Appendix B: Polyfilling Block Scope](apB.md) 22 | * [Appendix C: Lexical-this](apC.md) 23 | * [Appendix D: Thank You's!](apD.md) 24 | -------------------------------------------------------------------------------- /scope & closures/toc.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: Scope & Closures 2 | 3 | ## Table of Contents 4 | 5 | * Foreword 6 | * Preface 7 | * Chapter 1: What is Scope? 8 | * Compiler Theory 9 | * Understanding Scope 10 | * Nested Scope 11 | * Errors 12 | * Chapter 2: Lexical Scope 13 | * Lex-time 14 | * Cheating Lexical 15 | * Chapter 3: Function vs. Block Scope 16 | * Scope From Functions 17 | * Hiding In Plain Scope 18 | * Functions As Scopes 19 | * Blocks As Scopes 20 | * Chapter 4: Hoisting 21 | * Chicken Or The Egg? 22 | * The Compiler Strikes Again 23 | * Functions First 24 | * Chapter 5: Scope Closures 25 | * Enlightenment 26 | * Nitty Gritty 27 | * Now I Can See 28 | * Loops + Closure 29 | * Modules 30 | * Appendix A: Dynamic Scope 31 | * Appendix B: Polyfilling Block Scope 32 | * Appendix C: Lexical-this 33 | * Appendix D: Acknowledgments 34 | -------------------------------------------------------------------------------- /types & grammar/toc.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: Types & Grammar 2 | 3 | ## Table of Contents 4 | 5 | * Foreword 6 | * Preface 7 | * Chapter 1: Types 8 | * A Type By Any Other Name... 9 | * Built-in Types 10 | * Values as Types 11 | * Chapter 2: Values 12 | * Arrays 13 | * Strings 14 | * Numbers 15 | * Special Values 16 | * Value vs Reference 17 | * Chapter 3: Natives 18 | * Internal `[[Class]]` 19 | * Boxing Wrappers 20 | * Unboxing 21 | * Natives as Constructors 22 | * Chapter 4: Coercion 23 | * Converting Values 24 | * Abstract Value Operations 25 | * Explicit Coercion 26 | * Implicit Coercion 27 | * Loose Equals vs Strict Equals 28 | * Abstract Relational Comparison 29 | * Chapter 5: Grammar 30 | * Statements & Expressions 31 | * Operator Precedence 32 | * Automatic Semicolons 33 | * Errors 34 | * Function Arguments 35 | * `try..finally` 36 | * `switch` 37 | * Appendix A: Mixed Environment JavaScript 38 | * Appendix B: Acknowledgments 39 | 40 | -------------------------------------------------------------------------------- /this & object prototypes/toc.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: *this* & Object Prototypes 2 | 3 | ## Table of Contents 4 | 5 | * Foreword 6 | * Preface 7 | * Chapter 1: `this` Or That? 8 | * Why `this`? 9 | * Confusions 10 | * What's `this`? 11 | * Chapter 2: `this` All Makes Sense Now! 12 | * Call-site 13 | * Nothing But Rules 14 | * Everything In Order 15 | * Binding Exceptions 16 | * Lexical `this` 17 | * Chapter 3: Objects 18 | * Syntax 19 | * Type 20 | * Contents 21 | * Iteration 22 | * Chapter 4: Mixing (Up) "Class" Objects 23 | * Class Theory 24 | * Class Mechanics 25 | * Class Inheritance 26 | * Mixins 27 | * Chapter 5: Prototypes 28 | * `[[Prototype]]` 29 | * "Class" 30 | * "(Prototypal) Inheritance" 31 | * Object Links 32 | * Chapter 6: Behavior Delegation 33 | * Towards Delegation-Oriented Design 34 | * Classes vs. Objects 35 | * Simpler Design 36 | * Nicer Syntax 37 | * Introspection 38 | * Appendix A: ES6 `class` 39 | * Appendix B: Acknowledgments 40 | 41 | -------------------------------------------------------------------------------- /async & performance/toc.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: Async & Performance 2 | 3 | ## Table of Contents 4 | 5 | * Foreword 6 | * Preface 7 | * Chapter 1: Asynchrony: Now & Later 8 | * A Program In Chunks 9 | * Event Loop 10 | * Parallel Threading 11 | * Concurrency 12 | * Jobs 13 | * Statement Ordering 14 | * Chapter 2: Callbacks 15 | * Continuations 16 | * Sequential Brain 17 | * Trust Issues 18 | * Trying To Save Callbacks 19 | * Chapter 3: Promises 20 | * What is a Promise? 21 | * Thenable Duck-Typing 22 | * Promise Trust 23 | * Chain Flow 24 | * Error Handling 25 | * Promise Patterns 26 | * Promise API Recap 27 | * Promise Limitations 28 | * Chapter 4: Generators 29 | * Breaking Run-to-completion 30 | * Generator'ing Values 31 | * Iterating Generators Asynchronously 32 | * Generators + Promises 33 | * Generator Delegation 34 | * Generator Concurrency 35 | * Thunks 36 | * Pre-ES6 Generators 37 | * Chapter 5: Program Performance 38 | * Web Workers 39 | * SIMD 40 | * asm.js 41 | * Chapter 6: Benchmarking & Tuning 42 | * Benchmarking 43 | * Context Is King 44 | * jsPerf.com 45 | * Writing Good Tests 46 | * Microperformance 47 | * Tail Call Optimization (TCO) 48 | * Appendix A: *asynquence* Library 49 | * Appendix B: Advanced Async Patterns 50 | * Appendix C: Acknowledgments 51 | 52 | -------------------------------------------------------------------------------- /es6 & beyond/toc.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: ES6 & Beyond 2 | 3 | ## Table of Contents 4 | 5 | * Foreword 6 | * Preface 7 | * Chapter 1: ES? Now & Future 8 | * Versioning 9 | * Transpiling 10 | * Chapter 2: Syntax 11 | * Block-Scoped Declarations 12 | * Spread / Rest 13 | * Default Parameter Values 14 | * Destructuring 15 | * Object Literal Extensions 16 | * Template Literals 17 | * Arrow Functions 18 | * `for..of` Loops 19 | * Regular Expression Extensions 20 | * Number Literal Extensions 21 | * Unicode 22 | * Symbols 23 | * Chapter 3: Organization 24 | * Iterators 25 | * Generators 26 | * Modules 27 | * Classes 28 | * Chapter 4: Async Flow Control 29 | * Promises 30 | * Generators + Promises 31 | * Chapter 5: Collections 32 | * TypedArrays 33 | * Maps 34 | * WeakMaps 35 | * Sets 36 | * WeakSets 37 | * Chapter 6: API Additions 38 | * `Array` 39 | * `Object` 40 | * `Math` 41 | * `Number` 42 | * `String` 43 | * Chapter 7: Meta Programming 44 | * Function Names 45 | * Meta Properties 46 | * Well Known Symbols 47 | * Proxies 48 | * `Reflect` API 49 | * Feature Testing 50 | * Tail Call Optimization (TCO) 51 | * Chapter 8: Beyond ES6 52 | * `async function`s 53 | * `Object.observe(..)` 54 | * Exponentiation Operator 55 | * Object Properties and `...` 56 | * `Array#includes(..)` 57 | * SIMD 58 | * Appendix A: Acknowledgments 59 | -------------------------------------------------------------------------------- /es6 & beyond/foreword.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: ES6 & Beyond 2 | # Foreword 3 | 4 | Kyle Simpson is a thorough pragmatist. 5 | 6 | I can't think of higher praise than this. To me, these are two of the most important qualities that a software developer must have. That's right: *must*, not *should*. Kyle's keen ability to tease apart layers of the JavaScript programming language and present them in understandable and meaningful portions is second to none. 7 | 8 | *ES6 & Beyond* will be familiar to readers of the *You Don't Know JS* series: they can expect to be deeply immersed in everything from the obvious, to the very subtle -- revealing semantics that were either taken for granted or never even considered. Until now, the *You Don't Know JS* book series has covered material that has at least some degree of familiarity to its readers. They have either seen or heard about the subject matter; they may even have experience with it. This volume covers material that only a very small portion of the JavaScript developer community has been exposed to: the evolutionary changes to the language introduced in the ECMAScript 2015 Language Specification. 9 | 10 | Over the last couple years, I've witnessed Kyle's tireless efforts to familiarize himself with this material to a level of expertise that is rivaled by only a handful of his professional peers. That's quite a feat, considering that at the time of this writing, the language specification document hasn't been formally published! But what I've said is true, and I've read every word that Kyle's written for this book. I've followed every change, and each time, the content only gets better and provides yet a deeper level of understanding. 11 | 12 | This book is about shaking up your sense of understanding by exposing you to the new and unknown. The intention is to evolve your knowledge in step with your tools by bestowing you with new capabilities. It exists to give you the confidence to fully embrace the next major era of JavaScript programming. 13 | 14 | Rick Waldron
15 | [@rwaldron](http://twitter.com/rwaldron)
16 | Open Web Engineer at Bocoup
17 | Ecma/TC39 Representative for jQuery 18 | -------------------------------------------------------------------------------- /types & grammar/foreword.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: Types & Grammar 2 | # Foreword 3 | 4 | It was once said, "JavaScript is the only language developers don't learn to use before using it." 5 | 6 | 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 a core computer science language 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. 7 | 8 | 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 Goldeneye midi theme song playing in the background, a 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. 9 | 10 | 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 what's actually happening. The widespread use of JavaScript toolkits like jQuery have, in their own small way, perpetuated this pattern of nonlearning of core JavaScript. 11 | 12 | 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 fundamentals, and their "gotchas," and apply them magnificently. As useful as these toolkits are, it's still incredibly important to know the 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. 13 | 14 | *Types and 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: no fluff and word-smithing -- exactly the type of tech book I love. 15 | 16 | Enjoy Types and Grammar and don't let it get too far away from your desk! 17 | 18 | David Walsh
19 | [http://davidwalsh.name](http://davidwalsh.name), [@davidwalshblog](http://twitter.com/davidwalshblog)
20 | Senior Web Developer, Mozilla 21 | -------------------------------------------------------------------------------- /async & performance/foreword.md: -------------------------------------------------------------------------------- 1 | # Вы не знаете JavaScript: Асинхронность и Производительность 2 | # Предисловие 3 | 4 | На протяжении многих лет мой работодатель доверяет мне достаточно, чтобы я проводил собеседования. Если мы ищем кого-то с навыками JavaScript, обычно мой первый вопрос это... на самом деле это не правда. Для начала я выясню, нужно ли кандидату отойти в туалет или выпить воды, потому что чувство комфорта является довольно важным. Как только я удостоверюсь в том что с балансом жидкости в организме у кандидата всё в порядке, я начинаю интересоваться его познаниями в JavaScript, или хотя бы jQuery. 5 | 6 | Не то чтобы с jQuery что-то было не так. Он позволяет Вам делать многое, без особых знаний JavaScript, и это фича, а не баг. Но в том случае, если задача требует продвинутые знания о производительности и поддерживаемости Javascript кода, Вам нужен кто-то, кто знает как такие библиотеки нужно объединять. Вы должны уметь использовать ядро JavaScript так же, как и они. 7 | 8 | Если я хочу увидеть всю картину того, насколько кандидат знает JavaScript, в большей степени я заинтересован в том, чтобы узнать что он думает о замыканиях (вы же уже читали книгу из этой серии, верно?) и как получить максимальную отдачу от асинхронности, которая подводит нас к этой книге. 9 | 10 | Для начала, вы пройдёте через функции обратного вызова, хлеб и масло асинхронного программирования. Конечно, из хлеба и масла не выйдет особо изысканного блюда, но следующий курс полон вкусных-вкусных обещаний! (next course is full of tasty tasty promises - каламбур, намекающий, что вместо функций обратного вызова, стоит использовать Promise. - прим. перев.) 11 | 12 | Если вы не знакомы с промисами, то сейчас самое время в них разобраться. На данный момент, промисы являются общепринятым способом для работы с асинхронностью в JavaScript и DOM. Их будут использовать многие методы из DOM API, а многие уже это делают, так что будьте готовы! На момент написания, промисы уже поддерживаются в большинстве мажорных браузеров, и вскоре появятся в IE. Как только вы закончите с промисами, надеюсь вы приступите к изучению генераторов. 13 | 14 | Генераторы пробираются в стабильные версии Chrome и Firefox без особых почестей, потому что, откровенно говоря, они больше запутанные, чем интересные. По крайней мере, я так думал до того, как увидел как они используются в связке с промисами. В таком случае, они становятся довольно важным инструментом для поддержки читабельности кода. 15 | 16 | На десерт, конечно, я не буду портить сюрприз, но приготовьтесь заглянуть в будущее JavaScript! Мы рассмотрим нововведения, которые дадут Вам больше контроля над согласованностью и асинхронностью. 17 | 18 | Что ж, я не буду отвлекать вас от наслаждения книгой. Вы уже прочитали часть книги, перед тем как приступили к данному Предисловию, так что получите свои 10 асинхронных очков. Вы их заслужили! 19 | 20 | Джейк Арчибальд
21 | [jakearchibald.com](http://jakearchibald.com), [@jaffathecake](http://twitter.com/jaffathecake)
22 | Developer Advocate в Google Chrome 23 | -------------------------------------------------------------------------------- /scope & closures/apA.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: Scope & Closures 2 | # Appendix A: Dynamic Scope 3 | 4 | In Chapter 2, we talked about "Dynamic Scope" as a contrast to the "Lexical Scope" model, which is how scope works in JavaScript (and in fact, most other languages). 5 | 6 | We will briefly examine dynamic scope, to hammer home the contrast. But, more importantly, dynamic scope actually is a near cousin to another mechanism (`this`) in JavaScript, which we covered in the "*this & Object Prototypes*" title of this book series. 7 | 8 | As we saw in Chapter 2, lexical scope is the set of rules about how the *Engine* can look-up a variable and where it will find it. The key characteristic of lexical scope is that it is defined at author-time, when the code is written (assuming you don't cheat with `eval()` or `with`). 9 | 10 | Dynamic scope seems to imply, and for good reason, that there's a model whereby scope can be determined dynamically at runtime, rather than statically at author-time. That is in fact the case. Let's illustrate via code: 11 | 12 | ```js 13 | function foo() { 14 | console.log( a ); // 2 15 | } 16 | 17 | function bar() { 18 | var a = 3; 19 | foo(); 20 | } 21 | 22 | var a = 2; 23 | 24 | bar(); 25 | ``` 26 | 27 | Lexical scope holds that the RHS reference to `a` in `foo()` will be resolved to the global variable `a`, which will result in value `2` being output. 28 | 29 | Dynamic scope, by contrast, doesn't concern itself with how and where functions and scopes are declared, but rather **where they are called from**. In other words, the scope chain is based on the call-stack, not the nesting of scopes in code. 30 | 31 | So, if JavaScript had dynamic scope, when `foo()` is executed, **theoretically** the code below would instead result in `3` as the output. 32 | 33 | ```js 34 | function foo() { 35 | console.log( a ); // 3 (not 2!) 36 | } 37 | 38 | function bar() { 39 | var a = 3; 40 | foo(); 41 | } 42 | 43 | var a = 2; 44 | 45 | bar(); 46 | ``` 47 | 48 | How can this be? Because when `foo()` cannot resolve the variable reference for `a`, instead of stepping up the nested (lexical) scope chain, it walks up the call-stack, to find where `foo()` was *called from*. Since `foo()` was called from `bar()`, it checks the variables in scope for `bar()`, and finds an `a` there with value `3`. 49 | 50 | Strange? You're probably thinking so, at the moment. 51 | 52 | But that's just because you've probably only ever worked on (or at least deeply considered) code which is lexically scoped. So dynamic scoping seems foreign. If you had only ever written code in a dynamically scoped language, it would seem natural, and lexical scope would be the odd-ball. 53 | 54 | To be clear, JavaScript **does not, in fact, have dynamic scope**. It has lexical scope. Plain and simple. But the `this` mechanism is kind of like dynamic scope. 55 | 56 | The key contrast: **lexical scope is write-time, whereas dynamic scope (and `this`!) are runtime**. Lexical scope cares *where a function was declared*, but dynamic scope cares where a function was *called from*. 57 | 58 | Finally: `this` cares *how a function was called*, which shows how closely related the `this` mechanism is to the idea of dynamic scoping. To dig more into `this`, read the title "*this & Object Prototypes*". 59 | -------------------------------------------------------------------------------- /up & going/foreword.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: Up & Going 2 | # Foreword 3 | 4 | What was the last new thing you learned? 5 | 6 | Perhaps it was a foreign language, like Italian or German. Or maybe it was a graphics editor, like Photoshop. Or a cooking technique or woodworking or an exercise routine. I want you to remember that feeling when you finally got it: the lightbulb moment. When things went from blurry to crystal clear, as you mastered the table saw or understood the difference between masculine and feminine nouns in French. How did it feel? Pretty amazing, right? 7 | 8 | Now I want you to travel back a little bit further in your memory to right before you learned your new skill. How did *that* feel? Probably slightly intimidating and maybe a little bit frustrating, right? At one point, we all did not know the things that we know now and that’s totally OK; we all start somewhere. Learning new material is an exciting adventure, especially if you are looking to learn the subject efficiently. 9 | 10 | I teach a lot of beginner coding classes. The students who take my classes have often tried teaching themselves subjects like HTML or JavaScript by reading blog posts or copying and pasting code, but they haven’t been able to truly master the material that will allow them to code their desired outcome. And because they don’t truly grasp the ins and outs of certain coding topics, they can’t write powerful code or debug their own work, as they don’t really understand what is happening. 11 | 12 | I always believe in teaching my classes the proper way, meaning I teach web standards, semantic markup, well-commented code, and other best practices. I cover the subject in a thorough manner to explain the hows and whys, without just tossing out code to copy and paste. When you strive to comprehend your code, you create better work and become better at what you do. The code isn’t just your *job* anymore, it’s your *craft*. This is why I love *Up & Going*. Kyle takes us on a deep dive through syntax and terminology to give a great introduction to JavaScript without cutting corners. This book doesn’t skim over the surface, but really allows us to genuinely understand the concepts we will be writing. 13 | 14 | Because it’s not enough to be able to duplicate jQuery snippets into your website, the same way it’s not enough to learn how to open, close, and save a document in Photoshop. Sure, once I learn a few basics about the program I could create and share a design I made. But without legitimately knowing the tools and what is behind them, how can I define a grid, or craft a legible type system, or optimize graphics for web use. The same goes for JavaScript. Without knowing how loops work, or how to define variables, or what scope is, we won’t be writing the best code we can. We don’t want to settle for anything less -- this is, after all, our craft. 15 | 16 | The more you are exposed to JavaScript, the clearer it becomes. Words like closures, objects, and methods might seem out of reach to you now, but this book will help those terms come into clarity. I want you to keep those two feelings of before and after you learn something in mind as you begin this book. It might seem daunting, but you’ve picked up this book because you are starting an awesome journey to hone your knowledge. *Up & Going* is the start of our path to understanding programming. Enjoy the lightbulb moments! 17 | 18 | Jenn Lukas
19 | [jennlukas.com](http://jennlukas.com/), [@jennlukas](https://twitter.com/jennlukas)
20 | Front-end consultant 21 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Please feel free to contribute to the quality of this content by submitting PR's for improvements to code snippets, explanations, etc. If there's any doubt or if you think that a word/phrase is used confusingly, **before submitting a PR, open an issue to ask about it.** 4 | 5 | However, if you choose to contribute content (not just typo corrections) to this repo, you agree that you're giving me a non-exclusive license to use that content for the book, as I (and my publisher) deem appropriate. You probably guessed that already, but I just have to make sure the lawyers are happy by explicitly stating it. 6 | 7 | ## Reading Experience (Chapter/Section links, etc) 8 | 9 | I understand that reading one long .md file, with no relative cross links to other sections/etc, is not the preferred reading experience for most of you. As such, it's totally reasonable to want to file an issue/PR to add those kinds of features. 10 | 11 | This topic has been brought up many times, and I've considered it. For now, I **do not** accept these kinds of changes into the repo. 12 | 13 | The main purpose of my book repos is to track and manage the content for the purposes of publication (paid-for ebooks and print books). I do this in the open because I also care about providing free and early access to the content, to make sure there is no paywall barrier to learning. 14 | 15 | As such, this repo **is not optimized for your reading experience.** 16 | 17 | The primary reading experience, likely the most pleasant one for many of you, is the ebooks or print books, which [are available for sale](http://ssearch.oreilly.com/?q=%22you+don%27t+know+js%22&x=0&y=0). The balance I'm striking here is releasing the content for free, but selling the reading experience. Other authors make different decisions on that balance, but that's what I've come to for now. 18 | 19 | I hope you continue to enjoy and benefit from the content, and I also hope you value it enough to [purchase the best reading experience](http://ssearch.oreilly.com/?q=%22you+don%27t+know+js%22&x=0&y=0) in the ebook/print form. 20 | 21 | ## Editions 22 | 23 | The current state of this repo is the 1st Edition of the published form of these books. That means that you should have almost exactly the same content here as in the ebooks or printed books, with only minor variances in typos, formatting, etc. 24 | 25 | I generally am not accepting any changes to the current repo, as I do not want this content to diverge from what's in the published books. There are over a hundred filed issues/PRs for changes that are being collected for the 2nd Edition, but work has not yet begun on that. 26 | 27 | So, if you find something that should be fixed, just know that it will likely sit for awhile in that batch until it's time to make the 2nd Edition updates. At that time, my plan is to make separate branches to track the editions. 28 | 29 | ## Typos? 30 | 31 | These books go through official editing with the publisher, and typos are likely all caught at that stage. As such, **typos are not a big concern for this repo**. 32 | 33 | If you're going to submit a PR for typo fixes, please be measured in doing so by collecting several small changes into a single PR (in separate commits). Or, **just don't even worry about them for now,** because we'll get to them later. I promise. 34 | 35 | ## Search First! 36 | 37 | Also, if you have any questions or concerns, please make sure to search the issues (both open and closed!) first, to keep the churn of issues to a minimum. I want to keep my focus on writing these books as much as possible. 38 | -------------------------------------------------------------------------------- /this & object prototypes/foreword.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: *this* & Object Prototypes 2 | # Foreword 3 | 4 | While reading this book in preparation for writing this foreword, I was forced to reflect on how I learned JavaScript and how much it has changed over the last 15 years that I have been programming and developing with it. 5 | 6 | When I started using JavaScript 15 years ago, the practice of using non-HTML technologies such as CSS and JS in your web pages was called DHTML or Dynamic HTML. Back then, the usefulness of JavaScript varied greatly and seemed to be tilted toward adding animated snowflakes to your web pages or dynamic clocks that told the time in the status bar. Suffice it to say, I didn’t really pay much attention to JavaScript in the early part of my career because of the novelty of the implementations that I often found on the Internet. 7 | 8 | It wasn’t until 2005 that I first rediscovered JavaScript as a real programming language that I needed to pay closer attention to. After digging into the first beta release of Google Maps, I was hooked on the potential it had. At the time, Google Maps was a first-of-its-kind application -- it allowed you to move a map around with your mouse, zoom in and out, and make server requests without reloading the page -- all with JavaScript. It seemed like magic! 9 | 10 | When anything seems like magic, it is usually a good indication you are at the dawn of a new way of doing things. And boy, was I not wrong -- fast-forwarding to today, I would say that JavaScript is one of the primary languages I use for both client- and server-side programming, and I wouldn’t have it any other way. 11 | 12 | One of my regrets as I look over the past 15 years is that I didn’t give JavaScript more of a chance before 2005, or more accurately, that I lacked the foresight to see JavaScript as a true programming language that is just as useful as C++, C#, Java, and many others. 13 | 14 | If I had this *You Don’t Know JS* series of books at the start of my career, my career history would look much different than it does today. And that is one of the things I love about this series: it explains JS at a level that builds your understanding as you go through the series, but in a fun and informative way. 15 | 16 | *this & Object Prototypes* is a wonderful continuation to the series. It does a great and natural job of building on the prior book, Scope & Closures, and extending that knowledge to a very important part of the JS language, the `this` keyword and prototypes. These two simple things are pivotal for what you will learn in the future books, because they are foundational to doing real programming with JavaScript. The concept of how to create objects, relate them, and extend them to represent things in your application is necessary to create large and complex applications in JavaScript. And without them, creating complex applications (such as Google Maps) wouldn’t be possible in JavaScript. 17 | 18 | I would say that the vast majority of web developers probably have never built a JavaScript object and just treat the language as event-binding glue between buttons and AJAX requests. I was in that camp at a point in my career, but after I learned how to master prototypes and create objects in JavaScript, a world of possibilities opened up for me. If you fall into the category of just creating event-binding glue code, this book is a must-read; if you just need a refresher, this book will be a go-to resource for you. Either way, you will not be disappointed. Trust me! 19 | 20 | Nick Berardi
21 | [nickberardi.com](http://nickberardi.com), [@nberardi](http://twitter.com/nberardi) 22 | -------------------------------------------------------------------------------- /scope & closures/apC.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: Scope & Closures 2 | # Appendix C: Lexical-this 3 | 4 | Though this title does not address the `this` mechanism in any detail, there's one ES6 topic which relates `this` to lexical scope in an important way, which we will quickly examine. 5 | 6 | ES6 adds a special syntactic form of function declaration called the "arrow function". It looks like this: 7 | 8 | ```js 9 | var foo = a => { 10 | console.log( a ); 11 | }; 12 | 13 | foo( 2 ); // 2 14 | ``` 15 | 16 | The so-called "fat arrow" is often mentioned as a short-hand for the *tediously verbose* (sarcasm) `function` keyword. 17 | 18 | But there's something much more important going on with arrow-functions that has nothing to do with saving keystrokes in your declaration. 19 | 20 | Briefly, this code suffers a problem: 21 | 22 | ```js 23 | 24 | var obj = { 25 | id: "awesome", 26 | cool: function coolFn() { 27 | console.log( this.id ); 28 | } 29 | }; 30 | 31 | var id = "not awesome"; 32 | 33 | obj.cool(); // awesome 34 | 35 | setTimeout( obj.cool, 100 ); // not awesome 36 | ``` 37 | 38 | The problem is the loss of `this` binding on the `cool()` function. There are various ways to address that problem, but one often-repeated solution is `var self = this;`. 39 | 40 | That might look like: 41 | 42 | ```js 43 | var obj = { 44 | count: 0, 45 | cool: function coolFn() { 46 | var self = this; 47 | 48 | if (self.count < 1) { 49 | setTimeout( function timer(){ 50 | self.count++; 51 | console.log( "awesome?" ); 52 | }, 100 ); 53 | } 54 | } 55 | }; 56 | 57 | obj.cool(); // awesome? 58 | ``` 59 | 60 | Without getting too much into the weeds here, the `var self = this` "solution" just dispenses with the whole problem of understanding and properly using `this` binding, and instead falls back to something we're perhaps more comfortable with: lexical scope. `self` becomes just an identifier that can be resolved via lexical scope and closure, and cares not what happened to the `this` binding along the way. 61 | 62 | People don't like writing verbose stuff, especially when they do it over and over again. So, a motivation of ES6 is to help alleviate these scenarios, and indeed, *fix* common idiom problems, such as this one. 63 | 64 | The ES6 solution, the arrow-function, introduces a behavior called "lexical this". 65 | 66 | ```js 67 | var obj = { 68 | count: 0, 69 | cool: function coolFn() { 70 | if (this.count < 1) { 71 | setTimeout( () => { // arrow-function ftw? 72 | this.count++; 73 | console.log( "awesome?" ); 74 | }, 100 ); 75 | } 76 | } 77 | }; 78 | 79 | obj.cool(); // awesome? 80 | ``` 81 | 82 | The short explanation is that arrow-functions do not behave at all like normal functions when it comes to their `this` binding. They discard all the normal rules for `this` binding, and instead take on the `this` value of their immediate lexical enclosing scope, whatever it is. 83 | 84 | So, in that snippet, the arrow-function doesn't get its `this` unbound in some unpredictable way, it just "inherits" the `this` binding of the `cool()` function (which is correct if we invoke it as shown!). 85 | 86 | While this makes for shorter code, my perspective is that arrow-functions are really just codifying into the language syntax a common *mistake* of developers, which is to confuse and conflate "this binding" rules with "lexical scope" rules. 87 | 88 | Put another way: why go to the trouble and verbosity of using the `this` style coding paradigm, only to cut it off at the knees by mixing it with lexical references. It seems natural to embrace one approach or the other for any given piece of code, and not mix them in the same piece of code. 89 | 90 | **Note:** one other detraction from arrow-functions is that they are anonymous, not named. See Chapter 3 for the reasons why anonymous functions are less desirable than named functions. 91 | 92 | A more appropriate approach, in my perspective, to this "problem", is to use and embrace the `this` mechanism correctly. 93 | 94 | ```js 95 | var obj = { 96 | count: 0, 97 | cool: function coolFn() { 98 | if (this.count < 1) { 99 | setTimeout( function timer(){ 100 | this.count++; // `this` is safe because of `bind(..)` 101 | console.log( "more awesome" ); 102 | }.bind( this ), 100 ); // look, `bind()`! 103 | } 104 | } 105 | }; 106 | 107 | obj.cool(); // more awesome 108 | ``` 109 | 110 | Whether you prefer the new lexical-this behavior of arrow-functions, or you prefer the tried-and-true `bind()`, it's important to note that arrow-functions are **not** just about less typing of "function". 111 | 112 | They have an *intentional behavioral difference* that we should learn and understand, and if we so choose, leverage. 113 | 114 | Now that we fully understand lexical scoping (and closure!), understanding lexical-this should be a breeze! 115 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS (book series) 2 | 3 | This is a series of books diving deep into the core mechanisms of the JavaScript language. The first edition of the series is now complete. 4 | 5 |   6 |   7 |   8 |   9 |   10 | 11 | 12 | Please feel free to contribute to the quality of this content by submitting PR's for improvements to code snippets, explanations, etc. While typo fixes are welcomed, they will likely be caught through normal editing processes, and are thus not necessarily as important for this repository. 13 | 14 | **To read more about the motivations and perspective behind this book series, check out the [Preface](preface.md).** 15 | 16 | ## Titles 17 | 18 | * Read online (free!): ["Up & Going"](up\%20&\%20going/README.md#you-dont-know-js-up--going), Published: [Buy Now](http://www.ebooks.com/1993212/you-don-t-know-js-up-going/simpson-kyle/) in print, but the ebook format is free! 19 | * Read online (free!): ["Scope & Closures"](scope\%20&\%20closures/README.md#you-dont-know-js-scope--closures), Published: [Buy Now](http://www.ebooks.com/1647631/you-don-t-know-js-scope-closures/simpson-kyle/) 20 | * Read online (free!): ["this & Object Prototypes"](this\%20&\%20object\%20prototypes/README.md#you-dont-know-js-this--object-prototypes), Published: [Buy Now](http://www.ebooks.com/1734321/you-don-t-know-js-this-object-prototypes/simpson-kyle/) 21 | * Read online (free!): ["Types & Grammar"](types\%20&\%20grammar/README.md#you-dont-know-js-types--grammar), Published: [Buy Now](http://www.ebooks.com/1935541/you-don-t-know-js-types-grammar/simpson-kyle/) 22 | * Read online (free!): ["Async & Performance"](async\%20&\%20performance/README.md#you-dont-know-js-async--performance), Published: [Buy Now](http://www.ebooks.com/1977375/you-don-t-know-js-async-performance/simpson-kyle/) 23 | * Read online (free!): ["ES6 & Beyond"](es6\%20&\%20beyond/README.md#you-dont-know-js-es6--beyond), Published: [Buy Now](http://www.ebooks.com/2481820/you-don-t-know-js-es6-beyond/simpson-kyle/) 24 | 25 | ## Publishing 26 | 27 | These books are being released here as drafts, free to read, but are also being edited, produced, and published through O'Reilly. 28 | 29 | If you like the content you find here, and want to support more content like it, please purchase the books once they are available for sale, through your normal book sources. :) 30 | 31 | If you'd like to contribute financially towards the effort (or any of my other OSS work) aside from purchasing the books, I do have a [patreon](https://www.patreon.com/getify) that I would always appreciate your generosity towards. 32 | 33 | [![patreon.png](https://s11.postimg.org/axpzguh77/patreon.png)](https://www.patreon.com/getify) 34 | 35 | ## In-person Training 36 | 37 | The content for these books derives heavily from a series of training materials I teach professionally (in both public and private-corporate workshop format): "Deep JavaScript Foundations", "Rethinking Async", and "ES6: The Right Parts" workshops. 38 | 39 | If you like this content and would like to contact me regarding conducting training on these, or other various JS/HTML5/node.js topics, please reach out to me through email: getify @ gmail 40 | 41 | ## Online Video Training 42 | 43 | I also have some JS training material available in on-demand video format. I teach courses through [Frontend Masters](https://FrontendMasters.com), like my [Deep JavaScript Foundations](https://frontendmasters.com/courses/javascript-foundations/) workshop. You can find [all my courses here](https://frontendmasters.com/kyle-simpson/). 44 | 45 | Some of those courses are also distributed on other platforms, like Pluralsight, Lynda.com, and O'Reilly Safari Online. 46 | 47 | ## Contributions 48 | 49 | Any contributions you make to this effort **are of course greatly appreciated**. 50 | 51 | But **PLEASE** read the [Contributions Guidelines](CONTRIBUTING.md) carefully before submitting a PR. 52 | 53 | ## License & Copyright 54 | 55 | The materials herein are all (c) 2013-2017 Kyle Simpson. 56 | 57 | Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 4.0 Unported License. 58 | -------------------------------------------------------------------------------- /preface.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS 2 | # Preface 3 | 4 | I'm sure you noticed, but "JS" in the book series title is not an abbreviation for words used to curse about JavaScript, though cursing at the language's quirks is something we can probably all identify with! 5 | 6 | From the earliest days of the web, JavaScript has been a foundational technology that drives interactive experience around the content we consume. While flickering mouse trails and annoying pop-up prompts may be where JavaScript started, nearly 2 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. 7 | 8 | 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". 9 | 10 | Because JavaScript borrows concepts and syntax idioms from several languages, including proud C-style procedural roots as well as subtle, less obvious Scheme/Lisp-style functional roots, it is exceedingly approachable to a broad audience of developers, even those with just 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. 11 | 12 | While JavaScript is perhaps one of the easiest languages to get up and running with, its eccentricities make solid mastery of the language a vastly less common occurrence than in many other languages. 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. 13 | 14 | Sophisticated concepts which 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 JavaScript developer to just use the language as-is and not worry too much about what's going on under the hood. 15 | 16 | It is simultaneously a simple, easy-to-use language that has broad appeal, and a complex and nuanced collection of language mechanics which without careful study will elude *true understanding* even for the most seasoned of JavaScript developers. 17 | 18 | Therein lies the paradox of JavaScript, the Achilles' Heel of the language, the challenge we are presently addressing. Because JavaScript *can* be used without understanding, the understanding of the language is often never attained. 19 | 20 | ## Mission 21 | 22 | If at every point that you encounter a surprise or frustration in JavaScript, your response is to add it to the blacklist, as some are accustomed to doing, you soon will be relegated to a hollow shell of the richness of JavaScript. 23 | 24 | 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". 25 | 26 | This *You Don't Know JavaScript* book series offers a contrary challenge: learn and deeply understand *all* of JavaScript, even and especially "The Tough Parts". 27 | 28 | 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. Furthermore, we eschew the common advice to *retreat* when the road gets rough. 29 | 30 | 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 JavaScript is and can do. With that knowledge, no technique, no framework, no popular buzzword acronym of the week, will be beyond your understanding. 31 | 32 | These books each take on specific core parts of the language which are most commonly misunderstood or under-understood, and dive very deep and exhaustively into them. You should come away from reading with a firm confidence in your understanding, not just of the theoretical, but the practical "what you need to know" bits. 33 | 34 | 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. 35 | 36 | ## Summary 37 | 38 | 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*. 39 | 40 | Note: 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. 41 | -------------------------------------------------------------------------------- /scope & closures/apB.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: Scope & Closures 2 | # Appendix B: Polyfilling Block Scope 3 | 4 | In Chapter 3, we explored Block Scope. We saw that `with` and the `catch` clause are both tiny examples of block scope that have existed in JavaScript since at least the introduction of ES3. 5 | 6 | But it's ES6's introduction of `let` that finally gives full, unfettered block-scoping capability to our code. There are many exciting things, both functionally and code-stylistically, that block scope will enable. 7 | 8 | But what if we wanted to use block scope in pre-ES6 environments? 9 | 10 | Consider this code: 11 | 12 | ```js 13 | { 14 | let a = 2; 15 | console.log( a ); // 2 16 | } 17 | 18 | console.log( a ); // ReferenceError 19 | ``` 20 | 21 | This will work great in ES6 environments. But can we do so pre-ES6? `catch` is the answer. 22 | 23 | ```js 24 | try{throw 2}catch(a){ 25 | console.log( a ); // 2 26 | } 27 | 28 | console.log( a ); // ReferenceError 29 | ``` 30 | 31 | Whoa! That's some ugly, weird looking code. We see a `try/catch` that appears to forcibly throw an error, but the "error" it throws is just a value `2`, and then the variable declaration that receives it is in the `catch(a)` clause. Mind: blown. 32 | 33 | That's right, the `catch` clause has block-scoping to it, which means it can be used as a polyfill for block scope in pre-ES6 environments. 34 | 35 | "But...", you say. "...no one wants to write ugly code like that!" That's true. No one writes (some of) the code output by the CoffeeScript compiler, either. That's not the point. 36 | 37 | The point is that tools can transpile ES6 code to work in pre-ES6 environments. You can write code using block-scoping, and benefit from such functionality, and let a build-step tool take care of producing code that will actually *work* when deployed. 38 | 39 | This is actually the preferred migration path for all (ahem, most) of ES6: to use a code transpiler to take ES6 code and produce ES5-compatible code during the transition from pre-ES6 to ES6. 40 | 41 | ## Traceur 42 | 43 | Google maintains a project called "Traceur" [^note-traceur], which is exactly tasked with transpiling ES6 features into pre-ES6 (mostly ES5, but not all!) for general usage. The TC39 committee relies on this tool (and others) to test out the semantics of the features they specify. 44 | 45 | What does Traceur produce from our snippet? You guessed it! 46 | 47 | ```js 48 | { 49 | try { 50 | throw undefined; 51 | } catch (a) { 52 | a = 2; 53 | console.log( a ); 54 | } 55 | } 56 | 57 | console.log( a ); 58 | ``` 59 | 60 | So, with the use of such tools, we can start taking advantage of block scope regardless of if we are targeting ES6 or not, because `try/catch` has been around (and worked this way) from ES3 days. 61 | 62 | ## Implicit vs. Explicit Blocks 63 | 64 | In Chapter 3, we identified some potential pitfalls to code maintainability/refactorability when we introduce block-scoping. Is there another way to take advantage of block scope but to reduce this downside? 65 | 66 | Consider this alternate form of `let`, called the "let block" or "let statement" (contrasted with "let declarations" from before). 67 | 68 | ```js 69 | let (a = 2) { 70 | console.log( a ); // 2 71 | } 72 | 73 | console.log( a ); // ReferenceError 74 | ``` 75 | 76 | Instead of implicitly hijacking an existing block, the let-statement creates an explicit block for its scope binding. Not only does the explicit block stand out more, and perhaps fare more robustly in code refactoring, it produces somewhat cleaner code by, grammatically, forcing all the declarations to the top of the block. This makes it easier to look at any block and know what's scoped to it and not. 77 | 78 | As a pattern, it mirrors the approach many people take in function-scoping when they manually move/hoist all their `var` declarations to the top of the function. The let-statement puts them there at the top of the block by intent, and if you don't use `let` declarations strewn throughout, your block-scoping declarations are somewhat easier to identify and maintain. 79 | 80 | But, there's a problem. The let-statement form is not included in ES6. Neither does the official Traceur compiler accept that form of code. 81 | 82 | We have two options. We can format using ES6-valid syntax and a little sprinkle of code discipline: 83 | 84 | ```js 85 | /*let*/ { let a = 2; 86 | console.log( a ); 87 | } 88 | 89 | console.log( a ); // ReferenceError 90 | ``` 91 | 92 | But, tools are meant to solve our problems. So the other option is to write explicit let statement blocks, and let a tool convert them to valid, working code. 93 | 94 | So, I built a tool called "let-er" [^note-let_er] to address just this issue. *let-er* is a build-step code transpiler, but its only task is to find let-statement forms and transpile them. It will leave alone any of the rest of your code, including any let-declarations. You can safely use *let-er* as the first ES6 transpiler step, and then pass your code through something like Traceur if necessary. 95 | 96 | Moreover, *let-er* has a configuration flag `--es6`, which when turned on (off by default), changes the kind of code produced. Instead of the `try/catch` ES3 polyfill hack, *let-er* would take our snippet and produce the fully ES6-compliant, non-hacky: 97 | 98 | ```js 99 | { 100 | let a = 2; 101 | console.log( a ); 102 | } 103 | 104 | console.log( a ); // ReferenceError 105 | ``` 106 | 107 | So, you can start using *let-er* right away, and target all pre-ES6 environments, and when you only care about ES6, you can add the flag and instantly target only ES6. 108 | 109 | And most importantly, **you can use the more preferable and more explicit let-statement form** even though it is not an official part of any ES version (yet). 110 | 111 | ## Performance 112 | 113 | Let me add one last quick note on the performance of `try/catch`, and/or to address the question, "why not just use an IIFE to create the scope?" 114 | 115 | Firstly, the performance of `try/catch` *is* slower, but there's no reasonable assumption that it *has* to be that way, or even that it *always will be* that way. Since the official TC39-approved ES6 transpiler uses `try/catch`, the Traceur team has asked Chrome to improve the performance of `try/catch`, and they are obviously motivated to do so. 116 | 117 | Secondly, IIFE is not a fair apples-to-apples comparison with `try/catch`, because a function wrapped around any arbitrary code changes the meaning, inside of that code, of `this`, `return`, `break`, and `continue`. IIFE is not a suitable general substitute. It could only be used manually in certain cases. 118 | 119 | The question really becomes: do you want block-scoping, or not. If you do, these tools provide you that option. If not, keep using `var` and go on about your coding! 120 | 121 | [^note-traceur]: [Google Traceur](http://traceur-compiler.googlecode.com/git/demo/repl.html) 122 | 123 | [^note-let_er]\: [let-er](https://github.com/getify/let-er) 124 | -------------------------------------------------------------------------------- /scope & closures/ch4.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: Scope & Closures 2 | # Chapter 4: Hoisting 3 | 4 | By now, you should be fairly comfortable with the idea of scope, and how variables are attached to different levels of scope depending on where and how they are declared. Both function scope and block scope behave by the same rules in this regard: any variable declared within a scope is attached to that scope. 5 | 6 | But there's a subtle detail of how scope attachment works with declarations that appear in various locations within a scope, and that detail is what we will examine here. 7 | 8 | ## Chicken Or The Egg? 9 | 10 | There's a temptation to think that all of the code you see in a JavaScript program is interpreted line-by-line, top-down in order, as the program executes. While that is substantially true, there's one part of that assumption which can lead to incorrect thinking about your program. 11 | 12 | Consider this code: 13 | 14 | ```js 15 | a = 2; 16 | 17 | var a; 18 | 19 | console.log( a ); 20 | ``` 21 | 22 | What do you expect to be printed in the `console.log(..)` statement? 23 | 24 | Many developers would expect `undefined`, since the `var a` statement comes after the `a = 2`, and it would seem natural to assume that the variable is re-defined, and thus assigned the default `undefined`. However, the output will be `2`. 25 | 26 | Consider another piece of code: 27 | 28 | ```js 29 | console.log( a ); 30 | 31 | var a = 2; 32 | ``` 33 | 34 | You might be tempted to assume that, since the previous snippet exhibited some less-than-top-down looking behavior, perhaps in this snippet, `2` will also be printed. Others may think that since the `a` variable is used before it is declared, this must result in a `ReferenceError` being thrown. 35 | 36 | Unfortunately, both guesses are incorrect. `undefined` is the output. 37 | 38 | **So, what's going on here?** It would appear we have a chicken-and-the-egg question. Which comes first, the declaration ("egg"), or the assignment ("chicken")? 39 | 40 | ## The Compiler Strikes Again 41 | 42 | To answer this question, we need to refer back to Chapter 1, and our discussion of compilers. Recall that the *Engine* actually will compile your JavaScript code before it interprets it. Part of the compilation phase was to find and associate all declarations with their appropriate scopes. Chapter 2 showed us that this is the heart of Lexical Scope. 43 | 44 | So, the best way to think about things is that all declarations, both variables and functions, are processed first, before any part of your code is executed. 45 | 46 | When you see `var a = 2;`, you probably think of that as one statement. But JavaScript actually thinks of it as two statements: `var a;` and `a = 2;`. The first statement, the declaration, is processed during the compilation phase. The second statement, the assignment, is left **in place** for the execution phase. 47 | 48 | Our first snippet then should be thought of as being handled like this: 49 | 50 | ```js 51 | var a; 52 | ``` 53 | ```js 54 | a = 2; 55 | 56 | console.log( a ); 57 | ``` 58 | 59 | ...where the first part is the compilation and the second part is the execution. 60 | 61 | Similarly, our second snippet is actually processed as: 62 | 63 | ```js 64 | var a; 65 | ``` 66 | ```js 67 | console.log( a ); 68 | 69 | a = 2; 70 | ``` 71 | 72 | So, one way of thinking, sort of metaphorically, about this process, is that variable and function declarations are "moved" from where they appear in the flow of the code to the top of the code. This gives rise to the name "Hoisting". 73 | 74 | In other words, **the egg (declaration) comes before the chicken (assignment)**. 75 | 76 | **Note:** Only the declarations themselves are hoisted, while any assignments or other executable logic are left *in place*. If hoisting were to re-arrange the executable logic of our code, that could wreak havoc. 77 | 78 | ```js 79 | foo(); 80 | 81 | function foo() { 82 | console.log( a ); // undefined 83 | 84 | var a = 2; 85 | } 86 | ``` 87 | 88 | The function `foo`'s declaration (which in this case *includes* the implied value of it as an actual function) is hoisted, such that the call on the first line is able to execute. 89 | 90 | It's also important to note that hoisting is **per-scope**. So while our previous snippets were simplified in that they only included global scope, the `foo(..)` function we are now examining itself exhibits that `var a` is hoisted to the top of `foo(..)` (not, obviously, to the top of the program). So the program can perhaps be more accurately interpreted like this: 91 | 92 | ```js 93 | function foo() { 94 | var a; 95 | 96 | console.log( a ); // undefined 97 | 98 | a = 2; 99 | } 100 | 101 | foo(); 102 | ``` 103 | 104 | Function declarations are hoisted, as we just saw. But function expressions are not. 105 | 106 | ```js 107 | foo(); // not ReferenceError, but TypeError! 108 | 109 | var foo = function bar() { 110 | // ... 111 | }; 112 | ``` 113 | 114 | The variable identifier `foo` is hoisted and attached to the enclosing scope (global) of this program, so `foo()` doesn't fail as a `ReferenceError`. But `foo` has no value yet (as it would if it had been a true function declaration instead of expression). So, `foo()` is attempting to invoke the `undefined` value, which is a `TypeError` illegal operation. 115 | 116 | Also recall that even though it's a named function expression, the name identifier is not available in the enclosing scope: 117 | 118 | ```js 119 | foo(); // TypeError 120 | bar(); // ReferenceError 121 | 122 | var foo = function bar() { 123 | // ... 124 | }; 125 | ``` 126 | 127 | This snippet is more accurately interpreted (with hoisting) as: 128 | 129 | ```js 130 | var foo; 131 | 132 | foo(); // TypeError 133 | bar(); // ReferenceError 134 | 135 | foo = function() { 136 | var bar = ...self... 137 | // ... 138 | } 139 | ``` 140 | 141 | ## Functions First 142 | 143 | Both function declarations and variable declarations are hoisted. But a subtle detail (that *can* show up in code with multiple "duplicate" declarations) is that functions are hoisted first, and then variables. 144 | 145 | Consider: 146 | 147 | ```js 148 | foo(); // 1 149 | 150 | var foo; 151 | 152 | function foo() { 153 | console.log( 1 ); 154 | } 155 | 156 | foo = function() { 157 | console.log( 2 ); 158 | }; 159 | ``` 160 | 161 | `1` is printed instead of `2`! This snippet is interpreted by the *Engine* as: 162 | 163 | ```js 164 | function foo() { 165 | console.log( 1 ); 166 | } 167 | 168 | foo(); // 1 169 | 170 | foo = function() { 171 | console.log( 2 ); 172 | }; 173 | ``` 174 | 175 | Notice that `var foo` was the duplicate (and thus ignored) declaration, even though it came before the `function foo()...` declaration, because function declarations are hoisted before normal variables. 176 | 177 | While multiple/duplicate `var` declarations are effectively ignored, subsequent function declarations *do* override previous ones. 178 | 179 | ```js 180 | foo(); // 3 181 | 182 | function foo() { 183 | console.log( 1 ); 184 | } 185 | 186 | var foo = function() { 187 | console.log( 2 ); 188 | }; 189 | 190 | function foo() { 191 | console.log( 3 ); 192 | } 193 | ``` 194 | 195 | While this all may sound like nothing more than interesting academic trivia, it highlights the fact that duplicate definitions in the same scope are a really bad idea and will often lead to confusing results. 196 | 197 | Function declarations that appear inside of normal blocks typically hoist to the enclosing scope, rather than being conditional as this code implies: 198 | 199 | ```js 200 | foo(); // "b" 201 | 202 | var a = true; 203 | if (a) { 204 | function foo() { console.log( "a" ); } 205 | } 206 | else { 207 | function foo() { console.log( "b" ); } 208 | } 209 | ``` 210 | 211 | However, it's important to note that this behavior is not reliable and is subject to change in future versions of JavaScript, so it's probably best to avoid declaring functions in blocks. 212 | 213 | ## Review (TL;DR) 214 | 215 | We can be tempted to look at `var a = 2;` as one statement, but the JavaScript *Engine* does not see it that way. It sees `var a` and `a = 2` as two separate statements, the first one a compiler-phase task, and the second one an execution-phase task. 216 | 217 | What this leads to is that all declarations in a scope, regardless of where they appear, are processed *first* before the code itself is executed. You can visualize this as declarations (variables and functions) being "moved" to the top of their respective scopes, which we call "hoisting". 218 | 219 | Declarations themselves are hoisted, but assignments, even assignments of function expressions, are *not* hoisted. 220 | 221 | Be careful about duplicate declarations, especially mixed between normal var declarations and function declarations -- peril awaits if you do! 222 | -------------------------------------------------------------------------------- /types & grammar/apB.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: Types & Grammar 2 | # Appendix B: Acknowledgments 3 | 4 | I have many people to thank for making this book title and the overall series happen. 5 | 6 | First, I must thank my wife Christen Simpson, and my two kids Ethan and Emily, for putting up with Dad always pecking away at the computer. Even when not writing books, my obsession with JavaScript glues my eyes to the screen far more than it should. That time I borrow from my family is the reason these books can so deeply and completely explain JavaScript to you, the reader. I owe my family everything. 7 | 8 | I'd like to thank my editors at O'Reilly, namely Simon St.Laurent and Brian MacDonald, as well as the rest of the editorial and marketing staff. They are fantastic to work with, and have been especially accommodating during this experiment into "open source" book writing, editing, and production. 9 | 10 | Thank you to the many folks who have participated in making this book series better by providing editorial suggestions and corrections, including Shelley Powers, Tim Ferro, Evan Borden, Forrest L. Norvell, Jennifer Davis, Jesse Harlin, and many others. A big thank you to David Walsh for writing the Foreword for this title. 11 | 12 | Thank you to the countless folks in the community, including members of the TC39 committee, who have shared so much knowledge with the rest of us, and especially tolerated my incessant questions and explorations with patience and detail. John-David Dalton, Juriy "kangax" Zaytsev, Mathias Bynens, Axel Rauschmayer, Nicholas Zakas, Angus Croll, Reginald Braithwaite, Dave Herman, Brendan Eich, Allen Wirfs-Brock, Bradley Meck, Domenic Denicola, David Walsh, Tim Disney, Peter van der Zee, Andrea Giammarchi, Kit Cambridge, Eric Elliott, and so many others, I can't even scratch the surface. 13 | 14 | The *You Don't Know JS* book series was born on Kickstarter, so I also wish to thank all my (nearly) 500 generous backers, without whom this book series could not have happened: 15 | 16 | > Jan Szpila, nokiko, Murali Krishnamoorthy, Ryan Joy, Craig Patchett, pdqtrader, Dale Fukami, ray hatfield, R0drigo Perez [Mx], Dan Petitt, Jack Franklin, Andrew Berry, Brian Grinstead, Rob Sutherland, Sergi Meseguer, Phillip Gourley, Mark Watson, Jeff Carouth, Alfredo Sumaran, Martin Sachse, Marcio Barrios, Dan, AimelyneM, Matt Sullivan, Delnatte Pierre-Antoine, Jake Smith, Eugen Tudorancea, Iris, David Trinh, simonstl, Ray Daly, Uros Gruber, Justin Myers, Shai Zonis, Mom & Dad, Devin Clark, Dennis Palmer, Brian Panahi Johnson, Josh Marshall, Marshall, Dennis Kerr, Matt Steele, Erik Slagter, Sacah, Justin Rainbow, Christian Nilsson, Delapouite, D.Pereira, Nicolas Hoizey, George V. Reilly, Dan Reeves, Bruno Laturner, Chad Jennings, Shane King, Jeremiah Lee Cohick, od3n, Stan Yamane, Marko Vucinic, Jim B, Stephen Collins, Ægir Þorsteinsson, Eric Pederson, Owain, Nathan Smith, Jeanetteurphy, Alexandre ELISÉ, Chris Peterson, Rik Watson, Luke Matthews, Justin Lowery, Morten Nielsen, Vernon Kesner, Chetan Shenoy, Paul Tregoing, Marc Grabanski, Dion Almaer, Andrew Sullivan, Keith Elsass, Tom Burke, Brian Ashenfelter, David Stuart, Karl Swedberg, Graeme, Brandon Hays, John Christopher, Gior, manoj reddy, Chad Smith, Jared Harbour, Minoru TODA, Chris Wigley, Daniel Mee, Mike, Handyface, Alex Jahraus, Carl Furrow, Rob Foulkrod, Max Shishkin, Leigh Penny Jr., Robert Ferguson, Mike van Hoenselaar, Hasse Schougaard, rajan venkataguru, Jeff Adams, Trae Robbins, Rolf Langenhuijzen, Jorge Antunes, Alex Koloskov, Hugh Greenish, Tim Jones, Jose Ochoa, Michael Brennan-White, Naga Harish Muvva, Barkóczi Dávid, Kitt Hodsden, Paul McGraw, Sascha Goldhofer, Andrew Metcalf, Markus Krogh, Michael Mathews, Matt Jared, Juanfran, Georgie Kirschner, Kenny Lee, Ted Zhang, Amit Pahwa, Inbal Sinai, Dan Raine, Schabse Laks, Michael Tervoort, Alexandre Abreu, Alan Joseph Williams, NicolasD, Cindy Wong, Reg Braithwaite, LocalPCGuy, Jon Friskics, Chris Merriman, John Pena, Jacob Katz, Sue Lockwood, Magnus Johansson, Jeremy Crapsey, Grzegorz Pawłowski, nico nuzzaci, Christine Wilks, Hans Bergren, charles montgomery, Ariel בר-לבב Fogel, Ivan Kolev, Daniel Campos, Hugh Wood, Christian Bradford, Frédéric Harper, Ionuţ Dan Popa, Jeff Trimble, Rupert Wood, Trey Carrico, Pancho Lopez, Joël kuijten, Tom A Marra, Jeff Jewiss, Jacob Rios, Paolo Di Stefano, Soledad Penades, Chris Gerber, Andrey Dolganov, Wil Moore III, Thomas Martineau, Kareem, Ben Thouret, Udi Nir, Morgan Laupies, jory carson-burson, Nathan L Smith, Eric Damon Walters, Derry Lozano-Hoyland, Geoffrey Wiseman, mkeehner, KatieK, Scott MacFarlane, Brian LaShomb, Adrien Mas, christopher ross, Ian Littman, Dan Atkinson, Elliot Jobe, Nick Dozier, Peter Wooley, John Hoover, dan, Martin A. Jackson, Héctor Fernando Hurtado, andy ennamorato, Paul Seltmann, Melissa Gore, Dave Pollard, Jack Smith, Philip Da Silva, Guy Israeli, @megalithic, Damian Crawford, Felix Gliesche, April Carter Grant, Heidi, jim tierney, Andrea Giammarchi, Nico Vignola, Don Jones, Chris Hartjes, Alex Howes, john gibbon, David J. Groom, BBox, Yu 'Dilys' Sun, Nate Steiner, Brandon Satrom, Brian Wyant, Wesley Hales, Ian Pouncey, Timothy Kevin Oxley, George Terezakis, sanjay raj, Jordan Harband, Marko McLion, Wolfgang Kaufmann, Pascal Peuckert, Dave Nugent, Markus Liebelt, Welling Guzman, Nick Cooley, Daniel Mesquita, Robert Syvarth, Chris Coyier, Rémy Bach, Adam Dougal, Alistair Duggin, David Loidolt, Ed Richer, Brian Chenault, GoldFire Studios, Carles Andrés, Carlos Cabo, Yuya Saito, roberto ricardo, Barnett Klane, Mike Moore, Kevin Marx, Justin Love, Joe Taylor, Paul Dijou, Michael Kohler, Rob Cassie, Mike Tierney, Cody Leroy Lindley, tofuji, Shimon Schwartz, Raymond, Luc De Brouwer, David Hayes, Rhys Brett-Bowen, Dmitry, Aziz Khoury, Dean, Scott Tolinski - Level Up, Clement Boirie, Djordje Lukic, Anton Kotenko, Rafael Corral, Philip Hurwitz, Jonathan Pidgeon, Jason Campbell, Joseph C., SwiftOne, Jan Hohner, Derick Bailey, getify, Daniel Cousineau, Chris Charlton, Eric Turner, David Turner, Joël Galeran, Dharma Vagabond, adam, Dirk van Bergen, dave ♥♫★ furf, Vedran Zakanj, Ryan McAllen, Natalie Patrice Tucker, Eric J. Bivona, Adam Spooner, Aaron Cavano, Kelly Packer, Eric J, Martin Drenovac, Emilis, Michael Pelikan, Scott F. Walter, Josh Freeman, Brandon Hudgeons, vijay chennupati, Bill Glennon, Robin R., Troy Forster, otaku_coder, Brad, Scott, Frederick Ostrander, Adam Brill, Seb Flippence, Michael Anderson, Jacob, Adam Randlett, Standard, Joshua Clanton, Sebastian Kouba, Chris Deck, SwordFire, Hannes Papenberg, Richard Woeber, hnzz, Rob Crowther, Jedidiah Broadbent, Sergey Chernyshev, Jay-Ar Jamon, Ben Combee, luciano bonachela, Mark Tomlinson, Kit Cambridge, Michael Melgares, Jacob Adams, Adrian Bruinhout, Bev Wieber, Scott Puleo, Thomas Herzog, April Leone, Daniel Mizieliński, Kees van Ginkel, Jon Abrams, Erwin Heiser, Avi Laviad, David newell, Jean-Francois Turcot, Niko Roberts, Erik Dana, Charles Neill, Aaron Holmes, Grzegorz Ziółkowski, Nathan Youngman, Timothy, Jacob Mather, Michael Allan, Mohit Seth, Ryan Ewing, Benjamin Van Treese, Marcelo Santos, Denis Wolf, Phil Keys, Chris Yung, Timo Tijhof, Martin Lekvall, Agendine, Greg Whitworth, Helen Humphrey, Dougal Campbell, Johannes Harth, Bruno Girin, Brian Hough, Darren Newton, Craig McPheat, Olivier Tille, Dennis Roethig, Mathias Bynens, Brendan Stromberger, sundeep, John Meyer, Ron Male, John F Croston III, gigante, Carl Bergenhem, B.J. May, Rebekah Tyler, Ted Foxberry, Jordan Reese, Terry Suitor, afeliz, Tom Kiefer, Darragh Duffy, Kevin Vanderbeken, Andy Pearson, Simon Mac Donald, Abid Din, Chris Joel, Tomas Theunissen, David Dick, Paul Grock, Brandon Wood, John Weis, dgrebb, Nick Jenkins, Chuck Lane, Johnny Megahan, marzsman, Tatu Tamminen, Geoffrey Knauth, Alexander Tarmolov, Jeremy Tymes, Chad Auld, Sean Parmelee, Rob Staenke, Dan Bender, Yannick derwa, Joshua Jones, Geert Plaisier, Tom LeZotte, Christen Simpson, Stefan Bruvik, Justin Falcone, Carlos Santana, Michael Weiss, Pablo Villoslada, Peter deHaan, Dimitris Iliopoulos, seyDoggy, Adam Jordens, Noah Kantrowitz, Amol M, Matthew Winnard, Dirk Ginader, Phinam Bui, David Rapson, Andrew Baxter, Florian Bougel, Michael George, Alban Escalier, Daniel Sellers, Sasha Rudan, John Green, Robert Kowalski, David I. Teixeira (@ditma, Charles Carpenter, Justin Yost, Sam S, Denis Ciccale, Kevin Sheurs, Yannick Croissant, Pau Fracés, Stephen McGowan, Shawn Searcy, Chris Ruppel, Kevin Lamping, Jessica Campbell, Christopher Schmitt, Sablons, Jonathan Reisdorf, Bunni Gek, Teddy Huff, Michael Mullany, Michael Fürstenberg, Carl Henderson, Rick Yoesting, Scott Nichols, Hernán Ciudad, Andrew Maier, Mike Stapp, Jesse Shawl, Sérgio Lopes, jsulak, Shawn Price, Joel Clermont, Chris Ridmann, Sean Timm, Jason Finch, Aiden Montgomery, Elijah Manor, Derek Gathright, Jesse Harlin, Dillon Curry, Courtney Myers, Diego Cadenas, Arne de Bree, João Paulo Dubas, James Taylor, Philipp Kraeutli, Mihai Păun, Sam Gharegozlou, joshjs, Matt Murchison, Eric Windham, Timo Behrmann, Andrew Hall, joshua price, Théophile Villard 17 | 18 | This book series is being produced in an open source fashion, including editing and production. We owe GitHub a debt of gratitude for making that sort of thing possible for the community! 19 | 20 | Thank you again to all the countless folks I didn't name but who I nonetheless owe thanks. May this book series be "owned" by all of us and serve to contribute to increasing awareness and understanding of the JavaScript language, to the benefit of all current and future community contributors. 21 | -------------------------------------------------------------------------------- /scope & closures/apD.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: Scope & Closures 2 | # Appendix D: Acknowledgments 3 | 4 | I have many people to thank for making this book title and the overall series happen. 5 | 6 | First, I must thank my wife Christen Simpson, and my two kids Ethan and Emily, for putting up with Dad always pecking away at the computer. Even when not writing books, my obsession with JavaScript glues my eyes to the screen far more than it should. That time I borrow from my family is the reason these books can so deeply and completely explain JavaScript to you, the reader. I owe my family everything. 7 | 8 | I'd like to thank my editors at O'Reilly, namely Simon St.Laurent and Brian MacDonald, as well as the rest of the editorial and marketing staff. They are fantastic to work with, and have been especially accommodating during this experiment into "open source" book writing, editing, and production. 9 | 10 | Thank you to the many folks who have participated in making this book series better by providing editorial suggestions and corrections, including Shelley Powers, Tim Ferro, Evan Borden, Forrest L. Norvell, Jennifer Davis, Jesse Harlin, and many others. A big thank you to Shane Hudson for writing the Foreword for this title. 11 | 12 | Thank you to the countless folks in the community, including members of the TC39 committee, who have shared so much knowledge with the rest of us, and especially tolerated my incessant questions and explorations with patience and detail. John-David Dalton, Juriy "kangax" Zaytsev, Mathias Bynens, Axel Rauschmayer, Nicholas Zakas, Angus Croll, Reginald Braithwaite, Dave Herman, Brendan Eich, Allen Wirfs-Brock, Bradley Meck, Domenic Denicola, David Walsh, Tim Disney, Peter van der Zee, Andrea Giammarchi, Kit Cambridge, Eric Elliott, and so many others, I can't even scratch the surface. 13 | 14 | The *You Don't Know JS* book series was born on Kickstarter, so I also wish to thank all my (nearly) 500 generous backers, without whom this book series could not have happened: 15 | 16 | > Jan Szpila, nokiko, Murali Krishnamoorthy, Ryan Joy, Craig Patchett, pdqtrader, Dale Fukami, ray hatfield, R0drigo Perez [Mx], Dan Petitt, Jack Franklin, Andrew Berry, Brian Grinstead, Rob Sutherland, Sergi Meseguer, Phillip Gourley, Mark Watson, Jeff Carouth, Alfredo Sumaran, Martin Sachse, Marcio Barrios, Dan, AimelyneM, Matt Sullivan, Delnatte Pierre-Antoine, Jake Smith, Eugen Tudorancea, Iris, David Trinh, simonstl, Ray Daly, Uros Gruber, Justin Myers, Shai Zonis, Mom & Dad, Devin Clark, Dennis Palmer, Brian Panahi Johnson, Josh Marshall, Marshall, Dennis Kerr, Matt Steele, Erik Slagter, Sacah, Justin Rainbow, Christian Nilsson, Delapouite, D.Pereira, Nicolas Hoizey, George V. Reilly, Dan Reeves, Bruno Laturner, Chad Jennings, Shane King, Jeremiah Lee Cohick, od3n, Stan Yamane, Marko Vucinic, Jim B, Stephen Collins, Ægir Þorsteinsson, Eric Pederson, Owain, Nathan Smith, Jeanetteurphy, Alexandre ELISÉ, Chris Peterson, Rik Watson, Luke Matthews, Justin Lowery, Morten Nielsen, Vernon Kesner, Chetan Shenoy, Paul Tregoing, Marc Grabanski, Dion Almaer, Andrew Sullivan, Keith Elsass, Tom Burke, Brian Ashenfelter, David Stuart, Karl Swedberg, Graeme, Brandon Hays, John Christopher, Gior, manoj reddy, Chad Smith, Jared Harbour, Minoru TODA, Chris Wigley, Daniel Mee, Mike, Handyface, Alex Jahraus, Carl Furrow, Rob Foulkrod, Max Shishkin, Leigh Penny Jr., Robert Ferguson, Mike van Hoenselaar, Hasse Schougaard, rajan venkataguru, Jeff Adams, Trae Robbins, Rolf Langenhuijzen, Jorge Antunes, Alex Koloskov, Hugh Greenish, Tim Jones, Jose Ochoa, Michael Brennan-White, Naga Harish Muvva, Barkóczi Dávid, Kitt Hodsden, Paul McGraw, Sascha Goldhofer, Andrew Metcalf, Markus Krogh, Michael Mathews, Matt Jared, Juanfran, Georgie Kirschner, Kenny Lee, Ted Zhang, Amit Pahwa, Inbal Sinai, Dan Raine, Schabse Laks, Michael Tervoort, Alexandre Abreu, Alan Joseph Williams, NicolasD, Cindy Wong, Reg Braithwaite, LocalPCGuy, Jon Friskics, Chris Merriman, John Pena, Jacob Katz, Sue Lockwood, Magnus Johansson, Jeremy Crapsey, Grzegorz Pawłowski, nico nuzzaci, Christine Wilks, Hans Bergren, charles montgomery, Ariel בר-לבב Fogel, Ivan Kolev, Daniel Campos, Hugh Wood, Christian Bradford, Frédéric Harper, Ionuţ Dan Popa, Jeff Trimble, Rupert Wood, Trey Carrico, Pancho Lopez, Joël kuijten, Tom A Marra, Jeff Jewiss, Jacob Rios, Paolo Di Stefano, Soledad Penades, Chris Gerber, Andrey Dolganov, Wil Moore III, Thomas Martineau, Kareem, Ben Thouret, Udi Nir, Morgan Laupies, jory carson-burson, Nathan L Smith, Eric Damon Walters, Derry Lozano-Hoyland, Geoffrey Wiseman, mkeehner, KatieK, Scott MacFarlane, Brian LaShomb, Adrien Mas, christopher ross, Ian Littman, Dan Atkinson, Elliot Jobe, Nick Dozier, Peter Wooley, John Hoover, dan, Martin A. Jackson, Héctor Fernando Hurtado, andy ennamorato, Paul Seltmann, Melissa Gore, Dave Pollard, Jack Smith, Philip Da Silva, Guy Israeli, @megalithic, Damian Crawford, Felix Gliesche, April Carter Grant, Heidi, jim tierney, Andrea Giammarchi, Nico Vignola, Don Jones, Chris Hartjes, Alex Howes, john gibbon, David J. Groom, BBox, Yu 'Dilys' Sun, Nate Steiner, Brandon Satrom, Brian Wyant, Wesley Hales, Ian Pouncey, Timothy Kevin Oxley, George Terezakis, sanjay raj, Jordan Harband, Marko McLion, Wolfgang Kaufmann, Pascal Peuckert, Dave Nugent, Markus Liebelt, Welling Guzman, Nick Cooley, Daniel Mesquita, Robert Syvarth, Chris Coyier, Rémy Bach, Adam Dougal, Alistair Duggin, David Loidolt, Ed Richer, Brian Chenault, GoldFire Studios, Carles Andrés, Carlos Cabo, Yuya Saito, roberto ricardo, Barnett Klane, Mike Moore, Kevin Marx, Justin Love, Joe Taylor, Paul Dijou, Michael Kohler, Rob Cassie, Mike Tierney, Cody Leroy Lindley, tofuji, Shimon Schwartz, Raymond, Luc De Brouwer, David Hayes, Rhys Brett-Bowen, Dmitry, Aziz Khoury, Dean, Scott Tolinski - Level Up, Clement Boirie, Djordje Lukic, Anton Kotenko, Rafael Corral, Philip Hurwitz, Jonathan Pidgeon, Jason Campbell, Joseph C., SwiftOne, Jan Hohner, Derick Bailey, getify, Daniel Cousineau, Chris Charlton, Eric Turner, David Turner, Joël Galeran, Dharma Vagabond, adam, Dirk van Bergen, dave ♥♫★ furf, Vedran Zakanj, Ryan McAllen, Natalie Patrice Tucker, Eric J. Bivona, Adam Spooner, Aaron Cavano, Kelly Packer, Eric J, Martin Drenovac, Emilis, Michael Pelikan, Scott F. Walter, Josh Freeman, Brandon Hudgeons, vijay chennupati, Bill Glennon, Robin R., Troy Forster, otaku_coder, Brad, Scott, Frederick Ostrander, Adam Brill, Seb Flippence, Michael Anderson, Jacob, Adam Randlett, Standard, Joshua Clanton, Sebastian Kouba, Chris Deck, SwordFire, Hannes Papenberg, Richard Woeber, hnzz, Rob Crowther, Jedidiah Broadbent, Sergey Chernyshev, Jay-Ar Jamon, Ben Combee, luciano bonachela, Mark Tomlinson, Kit Cambridge, Michael Melgares, Jacob Adams, Adrian Bruinhout, Bev Wieber, Scott Puleo, Thomas Herzog, April Leone, Daniel Mizieliński, Kees van Ginkel, Jon Abrams, Erwin Heiser, Avi Laviad, David newell, Jean-Francois Turcot, Niko Roberts, Erik Dana, Charles Neill, Aaron Holmes, Grzegorz Ziółkowski, Nathan Youngman, Timothy, Jacob Mather, Michael Allan, Mohit Seth, Ryan Ewing, Benjamin Van Treese, Marcelo Santos, Denis Wolf, Phil Keys, Chris Yung, Timo Tijhof, Martin Lekvall, Agendine, Greg Whitworth, Helen Humphrey, Dougal Campbell, Johannes Harth, Bruno Girin, Brian Hough, Darren Newton, Craig McPheat, Olivier Tille, Dennis Roethig, Mathias Bynens, Brendan Stromberger, sundeep, John Meyer, Ron Male, John F Croston III, gigante, Carl Bergenhem, B.J. May, Rebekah Tyler, Ted Foxberry, Jordan Reese, Terry Suitor, afeliz, Tom Kiefer, Darragh Duffy, Kevin Vanderbeken, Andy Pearson, Simon Mac Donald, Abid Din, Chris Joel, Tomas Theunissen, David Dick, Paul Grock, Brandon Wood, John Weis, dgrebb, Nick Jenkins, Chuck Lane, Johnny Megahan, marzsman, Tatu Tamminen, Geoffrey Knauth, Alexander Tarmolov, Jeremy Tymes, Chad Auld, Sean Parmelee, Rob Staenke, Dan Bender, Yannick derwa, Joshua Jones, Geert Plaisier, Tom LeZotte, Christen Simpson, Stefan Bruvik, Justin Falcone, Carlos Santana, Michael Weiss, Pablo Villoslada, Peter deHaan, Dimitris Iliopoulos, seyDoggy, Adam Jordens, Noah Kantrowitz, Amol M, Matthew Winnard, Dirk Ginader, Phinam Bui, David Rapson, Andrew Baxter, Florian Bougel, Michael George, Alban Escalier, Daniel Sellers, Sasha Rudan, John Green, Robert Kowalski, David I. Teixeira (@ditma), Charles Carpenter, Justin Yost, Sam S, Denis Ciccale, Kevin Sheurs, Yannick Croissant, Pau Fracés, Stephen McGowan, Shawn Searcy, Chris Ruppel, Kevin Lamping, Jessica Campbell, Christopher Schmitt, Sablons, Jonathan Reisdorf, Bunni Gek, Teddy Huff, Michael Mullany, Michael Fürstenberg, Carl Henderson, Rick Yoesting, Scott Nichols, Hernán Ciudad, Andrew Maier, Mike Stapp, Jesse Shawl, Sérgio Lopes, jsulak, Shawn Price, Joel Clermont, Chris Ridmann, Sean Timm, Jason Finch, Aiden Montgomery, Elijah Manor, Derek Gathright, Jesse Harlin, Dillon Curry, Courtney Myers, Diego Cadenas, Arne de Bree, João Paulo Dubas, James Taylor, Philipp Kraeutli, Mihai Păun, Sam Gharegozlou, joshjs, Matt Murchison, Eric Windham, Timo Behrmann, Andrew Hall, joshua price, Théophile Villard 17 | 18 | This book series is being produced in an open source fashion, including editing and production. We owe GitHub a debt of gratitude for making that sort of thing possible for the community! 19 | 20 | Thank you again to all the countless folks I didn't name but who I nonetheless owe thanks. May this book series be "owned" by all of us and serve to contribute to increasing awareness and understanding of the JavaScript language, to the benefit of all current and future community contributors. 21 | -------------------------------------------------------------------------------- /this & object prototypes/apB.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: *this* & Object Prototypes 2 | # Appendix B: Acknowledgments 3 | 4 | I have many people to thank for making this book title and the overall series happen. 5 | 6 | First, I must thank my wife Christen Simpson, and my two kids Ethan and Emily, for putting up with Dad always pecking away at the computer. Even when not writing books, my obsession with JavaScript glues my eyes to the screen far more than it should. That time I borrow from my family is the reason these books can so deeply and completely explain JavaScript to you, the reader. I owe my family everything. 7 | 8 | I'd like to thank my editors at O'Reilly, namely Simon St.Laurent and Brian MacDonald, as well as the rest of the editorial and marketing staff. They are fantastic to work with, and have been especially accommodating during this experiment into "open source" book writing, editing, and production. 9 | 10 | Thank you to the many folks who have participated in making this book series better by providing editorial suggestions and corrections, including Shelley Powers, Tim Ferro, Evan Borden, Forrest L. Norvell, Jennifer Davis, Jesse Harlin, and many others. A big thank you to Nick Berardi for writing the Foreword for this title. 11 | 12 | Thank you to the countless folks in the community, including members of the TC39 committee, who have shared so much knowledge with the rest of us, and especially tolerated my incessant questions and explorations with patience and detail. John-David Dalton, Juriy "kangax" Zaytsev, Mathias Bynens, Axel Rauschmayer, Nicholas Zakas, Angus Croll, Reginald Braithwaite, Dave Herman, Brendan Eich, Allen Wirfs-Brock, Bradley Meck, Domenic Denicola, David Walsh, Tim Disney, Peter van der Zee, Andrea Giammarchi, Kit Cambridge, Eric Elliott, and so many others, I can't even scratch the surface. 13 | 14 | The *You Don't Know JS* book series was born on Kickstarter, so I also wish to thank all my (nearly) 500 generous backers, without whom this book series could not have happened: 15 | 16 | > Jan Szpila, nokiko, Murali Krishnamoorthy, Ryan Joy, Craig Patchett, pdqtrader, Dale Fukami, ray hatfield, R0drigo Perez [Mx], Dan Petitt, Jack Franklin, Andrew Berry, Brian Grinstead, Rob Sutherland, Sergi Meseguer, Phillip Gourley, Mark Watson, Jeff Carouth, Alfredo Sumaran, Martin Sachse, Marcio Barrios, Dan, AimelyneM, Matt Sullivan, Delnatte Pierre-Antoine, Jake Smith, Eugen Tudorancea, Iris, David Trinh, simonstl, Ray Daly, Uros Gruber, Justin Myers, Shai Zonis, Mom & Dad, Devin Clark, Dennis Palmer, Brian Panahi Johnson, Josh Marshall, Marshall, Dennis Kerr, Matt Steele, Erik Slagter, Sacah, Justin Rainbow, Christian Nilsson, Delapouite, D.Pereira, Nicolas Hoizey, George V. Reilly, Dan Reeves, Bruno Laturner, Chad Jennings, Shane King, Jeremiah Lee Cohick, od3n, Stan Yamane, Marko Vucinic, Jim B, Stephen Collins, Ægir Þorsteinsson, Eric Pederson, Owain, Nathan Smith, Jeanetteurphy, Alexandre ELISÉ, Chris Peterson, Rik Watson, Luke Matthews, Justin Lowery, Morten Nielsen, Vernon Kesner, Chetan Shenoy, Paul Tregoing, Marc Grabanski, Dion Almaer, Andrew Sullivan, Keith Elsass, Tom Burke, Brian Ashenfelter, David Stuart, Karl Swedberg, Graeme, Brandon Hays, John Christopher, Gior, manoj reddy, Chad Smith, Jared Harbour, Minoru TODA, Chris Wigley, Daniel Mee, Mike, Handyface, Alex Jahraus, Carl Furrow, Rob Foulkrod, Max Shishkin, Leigh Penny Jr., Robert Ferguson, Mike van Hoenselaar, Hasse Schougaard, rajan venkataguru, Jeff Adams, Trae Robbins, Rolf Langenhuijzen, Jorge Antunes, Alex Koloskov, Hugh Greenish, Tim Jones, Jose Ochoa, Michael Brennan-White, Naga Harish Muvva, Barkóczi Dávid, Kitt Hodsden, Paul McGraw, Sascha Goldhofer, Andrew Metcalf, Markus Krogh, Michael Mathews, Matt Jared, Juanfran, Georgie Kirschner, Kenny Lee, Ted Zhang, Amit Pahwa, Inbal Sinai, Dan Raine, Schabse Laks, Michael Tervoort, Alexandre Abreu, Alan Joseph Williams, NicolasD, Cindy Wong, Reg Braithwaite, LocalPCGuy, Jon Friskics, Chris Merriman, John Pena, Jacob Katz, Sue Lockwood, Magnus Johansson, Jeremy Crapsey, Grzegorz Pawłowski, nico nuzzaci, Christine Wilks, Hans Bergren, charles montgomery, Ariel בר-לבב Fogel, Ivan Kolev, Daniel Campos, Hugh Wood, Christian Bradford, Frédéric Harper, Ionuţ Dan Popa, Jeff Trimble, Rupert Wood, Trey Carrico, Pancho Lopez, Joël kuijten, Tom A Marra, Jeff Jewiss, Jacob Rios, Paolo Di Stefano, Soledad Penades, Chris Gerber, Andrey Dolganov, Wil Moore III, Thomas Martineau, Kareem, Ben Thouret, Udi Nir, Morgan Laupies, jory carson-burson, Nathan L Smith, Eric Damon Walters, Derry Lozano-Hoyland, Geoffrey Wiseman, mkeehner, KatieK, Scott MacFarlane, Brian LaShomb, Adrien Mas, christopher ross, Ian Littman, Dan Atkinson, Elliot Jobe, Nick Dozier, Peter Wooley, John Hoover, dan, Martin A. Jackson, Héctor Fernando Hurtado, andy ennamorato, Paul Seltmann, Melissa Gore, Dave Pollard, Jack Smith, Philip Da Silva, Guy Israeli, @megalithic, Damian Crawford, Felix Gliesche, April Carter Grant, Heidi, jim tierney, Andrea Giammarchi, Nico Vignola, Don Jones, Chris Hartjes, Alex Howes, john gibbon, David J. Groom, BBox, Yu 'Dilys' Sun, Nate Steiner, Brandon Satrom, Brian Wyant, Wesley Hales, Ian Pouncey, Timothy Kevin Oxley, George Terezakis, sanjay raj, Jordan Harband, Marko McLion, Wolfgang Kaufmann, Pascal Peuckert, Dave Nugent, Markus Liebelt, Welling Guzman, Nick Cooley, Daniel Mesquita, Robert Syvarth, Chris Coyier, Rémy Bach, Adam Dougal, Alistair Duggin, David Loidolt, Ed Richer, Brian Chenault, GoldFire Studios, Carles Andrés, Carlos Cabo, Yuya Saito, roberto ricardo, Barnett Klane, Mike Moore, Kevin Marx, Justin Love, Joe Taylor, Paul Dijou, Michael Kohler, Rob Cassie, Mike Tierney, Cody Leroy Lindley, tofuji, Shimon Schwartz, Raymond, Luc De Brouwer, David Hayes, Rhys Brett-Bowen, Dmitry, Aziz Khoury, Dean, Scott Tolinski - Level Up, Clement Boirie, Djordje Lukic, Anton Kotenko, Rafael Corral, Philip Hurwitz, Jonathan Pidgeon, Jason Campbell, Joseph C., SwiftOne, Jan Hohner, Derick Bailey, getify, Daniel Cousineau, Chris Charlton, Eric Turner, David Turner, Joël Galeran, Dharma Vagabond, adam, Dirk van Bergen, dave ♥♫★ furf, Vedran Zakanj, Ryan McAllen, Natalie Patrice Tucker, Eric J. Bivona, Adam Spooner, Aaron Cavano, Kelly Packer, Eric J, Martin Drenovac, Emilis, Michael Pelikan, Scott F. Walter, Josh Freeman, Brandon Hudgeons, vijay chennupati, Bill Glennon, Robin R., Troy Forster, otaku_coder, Brad, Scott, Frederick Ostrander, Adam Brill, Seb Flippence, Michael Anderson, Jacob, Adam Randlett, Standard, Joshua Clanton, Sebastian Kouba, Chris Deck, SwordFire, Hannes Papenberg, Richard Woeber, hnzz, Rob Crowther, Jedidiah Broadbent, Sergey Chernyshev, Jay-Ar Jamon, Ben Combee, luciano bonachela, Mark Tomlinson, Kit Cambridge, Michael Melgares, Jacob Adams, Adrian Bruinhout, Bev Wieber, Scott Puleo, Thomas Herzog, April Leone, Daniel Mizieliński, Kees van Ginkel, Jon Abrams, Erwin Heiser, Avi Laviad, David newell, Jean-Francois Turcot, Niko Roberts, Erik Dana, Charles Neill, Aaron Holmes, Grzegorz Ziółkowski, Nathan Youngman, Timothy, Jacob Mather, Michael Allan, Mohit Seth, Ryan Ewing, Benjamin Van Treese, Marcelo Santos, Denis Wolf, Phil Keys, Chris Yung, Timo Tijhof, Martin Lekvall, Agendine, Greg Whitworth, Helen Humphrey, Dougal Campbell, Johannes Harth, Bruno Girin, Brian Hough, Darren Newton, Craig McPheat, Olivier Tille, Dennis Roethig, Mathias Bynens, Brendan Stromberger, sundeep, John Meyer, Ron Male, John F Croston III, gigante, Carl Bergenhem, B.J. May, Rebekah Tyler, Ted Foxberry, Jordan Reese, Terry Suitor, afeliz, Tom Kiefer, Darragh Duffy, Kevin Vanderbeken, Andy Pearson, Simon Mac Donald, Abid Din, Chris Joel, Tomas Theunissen, David Dick, Paul Grock, Brandon Wood, John Weis, dgrebb, Nick Jenkins, Chuck Lane, Johnny Megahan, marzsman, Tatu Tamminen, Geoffrey Knauth, Alexander Tarmolov, Jeremy Tymes, Chad Auld, Sean Parmelee, Rob Staenke, Dan Bender, Yannick derwa, Joshua Jones, Geert Plaisier, Tom LeZotte, Christen Simpson, Stefan Bruvik, Justin Falcone, Carlos Santana, Michael Weiss, Pablo Villoslada, Peter deHaan, Dimitris Iliopoulos, seyDoggy, Adam Jordens, Noah Kantrowitz, Amol M, Matthew Winnard, Dirk Ginader, Phinam Bui, David Rapson, Andrew Baxter, Florian Bougel, Michael George, Alban Escalier, Daniel Sellers, Sasha Rudan, John Green, Robert Kowalski, David I. Teixeira (@ditma, Charles Carpenter, Justin Yost, Sam S, Denis Ciccale, Kevin Sheurs, Yannick Croissant, Pau Fracés, Stephen McGowan, Shawn Searcy, Chris Ruppel, Kevin Lamping, Jessica Campbell, Christopher Schmitt, Sablons, Jonathan Reisdorf, Bunni Gek, Teddy Huff, Michael Mullany, Michael Fürstenberg, Carl Henderson, Rick Yoesting, Scott Nichols, Hernán Ciudad, Andrew Maier, Mike Stapp, Jesse Shawl, Sérgio Lopes, jsulak, Shawn Price, Joel Clermont, Chris Ridmann, Sean Timm, Jason Finch, Aiden Montgomery, Elijah Manor, Derek Gathright, Jesse Harlin, Dillon Curry, Courtney Myers, Diego Cadenas, Arne de Bree, João Paulo Dubas, James Taylor, Philipp Kraeutli, Mihai Păun, Sam Gharegozlou, joshjs, Matt Murchison, Eric Windham, Timo Behrmann, Andrew Hall, joshua price, Théophile Villard 17 | 18 | This book series is being produced in an open source fashion, including editing and production. We owe GitHub a debt of gratitude for making that sort of thing possible for the community! 19 | 20 | Thank you again to all the countless folks I didn't name but who I nonetheless owe thanks. May this book series be "owned" by all of us and serve to contribute to increasing awareness and understanding of the JavaScript language, to the benefit of all current and future community contributors. 21 | -------------------------------------------------------------------------------- /es6 & beyond/apA.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: ES6 & Beyond 2 | # Appendix A: Acknowledgments 3 | 4 | I have many people to thank for making this book title and the overall series happen. 5 | 6 | First, I must thank my wife Christen Simpson, and my two kids Ethan and Emily, for putting up with Dad always pecking away at the computer. Even when not writing books, my obsession with JavaScript glues my eyes to the screen far more than it should. That time I borrow from my family is the reason these books can so deeply and completely explain JavaScript to you, the reader. I owe my family everything. 7 | 8 | I'd like to thank my editors at O'Reilly, namely Simon St.Laurent and Brian MacDonald, as well as the rest of the editorial and marketing staff. They are fantastic to work with, and have been especially accommodating during this experiment into "open source" book writing, editing, and production. 9 | 10 | Thank you to the many folks who have participated in making this book series better by providing editorial suggestions and corrections, including Shelley Powers, Tim Ferro, Evan Borden, Forrest L. Norvell, Jennifer Davis, Jesse Harlin, and many others. A big thank you to Rick Waldron for writing the Foreword for this title. 11 | 12 | Thank you to the countless folks in the community, including members of the TC39 committee, who have shared so much knowledge with the rest of us, and especially tolerated my incessant questions and explorations with patience and detail. John-David Dalton, Juriy "kangax" Zaytsev, Mathias Bynens, Axel Rauschmayer, Nicholas Zakas, Angus Croll, Reginald Braithwaite, Dave Herman, Brendan Eich, Allen Wirfs-Brock, Bradley Meck, Domenic Denicola, David Walsh, Tim Disney, Peter van der Zee, Andrea Giammarchi, Kit Cambridge, Eric Elliott, André Bargull, Caitlin Potter, Brian Terlson, Ingvar Stepanyan, Chris Dickinson, Luke Hoban, and so many others, I can't even scratch the surface. 13 | 14 | The *You Don't Know JS* book series was born on Kickstarter, so I also wish to thank all my (nearly) 500 generous backers, without whom this book series could not have happened: 15 | 16 | > Jan Szpila, nokiko, Murali Krishnamoorthy, Ryan Joy, Craig Patchett, pdqtrader, Dale Fukami, ray hatfield, R0drigo Perez [Mx], Dan Petitt, Jack Franklin, Andrew Berry, Brian Grinstead, Rob Sutherland, Sergi Meseguer, Phillip Gourley, Mark Watson, Jeff Carouth, Alfredo Sumaran, Martin Sachse, Marcio Barrios, Dan, AimelyneM, Matt Sullivan, Delnatte Pierre-Antoine, Jake Smith, Eugen Tudorancea, Iris, David Trinh, simonstl, Ray Daly, Uros Gruber, Justin Myers, Shai Zonis, Mom & Dad, Devin Clark, Dennis Palmer, Brian Panahi Johnson, Josh Marshall, Marshall, Dennis Kerr, Matt Steele, Erik Slagter, Sacah, Justin Rainbow, Christian Nilsson, Delapouite, D.Pereira, Nicolas Hoizey, George V. Reilly, Dan Reeves, Bruno Laturner, Chad Jennings, Shane King, Jeremiah Lee Cohick, od3n, Stan Yamane, Marko Vucinic, Jim B, Stephen Collins, Ægir Þorsteinsson, Eric Pederson, Owain, Nathan Smith, Jeanetteurphy, Alexandre ELISÉ, Chris Peterson, Rik Watson, Luke Matthews, Justin Lowery, Morten Nielsen, Vernon Kesner, Chetan Shenoy, Paul Tregoing, Marc Grabanski, Dion Almaer, Andrew Sullivan, Keith Elsass, Tom Burke, Brian Ashenfelter, David Stuart, Karl Swedberg, Graeme, Brandon Hays, John Christopher, Gior, manoj reddy, Chad Smith, Jared Harbour, Minoru TODA, Chris Wigley, Daniel Mee, Mike, Handyface, Alex Jahraus, Carl Furrow, Rob Foulkrod, Max Shishkin, Leigh Penny Jr., Robert Ferguson, Mike van Hoenselaar, Hasse Schougaard, rajan venkataguru, Jeff Adams, Trae Robbins, Rolf Langenhuijzen, Jorge Antunes, Alex Koloskov, Hugh Greenish, Tim Jones, Jose Ochoa, Michael Brennan-White, Naga Harish Muvva, Barkóczi Dávid, Kitt Hodsden, Paul McGraw, Sascha Goldhofer, Andrew Metcalf, Markus Krogh, Michael Mathews, Matt Jared, Juanfran, Georgie Kirschner, Kenny Lee, Ted Zhang, Amit Pahwa, Inbal Sinai, Dan Raine, Schabse Laks, Michael Tervoort, Alexandre Abreu, Alan Joseph Williams, NicolasD, Cindy Wong, Reg Braithwaite, LocalPCGuy, Jon Friskics, Chris Merriman, John Pena, Jacob Katz, Sue Lockwood, Magnus Johansson, Jeremy Crapsey, Grzegorz Pawłowski, nico nuzzaci, Christine Wilks, Hans Bergren, charles montgomery, Ariel בר-לבב Fogel, Ivan Kolev, Daniel Campos, Hugh Wood, Christian Bradford, Frédéric Harper, Ionuţ Dan Popa, Jeff Trimble, Rupert Wood, Trey Carrico, Pancho Lopez, Joël kuijten, Tom A Marra, Jeff Jewiss, Jacob Rios, Paolo Di Stefano, Soledad Penades, Chris Gerber, Andrey Dolganov, Wil Moore III, Thomas Martineau, Kareem, Ben Thouret, Udi Nir, Morgan Laupies, jory carson-burson, Nathan L Smith, Eric Damon Walters, Derry Lozano-Hoyland, Geoffrey Wiseman, mkeehner, KatieK, Scott MacFarlane, Brian LaShomb, Adrien Mas, christopher ross, Ian Littman, Dan Atkinson, Elliot Jobe, Nick Dozier, Peter Wooley, John Hoover, dan, Martin A. Jackson, Héctor Fernando Hurtado, andy ennamorato, Paul Seltmann, Melissa Gore, Dave Pollard, Jack Smith, Philip Da Silva, Guy Israeli, @megalithic, Damian Crawford, Felix Gliesche, April Carter Grant, Heidi, jim tierney, Andrea Giammarchi, Nico Vignola, Don Jones, Chris Hartjes, Alex Howes, john gibbon, David J. Groom, BBox, Yu 'Dilys' Sun, Nate Steiner, Brandon Satrom, Brian Wyant, Wesley Hales, Ian Pouncey, Timothy Kevin Oxley, George Terezakis, sanjay raj, Jordan Harband, Marko McLion, Wolfgang Kaufmann, Pascal Peuckert, Dave Nugent, Markus Liebelt, Welling Guzman, Nick Cooley, Daniel Mesquita, Robert Syvarth, Chris Coyier, Rémy Bach, Adam Dougal, Alistair Duggin, David Loidolt, Ed Richer, Brian Chenault, GoldFire Studios, Carles Andrés, Carlos Cabo, Yuya Saito, roberto ricardo, Barnett Klane, Mike Moore, Kevin Marx, Justin Love, Joe Taylor, Paul Dijou, Michael Kohler, Rob Cassie, Mike Tierney, Cody Leroy Lindley, tofuji, Shimon Schwartz, Raymond, Luc De Brouwer, David Hayes, Rhys Brett-Bowen, Dmitry, Aziz Khoury, Dean, Scott Tolinski - Level Up, Clement Boirie, Djordje Lukic, Anton Kotenko, Rafael Corral, Philip Hurwitz, Jonathan Pidgeon, Jason Campbell, Joseph C., SwiftOne, Jan Hohner, Derick Bailey, getify, Daniel Cousineau, Chris Charlton, Eric Turner, David Turner, Joël Galeran, Dharma Vagabond, adam, Dirk van Bergen, dave ♥♫★ furf, Vedran Zakanj, Ryan McAllen, Natalie Patrice Tucker, Eric J. Bivona, Adam Spooner, Aaron Cavano, Kelly Packer, Eric J, Martin Drenovac, Emilis, Michael Pelikan, Scott F. Walter, Josh Freeman, Brandon Hudgeons, vijay chennupati, Bill Glennon, Robin R., Troy Forster, otaku_coder, Brad, Scott, Frederick Ostrander, Adam Brill, Seb Flippence, Michael Anderson, Jacob, Adam Randlett, Standard, Joshua Clanton, Sebastian Kouba, Chris Deck, SwordFire, Hannes Papenberg, Richard Woeber, hnzz, Rob Crowther, Jedidiah Broadbent, Sergey Chernyshev, Jay-Ar Jamon, Ben Combee, luciano bonachela, Mark Tomlinson, Kit Cambridge, Michael Melgares, Jacob Adams, Adrian Bruinhout, Bev Wieber, Scott Puleo, Thomas Herzog, April Leone, Daniel Mizieliński, Kees van Ginkel, Jon Abrams, Erwin Heiser, Avi Laviad, David newell, Jean-Francois Turcot, Niko Roberts, Erik Dana, Charles Neill, Aaron Holmes, Grzegorz Ziółkowski, Nathan Youngman, Timothy, Jacob Mather, Michael Allan, Mohit Seth, Ryan Ewing, Benjamin Van Treese, Marcelo Santos, Denis Wolf, Phil Keys, Chris Yung, Timo Tijhof, Martin Lekvall, Agendine, Greg Whitworth, Helen Humphrey, Dougal Campbell, Johannes Harth, Bruno Girin, Brian Hough, Darren Newton, Craig McPheat, Olivier Tille, Dennis Roethig, Mathias Bynens, Brendan Stromberger, sundeep, John Meyer, Ron Male, John F Croston III, gigante, Carl Bergenhem, B.J. May, Rebekah Tyler, Ted Foxberry, Jordan Reese, Terry Suitor, afeliz, Tom Kiefer, Darragh Duffy, Kevin Vanderbeken, Andy Pearson, Simon Mac Donald, Abid Din, Chris Joel, Tomas Theunissen, David Dick, Paul Grock, Brandon Wood, John Weis, dgrebb, Nick Jenkins, Chuck Lane, Johnny Megahan, marzsman, Tatu Tamminen, Geoffrey Knauth, Alexander Tarmolov, Jeremy Tymes, Chad Auld, Sean Parmelee, Rob Staenke, Dan Bender, Yannick derwa, Joshua Jones, Geert Plaisier, Tom LeZotte, Christen Simpson, Stefan Bruvik, Justin Falcone, Carlos Santana, Michael Weiss, Pablo Villoslada, Peter deHaan, Dimitris Iliopoulos, seyDoggy, Adam Jordens, Noah Kantrowitz, Amol M, Matthew Winnard, Dirk Ginader, Phinam Bui, David Rapson, Andrew Baxter, Florian Bougel, Michael George, Alban Escalier, Daniel Sellers, Sasha Rudan, John Green, Robert Kowalski, David I. Teixeira (@ditma, Charles Carpenter, Justin Yost, Sam S, Denis Ciccale, Kevin Sheurs, Yannick Croissant, Pau Fracés, Stephen McGowan, Shawn Searcy, Chris Ruppel, Kevin Lamping, Jessica Campbell, Christopher Schmitt, Sablons, Jonathan Reisdorf, Bunni Gek, Teddy Huff, Michael Mullany, Michael Fürstenberg, Carl Henderson, Rick Yoesting, Scott Nichols, Hernán Ciudad, Andrew Maier, Mike Stapp, Jesse Shawl, Sérgio Lopes, jsulak, Shawn Price, Joel Clermont, Chris Ridmann, Sean Timm, Jason Finch, Aiden Montgomery, Elijah Manor, Derek Gathright, Jesse Harlin, Dillon Curry, Courtney Myers, Diego Cadenas, Arne de Bree, João Paulo Dubas, James Taylor, Philipp Kraeutli, Mihai Păun, Sam Gharegozlou, joshjs, Matt Murchison, Eric Windham, Timo Behrmann, Andrew Hall, joshua price, Théophile Villard 17 | 18 | This book series is being produced in an open source fashion, including editing and production. We owe GitHub a debt of gratitude for making that sort of thing possible for the community! 19 | 20 | Thank you again to all the countless folks I didn't name but who I nonetheless owe thanks. May this book series be "owned" by all of us and serve to contribute to increasing awareness and understanding of the JavaScript language, to the benefit of all current and future community contributors. 21 | -------------------------------------------------------------------------------- /up & going/apA.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: Up & Going 2 | # Appendix A: Acknowledgments 3 | 4 | I have many people to thank for making this book title and the overall series happen. 5 | 6 | First, I must thank my wife Christen Simpson, and my two kids Ethan and Emily, for putting up with Dad always pecking away at the computer. Even when not writing books, my obsession with JavaScript glues my eyes to the screen far more than it should. That time I borrow from my family is the reason these books can so deeply and completely explain JavaScript to you, the reader. I owe my family everything. 7 | 8 | I'd like to thank my editors at O'Reilly, namely Simon St.Laurent and Brian MacDonald, as well as the rest of the editorial and marketing staff. They are fantastic to work with, and have been especially accommodating during this experiment into "open source" book writing, editing, and production. 9 | 10 | Thank you to the many folks who have participated in making this book series better by providing editorial suggestions and corrections, including Shelley Powers, Tim Ferro, Evan Borden, Forrest L. Norvell, Jennifer Davis, Jesse Harlin, Kris Kowal, Rick Waldron, Jordan Harband, Benjamin Gruenbaum, Vyacheslav Egorov, David Nolen, and many others. A big thank you to Jenn Lukas for writing the Foreword for this title. 11 | 12 | Thank you to the countless folks in the community, including members of the TC39 committee, who have shared so much knowledge with the rest of us, and especially tolerated my incessant questions and explorations with patience and detail. John-David Dalton, Juriy "kangax" Zaytsev, Mathias Bynens, Axel Rauschmayer, Nicholas Zakas, Angus Croll, Reginald Braithwaite, Dave Herman, Brendan Eich, Allen Wirfs-Brock, Bradley Meck, Domenic Denicola, David Walsh, Tim Disney, Peter van der Zee, Andrea Giammarchi, Kit Cambridge, Eric Elliott, and so many others, I can't even scratch the surface. 13 | 14 | Since the "You Don't Know JS" book series was born on Kickstarter, I also wish to thank all my (nearly) 500 generous backers, without whom this book series could not have happened: 15 | 16 | > Jan Szpila, nokiko, Murali Krishnamoorthy, Ryan Joy, Craig Patchett, pdqtrader, Dale Fukami, ray hatfield, R0drigo Perez [Mx], Dan Petitt, Jack Franklin, Andrew Berry, Brian Grinstead, Rob Sutherland, Sergi Meseguer, Phillip Gourley, Mark Watson, Jeff Carouth, Alfredo Sumaran, Martin Sachse, Marcio Barrios, Dan, AimelyneM, Matt Sullivan, Delnatte Pierre-Antoine, Jake Smith, Eugen Tudorancea, Iris, David Trinh, simonstl, Ray Daly, Uros Gruber, Justin Myers, Shai Zonis, Mom & Dad, Devin Clark, Dennis Palmer, Brian Panahi Johnson, Josh Marshall, Marshall, Dennis Kerr, Matt Steele, Erik Slagter, Sacah, Justin Rainbow, Christian Nilsson, Delapouite, D.Pereira, Nicolas Hoizey, George V. Reilly, Dan Reeves, Bruno Laturner, Chad Jennings, Shane King, Jeremiah Lee Cohick, od3n, Stan Yamane, Marko Vucinic, Jim B, Stephen Collins, Ægir Þorsteinsson, Eric Pederson, Owain, Nathan Smith, Jeanetteurphy, Alexandre ELISÉ, Chris Peterson, Rik Watson, Luke Matthews, Justin Lowery, Morten Nielsen, Vernon Kesner, Chetan Shenoy, Paul Tregoing, Marc Grabanski, Dion Almaer, Andrew Sullivan, Keith Elsass, Tom Burke, Brian Ashenfelter, David Stuart, Karl Swedberg, Graeme, Brandon Hays, John Christopher, Gior, manoj reddy, Chad Smith, Jared Harbour, Minoru TODA, Chris Wigley, Daniel Mee, Mike, Handyface, Alex Jahraus, Carl Furrow, Rob Foulkrod, Max Shishkin, Leigh Penny Jr., Robert Ferguson, Mike van Hoenselaar, Hasse Schougaard, rajan venkataguru, Jeff Adams, Trae Robbins, Rolf Langenhuijzen, Jorge Antunes, Alex Koloskov, Hugh Greenish, Tim Jones, Jose Ochoa, Michael Brennan-White, Naga Harish Muvva, Barkóczi Dávid, Kitt Hodsden, Paul McGraw, Sascha Goldhofer, Andrew Metcalf, Markus Krogh, Michael Mathews, Matt Jared, Juanfran, Georgie Kirschner, Kenny Lee, Ted Zhang, Amit Pahwa, Inbal Sinai, Dan Raine, Schabse Laks, Michael Tervoort, Alexandre Abreu, Alan Joseph Williams, NicolasD, Cindy Wong, Reg Braithwaite, LocalPCGuy, Jon Friskics, Chris Merriman, John Pena, Jacob Katz, Sue Lockwood, Magnus Johansson, Jeremy Crapsey, Grzegorz Pawłowski, nico nuzzaci, Christine Wilks, Hans Bergren, charles montgomery, Ariel בר-לבב Fogel, Ivan Kolev, Daniel Campos, Hugh Wood, Christian Bradford, Frédéric Harper, Ionuţ Dan Popa, Jeff Trimble, Rupert Wood, Trey Carrico, Pancho Lopez, Joël kuijten, Tom A Marra, Jeff Jewiss, Jacob Rios, Paolo Di Stefano, Soledad Penades, Chris Gerber, Andrey Dolganov, Wil Moore III, Thomas Martineau, Kareem, Ben Thouret, Udi Nir, Morgan Laupies, jory carson-burson, Nathan L Smith, Eric Damon Walters, Derry Lozano-Hoyland, Geoffrey Wiseman, mkeehner, KatieK, Scott MacFarlane, Brian LaShomb, Adrien Mas, christopher ross, Ian Littman, Dan Atkinson, Elliot Jobe, Nick Dozier, Peter Wooley, John Hoover, dan, Martin A. Jackson, Héctor Fernando Hurtado, andy ennamorato, Paul Seltmann, Melissa Gore, Dave Pollard, Jack Smith, Philip Da Silva, Guy Israeli, @megalithic, Damian Crawford, Felix Gliesche, April Carter Grant, Heidi, jim tierney, Andrea Giammarchi, Nico Vignola, Don Jones, Chris Hartjes, Alex Howes, john gibbon, David J. Groom, BBox, Yu 'Dilys' Sun, Nate Steiner, Brandon Satrom, Brian Wyant, Wesley Hales, Ian Pouncey, Timothy Kevin Oxley, George Terezakis, sanjay raj, Jordan Harband, Marko McLion, Wolfgang Kaufmann, Pascal Peuckert, Dave Nugent, Markus Liebelt, Welling Guzman, Nick Cooley, Daniel Mesquita, Robert Syvarth, Chris Coyier, Rémy Bach, Adam Dougal, Alistair Duggin, David Loidolt, Ed Richer, Brian Chenault, GoldFire Studios, Carles Andrés, Carlos Cabo, Yuya Saito, roberto ricardo, Barnett Klane, Mike Moore, Kevin Marx, Justin Love, Joe Taylor, Paul Dijou, Michael Kohler, Rob Cassie, Mike Tierney, Cody Leroy Lindley, tofuji, Shimon Schwartz, Raymond, Luc De Brouwer, David Hayes, Rhys Brett-Bowen, Dmitry, Aziz Khoury, Dean, Scott Tolinski - Level Up, Clement Boirie, Djordje Lukic, Anton Kotenko, Rafael Corral, Philip Hurwitz, Jonathan Pidgeon, Jason Campbell, Joseph C., SwiftOne, Jan Hohner, Derick Bailey, getify, Daniel Cousineau, Chris Charlton, Eric Turner, David Turner, Joël Galeran, Dharma Vagabond, adam, Dirk van Bergen, dave ♥♫★ furf, Vedran Zakanj, Ryan McAllen, Natalie Patrice Tucker, Eric J. Bivona, Adam Spooner, Aaron Cavano, Kelly Packer, Eric J, Martin Drenovac, Emilis, Michael Pelikan, Scott F. Walter, Josh Freeman, Brandon Hudgeons, vijay chennupati, Bill Glennon, Robin R., Troy Forster, otaku_coder, Brad, Scott, Frederick Ostrander, Adam Brill, Seb Flippence, Michael Anderson, Jacob, Adam Randlett, Standard, Joshua Clanton, Sebastian Kouba, Chris Deck, SwordFire, Hannes Papenberg, Richard Woeber, hnzz, Rob Crowther, Jedidiah Broadbent, Sergey Chernyshev, Jay-Ar Jamon, Ben Combee, luciano bonachela, Mark Tomlinson, Kit Cambridge, Michael Melgares, Jacob Adams, Adrian Bruinhout, Bev Wieber, Scott Puleo, Thomas Herzog, April Leone, Daniel Mizieliński, Kees van Ginkel, Jon Abrams, Erwin Heiser, Avi Laviad, David newell, Jean-Francois Turcot, Niko Roberts, Erik Dana, Charles Neill, Aaron Holmes, Grzegorz Ziółkowski, Nathan Youngman, Timothy, Jacob Mather, Michael Allan, Mohit Seth, Ryan Ewing, Benjamin Van Treese, Marcelo Santos, Denis Wolf, Phil Keys, Chris Yung, Timo Tijhof, Martin Lekvall, Agendine, Greg Whitworth, Helen Humphrey, Dougal Campbell, Johannes Harth, Bruno Girin, Brian Hough, Darren Newton, Craig McPheat, Olivier Tille, Dennis Roethig, Mathias Bynens, Brendan Stromberger, sundeep, John Meyer, Ron Male, John F Croston III, gigante, Carl Bergenhem, B.J. May, Rebekah Tyler, Ted Foxberry, Jordan Reese, Terry Suitor, afeliz, Tom Kiefer, Darragh Duffy, Kevin Vanderbeken, Andy Pearson, Simon Mac Donald, Abid Din, Chris Joel, Tomas Theunissen, David Dick, Paul Grock, Brandon Wood, John Weis, dgrebb, Nick Jenkins, Chuck Lane, Johnny Megahan, marzsman, Tatu Tamminen, Geoffrey Knauth, Alexander Tarmolov, Jeremy Tymes, Chad Auld, Sean Parmelee, Rob Staenke, Dan Bender, Yannick derwa, Joshua Jones, Geert Plaisier, Tom LeZotte, Christen Simpson, Stefan Bruvik, Justin Falcone, Carlos Santana, Michael Weiss, Pablo Villoslada, Peter deHaan, Dimitris Iliopoulos, seyDoggy, Adam Jordens, Noah Kantrowitz, Amol M, Matthew Winnard, Dirk Ginader, Phinam Bui, David Rapson, Andrew Baxter, Florian Bougel, Michael George, Alban Escalier, Daniel Sellers, Sasha Rudan, John Green, Robert Kowalski, David I. Teixeira (@ditma, Charles Carpenter, Justin Yost, Sam S, Denis Ciccale, Kevin Sheurs, Yannick Croissant, Pau Fracés, Stephen McGowan, Shawn Searcy, Chris Ruppel, Kevin Lamping, Jessica Campbell, Christopher Schmitt, Sablons, Jonathan Reisdorf, Bunni Gek, Teddy Huff, Michael Mullany, Michael Fürstenberg, Carl Henderson, Rick Yoesting, Scott Nichols, Hernán Ciudad, Andrew Maier, Mike Stapp, Jesse Shawl, Sérgio Lopes, jsulak, Shawn Price, Joel Clermont, Chris Ridmann, Sean Timm, Jason Finch, Aiden Montgomery, Elijah Manor, Derek Gathright, Jesse Harlin, Dillon Curry, Courtney Myers, Diego Cadenas, Arne de Bree, João Paulo Dubas, James Taylor, Philipp Kraeutli, Mihai Păun, Sam Gharegozlou, joshjs, Matt Murchison, Eric Windham, Timo Behrmann, Andrew Hall, joshua price, Théophile Villard 17 | 18 | This book series is being produced in an open source fashion, including editing and production. We owe GitHub a debt of gratitude for making that sort of thing possible for the community! 19 | 20 | Thank you again to all the countless folks I didn't name but to whom I nonetheless owe thanks. May this book series be "owned" by all of us and serve to contribute to increasing awareness and understanding of the JavaScript language, to the benefit of all current and future community contributors. 21 | -------------------------------------------------------------------------------- /async & performance/apC.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: Async & Performance 2 | # Appendix C: Acknowledgments 3 | 4 | I have many people to thank for making this book title and the overall series happen. 5 | 6 | First, I must thank my wife Christen Simpson, and my two kids Ethan and Emily, for putting up with Dad always pecking away at the computer. Even when not writing books, my obsession with JavaScript glues my eyes to the screen far more than it should. That time I borrow from my family is the reason these books can so deeply and completely explain JavaScript to you, the reader. I owe my family everything. 7 | 8 | I'd like to thank my editors at O'Reilly, namely Simon St.Laurent and Brian MacDonald, as well as the rest of the editorial and marketing staff. They are fantastic to work with, and have been especially accommodating during this experiment into "open source" book writing, editing, and production. 9 | 10 | Thank you to the many folks who have participated in making this book series better by providing editorial suggestions and corrections, including Shelley Powers, Tim Ferro, Evan Borden, Forrest L. Norvell, Jennifer Davis, Jesse Harlin, Kris Kowal, Rick Waldron, Jordan Harband, Benjamin Gruenbaum, Vyacheslav Egorov, David Nolen, and many others. A big thank you to Jake Archibald for writing the Foreword for this title. 11 | 12 | Thank you to the countless folks in the community, including members of the TC39 committee, who have shared so much knowledge with the rest of us, and especially tolerated my incessant questions and explorations with patience and detail. John-David Dalton, Juriy "kangax" Zaytsev, Mathias Bynens, Axel Rauschmayer, Nicholas Zakas, Angus Croll, Reginald Braithwaite, Dave Herman, Brendan Eich, Allen Wirfs-Brock, Bradley Meck, Domenic Denicola, David Walsh, Tim Disney, Peter van der Zee, Andrea Giammarchi, Kit Cambridge, Eric Elliott, and so many others, I can't even scratch the surface. 13 | 14 | The *You Don't Know JS* book series was born on Kickstarter, so I also wish to thank all my (nearly) 500 generous backers, without whom this book series could not have happened: 15 | 16 | > Jan Szpila, nokiko, Murali Krishnamoorthy, Ryan Joy, Craig Patchett, pdqtrader, Dale Fukami, ray hatfield, R0drigo Perez [Mx], Dan Petitt, Jack Franklin, Andrew Berry, Brian Grinstead, Rob Sutherland, Sergi Meseguer, Phillip Gourley, Mark Watson, Jeff Carouth, Alfredo Sumaran, Martin Sachse, Marcio Barrios, Dan, AimelyneM, Matt Sullivan, Delnatte Pierre-Antoine, Jake Smith, Eugen Tudorancea, Iris, David Trinh, simonstl, Ray Daly, Uros Gruber, Justin Myers, Shai Zonis, Mom & Dad, Devin Clark, Dennis Palmer, Brian Panahi Johnson, Josh Marshall, Marshall, Dennis Kerr, Matt Steele, Erik Slagter, Sacah, Justin Rainbow, Christian Nilsson, Delapouite, D.Pereira, Nicolas Hoizey, George V. Reilly, Dan Reeves, Bruno Laturner, Chad Jennings, Shane King, Jeremiah Lee Cohick, od3n, Stan Yamane, Marko Vucinic, Jim B, Stephen Collins, Ægir Þorsteinsson, Eric Pederson, Owain, Nathan Smith, Jeanetteurphy, Alexandre ELISÉ, Chris Peterson, Rik Watson, Luke Matthews, Justin Lowery, Morten Nielsen, Vernon Kesner, Chetan Shenoy, Paul Tregoing, Marc Grabanski, Dion Almaer, Andrew Sullivan, Keith Elsass, Tom Burke, Brian Ashenfelter, David Stuart, Karl Swedberg, Graeme, Brandon Hays, John Christopher, Gior, manoj reddy, Chad Smith, Jared Harbour, Minoru TODA, Chris Wigley, Daniel Mee, Mike, Handyface, Alex Jahraus, Carl Furrow, Rob Foulkrod, Max Shishkin, Leigh Penny Jr., Robert Ferguson, Mike van Hoenselaar, Hasse Schougaard, rajan venkataguru, Jeff Adams, Trae Robbins, Rolf Langenhuijzen, Jorge Antunes, Alex Koloskov, Hugh Greenish, Tim Jones, Jose Ochoa, Michael Brennan-White, Naga Harish Muvva, Barkóczi Dávid, Kitt Hodsden, Paul McGraw, Sascha Goldhofer, Andrew Metcalf, Markus Krogh, Michael Mathews, Matt Jared, Juanfran, Georgie Kirschner, Kenny Lee, Ted Zhang, Amit Pahwa, Inbal Sinai, Dan Raine, Schabse Laks, Michael Tervoort, Alexandre Abreu, Alan Joseph Williams, NicolasD, Cindy Wong, Reg Braithwaite, LocalPCGuy, Jon Friskics, Chris Merriman, John Pena, Jacob Katz, Sue Lockwood, Magnus Johansson, Jeremy Crapsey, Grzegorz Pawłowski, nico nuzzaci, Christine Wilks, Hans Bergren, charles montgomery, Ariel בר-לבב Fogel, Ivan Kolev, Daniel Campos, Hugh Wood, Christian Bradford, Frédéric Harper, Ionuţ Dan Popa, Jeff Trimble, Rupert Wood, Trey Carrico, Pancho Lopez, Joël kuijten, Tom A Marra, Jeff Jewiss, Jacob Rios, Paolo Di Stefano, Soledad Penades, Chris Gerber, Andrey Dolganov, Wil Moore III, Thomas Martineau, Kareem, Ben Thouret, Udi Nir, Morgan Laupies, jory carson-burson, Nathan L Smith, Eric Damon Walters, Derry Lozano-Hoyland, Geoffrey Wiseman, mkeehner, KatieK, Scott MacFarlane, Brian LaShomb, Adrien Mas, christopher ross, Ian Littman, Dan Atkinson, Elliot Jobe, Nick Dozier, Peter Wooley, John Hoover, dan, Martin A. Jackson, Héctor Fernando Hurtado, andy ennamorato, Paul Seltmann, Melissa Gore, Dave Pollard, Jack Smith, Philip Da Silva, Guy Israeli, @megalithic, Damian Crawford, Felix Gliesche, April Carter Grant, Heidi, jim tierney, Andrea Giammarchi, Nico Vignola, Don Jones, Chris Hartjes, Alex Howes, john gibbon, David J. Groom, BBox, Yu 'Dilys' Sun, Nate Steiner, Brandon Satrom, Brian Wyant, Wesley Hales, Ian Pouncey, Timothy Kevin Oxley, George Terezakis, sanjay raj, Jordan Harband, Marko McLion, Wolfgang Kaufmann, Pascal Peuckert, Dave Nugent, Markus Liebelt, Welling Guzman, Nick Cooley, Daniel Mesquita, Robert Syvarth, Chris Coyier, Rémy Bach, Adam Dougal, Alistair Duggin, David Loidolt, Ed Richer, Brian Chenault, GoldFire Studios, Carles Andrés, Carlos Cabo, Yuya Saito, roberto ricardo, Barnett Klane, Mike Moore, Kevin Marx, Justin Love, Joe Taylor, Paul Dijou, Michael Kohler, Rob Cassie, Mike Tierney, Cody Leroy Lindley, tofuji, Shimon Schwartz, Raymond, Luc De Brouwer, David Hayes, Rhys Brett-Bowen, Dmitry, Aziz Khoury, Dean, Scott Tolinski - Level Up, Clement Boirie, Djordje Lukic, Anton Kotenko, Rafael Corral, Philip Hurwitz, Jonathan Pidgeon, Jason Campbell, Joseph C., SwiftOne, Jan Hohner, Derick Bailey, getify, Daniel Cousineau, Chris Charlton, Eric Turner, David Turner, Joël Galeran, Dharma Vagabond, adam, Dirk van Bergen, dave ♥♫★ furf, Vedran Zakanj, Ryan McAllen, Natalie Patrice Tucker, Eric J. Bivona, Adam Spooner, Aaron Cavano, Kelly Packer, Eric J, Martin Drenovac, Emilis, Michael Pelikan, Scott F. Walter, Josh Freeman, Brandon Hudgeons, vijay chennupati, Bill Glennon, Robin R., Troy Forster, otaku_coder, Brad, Scott, Frederick Ostrander, Adam Brill, Seb Flippence, Michael Anderson, Jacob, Adam Randlett, Standard, Joshua Clanton, Sebastian Kouba, Chris Deck, SwordFire, Hannes Papenberg, Richard Woeber, hnzz, Rob Crowther, Jedidiah Broadbent, Sergey Chernyshev, Jay-Ar Jamon, Ben Combee, luciano bonachela, Mark Tomlinson, Kit Cambridge, Michael Melgares, Jacob Adams, Adrian Bruinhout, Bev Wieber, Scott Puleo, Thomas Herzog, April Leone, Daniel Mizieliński, Kees van Ginkel, Jon Abrams, Erwin Heiser, Avi Laviad, David newell, Jean-Francois Turcot, Niko Roberts, Erik Dana, Charles Neill, Aaron Holmes, Grzegorz Ziółkowski, Nathan Youngman, Timothy, Jacob Mather, Michael Allan, Mohit Seth, Ryan Ewing, Benjamin Van Treese, Marcelo Santos, Denis Wolf, Phil Keys, Chris Yung, Timo Tijhof, Martin Lekvall, Agendine, Greg Whitworth, Helen Humphrey, Dougal Campbell, Johannes Harth, Bruno Girin, Brian Hough, Darren Newton, Craig McPheat, Olivier Tille, Dennis Roethig, Mathias Bynens, Brendan Stromberger, sundeep, John Meyer, Ron Male, John F Croston III, gigante, Carl Bergenhem, B.J. May, Rebekah Tyler, Ted Foxberry, Jordan Reese, Terry Suitor, afeliz, Tom Kiefer, Darragh Duffy, Kevin Vanderbeken, Andy Pearson, Simon Mac Donald, Abid Din, Chris Joel, Tomas Theunissen, David Dick, Paul Grock, Brandon Wood, John Weis, dgrebb, Nick Jenkins, Chuck Lane, Johnny Megahan, marzsman, Tatu Tamminen, Geoffrey Knauth, Alexander Tarmolov, Jeremy Tymes, Chad Auld, Sean Parmelee, Rob Staenke, Dan Bender, Yannick derwa, Joshua Jones, Geert Plaisier, Tom LeZotte, Christen Simpson, Stefan Bruvik, Justin Falcone, Carlos Santana, Michael Weiss, Pablo Villoslada, Peter deHaan, Dimitris Iliopoulos, seyDoggy, Adam Jordens, Noah Kantrowitz, Amol M, Matthew Winnard, Dirk Ginader, Phinam Bui, David Rapson, Andrew Baxter, Florian Bougel, Michael George, Alban Escalier, Daniel Sellers, Sasha Rudan, John Green, Robert Kowalski, David I. Teixeira (@ditma, Charles Carpenter, Justin Yost, Sam S, Denis Ciccale, Kevin Sheurs, Yannick Croissant, Pau Fracés, Stephen McGowan, Shawn Searcy, Chris Ruppel, Kevin Lamping, Jessica Campbell, Christopher Schmitt, Sablons, Jonathan Reisdorf, Bunni Gek, Teddy Huff, Michael Mullany, Michael Fürstenberg, Carl Henderson, Rick Yoesting, Scott Nichols, Hernán Ciudad, Andrew Maier, Mike Stapp, Jesse Shawl, Sérgio Lopes, jsulak, Shawn Price, Joel Clermont, Chris Ridmann, Sean Timm, Jason Finch, Aiden Montgomery, Elijah Manor, Derek Gathright, Jesse Harlin, Dillon Curry, Courtney Myers, Diego Cadenas, Arne de Bree, João Paulo Dubas, James Taylor, Philipp Kraeutli, Mihai Păun, Sam Gharegozlou, joshjs, Matt Murchison, Eric Windham, Timo Behrmann, Andrew Hall, joshua price, Théophile Villard 17 | 18 | This book series is being produced in an open source fashion, including editing and production. We owe GitHub a debt of gratitude for making that sort of thing possible for the community! 19 | 20 | Thank you again to all the countless folks I didn't name but who I nonetheless owe thanks. May this book series be "owned" by all of us and serve to contribute to increasing awareness and understanding of the JavaScript language, to the benefit of all current and future community contributors. 21 | -------------------------------------------------------------------------------- /es6 & beyond/ch1.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: ES6 & Beyond 2 | # Chapter 1: ES? Now & Future 3 | 4 | Before you dive into this book, you should have a solid working proficiency over JavaScript 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 forward. 5 | 6 | If you are still looking for confidence with JavaScript, I highly recommend you read the other titles in this series first: 7 | 8 | * *Up & Going*: Are you new to programming and JS? This is the roadmap you need to consult as you start your learning journey. 9 | * *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 lexical scope and functions as values? 10 | * *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 *objects linked to other objects* (OLOO)? 11 | * *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 comfortable are you with the nuances of JS grammar/syntax? 12 | * *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"? Do you know how to use generators to improve the legibility of async code? What exactly constitutes mature optimization of JS programs and individual operations? 13 | 14 | If you've already read all those titles and you feel pretty comfortable with the topics they cover, it's time we dive into the evolution of JS to explore all the changes coming not only soon but farther over the horizon. 15 | 16 | Unlike ES5, ES6 is not just a modest set of new APIs added to the language. It incorporates 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. 17 | 18 | ES6 is a radical jump forward for the language. Even if you think you know JS in ES5, ES6 is full of new stuff you *don't know yet*, so get ready! This book explores all the major themes of ES6 that you need to get up to speed on, and even gives you a glimpse of future features coming down the track that you should be aware of. 19 | 20 | **Warning:** All code in this book assumes an ES6+ environment. At the time of this writing, ES6 support varies quite a bit in browsers and JS environments (like Node.js), so your mileage may vary. 21 | 22 | ## Versioning 23 | 24 | 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"). 25 | 26 | The earliest versions, ES1 and ES2, were not widely known or implemented. ES3 was the first widespread baseline for JavaScript, and constitutes the JavaScript standard for browsers like IE6-8 and older Android 2.x mobile browsers. For political reasons beyond what we'll cover here, the ill-fated ES4 never came about. 27 | 28 | In 2009, ES5 was officially finalized (later ES5.1 in 2011), and settled as the widespread standard for JS for the modern revolution and explosion of browsers, such as Firefox, Chrome, Opera, Safari, and many others. 29 | 30 | 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. 31 | 32 | However, late into the ES6 specification timeline, suggestions have surfaced that versioning may in the future switch to a year-based schema, such as ES2016 (aka ES7) to refer to whatever version of the specification is finalized before the end of 2016. Some disagree, but ES6 will likely maintain its dominant mindshare over the late-change substitute ES2015. However, ES2016 may in fact signal the new year-based schema. 33 | 34 | 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, browsers start prototyping the feature, and early adopters start experimenting with the code. 35 | 36 | Usually well before there's an official stamp of approval, a feature is de facto standardized by virtue of this early engine/tooling prototyping. So it's also valid to consider the future of JS versioning to be per-feature rather than per-arbitrary-collection-of-major-features (as it is now) or even per-year (as it may become). 37 | 38 | The takeaway is that the version labels stop being as important, and JavaScript starts to be seen more as an evergreen, living standard. The best way to cope with this is to stop thinking about your code base as being "ES6-based," for instance, and instead consider it feature by feature for support. 39 | 40 | ## Transpiling 41 | 42 | Made even worse by the rapid evolution of features, a problem arises for JS developers 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 browsers without such support. 43 | 44 | 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 over five years ago. 45 | 46 | It's 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 features and patterns as soon as they stabilize in specification form and browsers have a chance to implement them. 47 | 48 | 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. 49 | 50 | For example, consider shorthand property definitions (see "Object Literal Extensions" in Chapter 2). Here's the ES6 form: 51 | 52 | ```js 53 | var foo = [1,2,3]; 54 | 55 | var obj = { 56 | foo // means `foo: foo` 57 | }; 58 | 59 | obj.foo; // [1,2,3] 60 | ``` 61 | 62 | But (roughly) here's how that transpiles: 63 | 64 | ```js 65 | var foo = [1,2,3]; 66 | 67 | var obj = { 68 | foo: foo 69 | }; 70 | 71 | obj.foo; // [1,2,3] 72 | ``` 73 | 74 | 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. 75 | 76 | Transpilers perform these transformations for you, usually in a build workflow step similar to how you perform linting, minification, and other similar operations. 77 | 78 | ### Shims/Polyfills 79 | 80 | 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. 81 | 82 | 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: 83 | 84 | ```js 85 | if (!Object.is) { 86 | Object.is = function(v1, v2) { 87 | // test for `-0` 88 | if (v1 === 0 && v2 === 0) { 89 | return 1 / v1 === 1 / v2; 90 | } 91 | // test for `NaN` 92 | if (v1 !== v1) { 93 | return v2 !== v2; 94 | } 95 | // everything else 96 | return v1 === v2; 97 | }; 98 | } 99 | ``` 100 | 101 | **Tip:** Pay attention to the outer `if` statement guard wrapped around the polyfill. This is an important detail, which means the snippet only defines its fallback behavior for older environments where the API in question isn't already defined; it would be very rare that you'd want to overwrite an existing API. 102 | 103 | There's a great collection of ES6 shims called "ES6 Shim" (https://github.com/paulmillr/es6-shim/) that you should definitely adopt as a standard part of any new JS project! 104 | 105 | It is assumed that JS will continue to evolve constantly, with browsers rolling out support for features continually rather than in large chunks. So the best strategy for keeping updated as it evolves is to just introduce polyfill shims into your code base, and a transpiler step into your build workflow, right now and get used to that new reality. 106 | 107 | If you decide to keep the status quo and just wait around for all browsers without a feature supported to go away before you start using the feature, you're always going to be way behind. You'll sadly be missing out on all the innovations designed to make writing JavaScript more effective, efficient, and robust. 108 | 109 | ## Review 110 | 111 | 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! 112 | 113 | 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. 114 | 115 | Now, JavaScript features land in browsers as they become ready, and it's up to you whether you'll get on the train early or whether you'll be playing costly catch-up games years from now. 116 | 117 | 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. 118 | 119 | 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! 120 | -------------------------------------------------------------------------------- /up & going/ch3.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: Up & Going 2 | # Chapter 3: Into YDKJS 3 | 4 | What is this series all about? Put simply, it's about taking seriously the task of learning *all parts of JavaScript*, not just some subset of the language that someone called "the good parts," and not just whatever minimal amount you need to get your job done at work. 5 | 6 | Serious developers in other languages expect to put in the effort to learn most or all of the language(s) they primarily write in, but JS developers seem to stand out from the crowd in the sense of typically not learning very much of the language. This is not a good thing, and it's not something we should continue to allow to be the norm. 7 | 8 | The *You Don't Know JS* (*YDKJS*) series stands in stark contrast to the typical approaches to learning JS, and is unlike almost any other JS books you will read. It challenges you to go beyond your comfort zone and to ask the deeper "why" questions for every single behavior you encounter. Are you up for that challenge? 9 | 10 | I'm going to use this final chapter to briefly summarize what to expect from the rest of the books in the series, and how to most effectively go about building a foundation of JS learning on top of *YDKJS*. 11 | 12 | ## Scope & Closures 13 | 14 | Perhaps one of the most fundamental things you'll need to quickly come to terms with is how scoping of variables really works in JavaScript. It's not enough to have anecdotal fuzzy *beliefs* about scope. 15 | 16 | The *Scope & Closures* title starts by debunking the common misconception that JS is an "interpreted language" and therefore not compiled. Nope. 17 | 18 | The JS engine compiles your code right before (and sometimes during!) execution. So we use some deeper understanding of the compiler's approach to our code to understand how it finds and deals with variable and function declarations. Along the way, we see the typical metaphor for JS variable scope management, "Hoisting." 19 | 20 | This critical understanding of "lexical scope" is what we then base our exploration of closure on for the last chapter of the book. Closure is perhaps the single most important concept in all of JS, but if you haven't first grasped firmly how scope works, closure will likely remain beyond your grasp. 21 | 22 | One important application of closure is the module pattern, as we briefly introduced in this book in Chapter 2. The module pattern is perhaps the most prevalent code organization pattern in all of JavaScript; deep understanding of it should be one of your highest priorities. 23 | 24 | ## this & Object Prototypes 25 | 26 | Perhaps one of the most widespread and persistent mistruths about JavaScript is that the `this` keyword refers to the function it appears in. Terribly mistaken. 27 | 28 | The `this` keyword is dynamically bound based on how the function in question is executed, and it turns out there are four simple rules to understand and fully determine `this` binding. 29 | 30 | Closely related to the `this` keyword is the object prototype mechanism, which is a look-up chain for properties, similar to how lexical scope variables are found. But wrapped up in the prototypes is the other huge miscue about JS: the idea of emulating (fake) classes and (so-called "prototypal") inheritance. 31 | 32 | Unfortunately, the desire to bring class and inheritance design pattern thinking to JavaScript is just about the worst thing you could try to do, because while the syntax may trick you into thinking there's something like classes present, in fact the prototype mechanism is fundamentally opposite in its behavior. 33 | 34 | What's at issue is whether it's better to ignore the mismatch and pretend that what you're implementing is "inheritance," or whether it's more appropriate to learn and embrace how the object prototype system actually works. The latter is more appropriately named "behavior delegation." 35 | 36 | This is more than syntactic preference. Delegation is an entirely different, and more powerful, design pattern, one that replaces the need to design with classes and inheritance. But these assertions will absolutely fly in the face of nearly every other blog post, book, and conference talk on the subject for the entirety of JavaScript's lifetime. 37 | 38 | The claims I make regarding delegation versus inheritance come not from a dislike of the language and its syntax, but from the desire to see the true capability of the language properly leveraged and the endless confusion and frustration wiped away. 39 | 40 | But the case I make regarding prototypes and delegation is a much more involved one than what I will indulge here. If you're ready to reconsider everything you think you know about JavaScript "classes" and "inheritance," I offer you the chance to "take the red pill" (*Matrix* 1999) and check out Chapters 4-6 of the *this & Object Prototypes* title of this series. 41 | 42 | ## Types & Grammar 43 | 44 | The third title in this series primarily focuses on tackling yet another highly controversial topic: type coercion. Perhaps no topic causes more frustration with JS developers than when you talk about the confusions surrounding implicit coercion. 45 | 46 | By far, the conventional wisdom is that implicit coercion is a "bad part" of the language and should be avoided at all costs. In fact, some have gone so far as to call it a "flaw" in the design of the language. Indeed, there are tools whose entire job is to do nothing but scan your code and complain if you're doing anything even remotely like coercion. 47 | 48 | But is coercion really so confusing, so bad, so treacherous, that your code is doomed from the start if you use it? 49 | 50 | I say no. After having built up an understanding of how types and values really work in Chapters 1-3, Chapter 4 takes on this debate and fully explains how coercion works, in all its nooks and crevices. We see just what parts of coercion really are surprising and what parts actually make complete sense if given the time to learn. 51 | 52 | But I'm not merely suggesting that coercion is sensible and learnable, I'm asserting that coercion is an incredibly useful and totally underestimated tool that *you should be using in your code.* I'm saying that coercion, when used properly, not only works, but makes your code better. All the naysayers and doubters will surely scoff at such a position, but I believe it's one of the main keys to upping your JS game. 53 | 54 | Do you want to just keep following what the crowd says, or are you willing to set all the assumptions aside and look at coercion with a fresh perspective? The *Types & Grammar* title of this series will coerce your thinking. 55 | 56 | ## Async & Performance 57 | 58 | The first three titles of this series focus on the core mechanics of the language, but the fourth title branches out slightly to cover patterns on top of the language mechanics for managing asynchronous programming. Asynchrony is not only critical to the performance of our applications, it's increasingly becoming *the* critical factor in writability and maintainability. 59 | 60 | The book starts first by clearing up a lot of terminology and concept confusion around things like "async," "parallel," and "concurrent," and explains in depth how such things do and do not apply to JS. 61 | 62 | Then we move into examining callbacks as the primary method of enabling asynchrony. But it's here that we quickly see that the callback alone is hopelessly insufficient for the modern demands of asynchronous programming. We identify two major deficiencies of callbacks-only coding: *Inversion of Control* (IoC) trust loss and lack of linear reason-ability. 63 | 64 | To address these two major deficiencies, ES6 introduces two new mechanisms (and indeed, patterns): promises and generators. 65 | 66 | Promises are a time-independent wrapper around a "future value," which lets you reason about and compose them regardless of if the value is ready or not yet. Moreover, they effectively solve the IoC trust issues by routing callbacks through a trustable and composable promise mechanism. 67 | 68 | Generators introduce a new mode of execution for JS functions, whereby the generator can be paused at `yield` points and be resumed asynchronously later. The pause-and-resume capability enables synchronous, sequential looking code in the generator to be processed asynchronously behind the scenes. By doing so, we address the non-linear, non-local-jump confusions of callbacks and thereby make our asynchronous code sync-looking so as to be more reason-able. 69 | 70 | But it's the combination of promises and generators that "yields" our most effective asynchronous coding pattern to date in JavaScript. In fact, much of the future sophistication of asynchrony coming in ES7 and later will certainly be built on this foundation. To be serious about programming effectively in an async world, you're going to need to get really comfortable with combining promises and generators. 71 | 72 | If promises and generators are about expressing patterns that let our programs run more concurrently and thus get more processing accomplished in a shorter period, JS has many other facets of performance optimization worth exploring. 73 | 74 | Chapter 5 delves into topics like program parallelism with Web Workers and data parallelism with SIMD, as well as low-level optimization techniques like ASM.js. Chapter 6 takes a look at performance optimization from the perspective of proper benchmarking techniques, including what kinds of performance to worry about and what to ignore. 75 | 76 | Writing JavaScript effectively means writing code that can break the constraint barriers of being run dynamically in a wide range of browsers and other environments. It requires a lot of intricate and detailed planning and effort on our parts to take a program from "it works" to "it works well." 77 | 78 | The *Async & Performance* title is designed to give you all the tools and skills you need to write reasonable and performant JavaScript code. 79 | 80 | ## ES6 & Beyond 81 | 82 | No matter how much you feel you've mastered JavaScript to this point, the truth is that JavaScript is never going to stop evolving, and moreover, the rate of evolution is increasing rapidly. This fact is almost a metaphor for the spirit of this series, to embrace that we'll never fully *know* every part of JS, because as soon as you master it all, there's going to be new stuff coming down the line that you'll need to learn. 83 | 84 | This title is dedicated to both the short- and mid-term visions of where the language is headed, not just the *known* stuff like ES6 but the *likely* stuff beyond. 85 | 86 | While all the titles of this series embrace the state of JavaScript at the time of this writing, which is mid-way through ES6 adoption, the primary focus in the series has been more on ES5. Now, we want to turn our attention to ES6, ES7, and ... 87 | 88 | Since ES6 is nearly complete at the time of this writing, *ES6 & Beyond* starts by dividing up the concrete stuff from the ES6 landscape into several key categories, including new syntax, new data structures (collections), and new processing capabilities and APIs. We cover each of these new ES6 features, in varying levels of detail, including reviewing details that are touched on in other books of this series. 89 | 90 | Some exciting ES6 things to look forward to reading about: destructuring, default parameter values, symbols, concise methods, computed properties, arrow functions, block scoping, promises, generators, iterators, modules, proxies, weakmaps, and much, much more! Phew, ES6 packs quite a punch! 91 | 92 | The first part of the book is a roadmap for all the stuff you need to learn to get ready for the new and improved JavaScript you'll be writing and exploring over the next couple of years. 93 | 94 | The latter part of the book turns attention to briefly glance at things that we can likely expect to see in the near future of JavaScript. The most important realization here is that post-ES6, JS is likely going to evolve feature by feature rather than version by version, which means we can expect to see these near-future things coming much sooner than you might imagine. 95 | 96 | The future for JavaScript is bright. Isn't it time we start learning it!? 97 | 98 | ## Review 99 | 100 | The *YDKJS* series is dedicated to the proposition that all JS developers can and should learn all of the parts of this great language. No person's opinion, no framework's assumptions, and no project's deadline should be the excuse for why you never learn and deeply understand JavaScript. 101 | 102 | We take each important area of focus in the language and dedicate a short but very dense book to fully explore all the parts of it that you perhaps thought you knew but probably didn't fully. 103 | 104 | "You Don't Know JS" isn't a criticism or an insult. It's a realization that all of us, myself included, must come to terms with. Learning JavaScript isn't an end goal but a process. We don't know JavaScript, yet. But we will! 105 | -------------------------------------------------------------------------------- /this & object prototypes/ch1.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: *this* & Object Prototypes 2 | # Chapter 1: `this` Or That? 3 | 4 | One of the most confused mechanisms in JavaScript is the `this` keyword. It's a special identifier keyword that's automatically defined in the scope of every function, but what exactly it refers to bedevils even seasoned JavaScript developers. 5 | 6 | > Any sufficiently *advanced* technology is indistinguishable from magic. -- Arthur C. Clarke 7 | 8 | JavaScript's `this` mechanism isn't actually *that* advanced, but developers often paraphrase that quote in their own mind by inserting "complex" or "confusing", and there's no question that without lack of clear understanding, `this` can seem downright magical in *your* confusion. 9 | 10 | **Note:** The word "this" is a terribly common pronoun in general discourse. So, it can be very difficult, especially verbally, to determine whether we are using "this" as a pronoun or using it to refer to the actual keyword identifier. For clarity, I will always use `this` to refer to the special keyword, and "this" or *this* or this otherwise. 11 | 12 | ## Why `this`? 13 | 14 | If the `this` mechanism is so confusing, even to seasoned JavaScript developers, one may wonder why it's even useful? Is it more trouble than it's worth? Before we jump into the *how*, we should examine the *why*. 15 | 16 | Let's try to illustrate the motivation and utility of `this`: 17 | 18 | ```js 19 | function identify() { 20 | return this.name.toUpperCase(); 21 | } 22 | 23 | function speak() { 24 | var greeting = "Hello, I'm " + identify.call( this ); 25 | console.log( greeting ); 26 | } 27 | 28 | var me = { 29 | name: "Kyle" 30 | }; 31 | 32 | var you = { 33 | name: "Reader" 34 | }; 35 | 36 | identify.call( me ); // KYLE 37 | identify.call( you ); // READER 38 | 39 | speak.call( me ); // Hello, I'm KYLE 40 | speak.call( you ); // Hello, I'm READER 41 | ``` 42 | 43 | If the *how* of this snippet confuses you, don't worry! We'll get to that shortly. Just set those questions aside briefly so we can look into the *why* more clearly. 44 | 45 | This code snippet allows the `identify()` and `speak()` functions to be re-used against multiple *context* (`me` and `you`) objects, rather than needing a separate version of the function for each object. 46 | 47 | Instead of relying on `this`, you could have explicitly passed in a context object to both `identify()` and `speak()`. 48 | 49 | ```js 50 | function identify(context) { 51 | return context.name.toUpperCase(); 52 | } 53 | 54 | function speak(context) { 55 | var greeting = "Hello, I'm " + identify( context ); 56 | console.log( greeting ); 57 | } 58 | 59 | identify( you ); // READER 60 | speak( me ); // Hello, I'm KYLE 61 | ``` 62 | 63 | However, the `this` mechanism provides a more elegant way of implicitly "passing along" an object reference, leading to cleaner API design and easier re-use. 64 | 65 | The more complex your usage pattern is, the more clearly you'll see that passing context around as an explicit parameter is often messier than passing around a `this` context. When we explore objects and prototypes, you will see the helpfulness of a collection of functions being able to automatically reference the proper context object. 66 | 67 | ## Confusions 68 | 69 | We'll soon begin to explain how `this` *actually* works, but first we must dispel some misconceptions about how it *doesn't* actually work. 70 | 71 | The name "this" creates confusion when developers try to think about it too literally. There are two meanings often assumed, but both are incorrect. 72 | 73 | ### Itself 74 | 75 | The first common temptation is to assume `this` refers to the function itself. That's a reasonable grammatical inference, at least. 76 | 77 | Why would you want to refer to a function from inside itself? The most common reasons would be things like recursion (calling a function from inside itself) or having an event handler that can unbind itself when it's first called. 78 | 79 | Developers new to JS's mechanisms often think that referencing the function as an object (all functions in JavaScript are objects!) lets you store *state* (values in properties) between function calls. While this is certainly possible and has some limited uses, the rest of the book will expound on many other patterns for *better* places to store state besides the function object. 80 | 81 | But for just a moment, we'll explore that pattern, to illustrate how `this` doesn't let a function get a reference to itself like we might have assumed. 82 | 83 | Consider the following code, where we attempt to track how many times a function (`foo`) was called: 84 | 85 | ```js 86 | function foo(num) { 87 | console.log( "foo: " + num ); 88 | 89 | // keep track of how many times `foo` is called 90 | this.count++; 91 | } 92 | 93 | foo.count = 0; 94 | 95 | var i; 96 | 97 | for (i=0; i<10; i++) { 98 | if (i > 5) { 99 | foo( i ); 100 | } 101 | } 102 | // foo: 6 103 | // foo: 7 104 | // foo: 8 105 | // foo: 9 106 | 107 | // how many times was `foo` called? 108 | console.log( foo.count ); // 0 -- WTF? 109 | ``` 110 | 111 | `foo.count` is *still* `0`, even though the four `console.log` statements clearly indicate `foo(..)` was in fact called four times. The frustration stems from a *too literal* interpretation of what `this` (in `this.count++`) means. 112 | 113 | When the code executes `foo.count = 0`, indeed it's adding a property `count` to the function object `foo`. But for the `this.count` reference inside of the function, `this` is not in fact pointing *at all* to that function object, and so even though the property names are the same, the root objects are different, and confusion ensues. 114 | 115 | **Note:** A responsible developer *should* ask at this point, "If I was incrementing a `count` property but it wasn't the one I expected, which `count` *was* I incrementing?" In fact, were she to dig deeper, she would find that she had accidentally created a global variable `count` (see Chapter 2 for *how* that happened!), and it currently has the value `NaN`. Of course, once she identifies this peculiar outcome, she then has a whole other set of questions: "How was it global, and why did it end up `NaN` instead of some proper count value?" (see Chapter 2). 116 | 117 | Instead of stopping at this point and digging into why the `this` reference doesn't seem to be behaving as *expected*, and answering those tough but important questions, many developers simply avoid the issue altogether, and hack toward some other solution, such as creating another object to hold the `count` property: 118 | 119 | ```js 120 | function foo(num) { 121 | console.log( "foo: " + num ); 122 | 123 | // keep track of how many times `foo` is called 124 | data.count++; 125 | } 126 | 127 | var data = { 128 | count: 0 129 | }; 130 | 131 | var i; 132 | 133 | for (i=0; i<10; i++) { 134 | if (i > 5) { 135 | foo( i ); 136 | } 137 | } 138 | // foo: 6 139 | // foo: 7 140 | // foo: 8 141 | // foo: 9 142 | 143 | // how many times was `foo` called? 144 | console.log( data.count ); // 4 145 | ``` 146 | 147 | While it is true that this approach "solves" the problem, unfortunately it simply ignores the real problem -- lack of understanding what `this` means and how it works -- and instead falls back to the comfort zone of a more familiar mechanism: lexical scope. 148 | 149 | **Note:** Lexical scope is a perfectly fine and useful mechanism; I am not belittling the use of it, by any means (see *"Scope & Closures"* title of this book series). But constantly *guessing* at how to use `this`, and usually being *wrong*, is not a good reason to retreat back to lexical scope and never learn *why* `this` eludes you. 150 | 151 | To reference a function object from inside itself, `this` by itself will typically be insufficient. You generally need a reference to the function object via a lexical identifier (variable) that points at it. 152 | 153 | Consider these two functions: 154 | 155 | ```js 156 | function foo() { 157 | foo.count = 4; // `foo` refers to itself 158 | } 159 | 160 | setTimeout( function(){ 161 | // anonymous function (no name), cannot 162 | // refer to itself 163 | }, 10 ); 164 | ``` 165 | 166 | In the first function, called a "named function", `foo` is a reference that can be used to refer to the function from inside itself. 167 | 168 | But in the second example, the function callback passed to `setTimeout(..)` has no name identifier (so called an "anonymous function"), so there's no proper way to refer to the function object itself. 169 | 170 | **Note:** The old-school but now deprecated and frowned-upon `arguments.callee` reference inside a function *also* points to the function object of the currently executing function. This reference is typically the only way to access an anonymous function's object from inside itself. The best approach, however, is to avoid the use of anonymous functions altogether, at least for those which require a self-reference, and instead use a named function (expression). `arguments.callee` is deprecated and should not be used. 171 | 172 | So another solution to our running example would have been to use the `foo` identifier as a function object reference in each place, and not use `this` at all, which *works*: 173 | 174 | ```js 175 | function foo(num) { 176 | console.log( "foo: " + num ); 177 | 178 | // keep track of how many times `foo` is called 179 | foo.count++; 180 | } 181 | 182 | foo.count = 0; 183 | 184 | var i; 185 | 186 | for (i=0; i<10; i++) { 187 | if (i > 5) { 188 | foo( i ); 189 | } 190 | } 191 | // foo: 6 192 | // foo: 7 193 | // foo: 8 194 | // foo: 9 195 | 196 | // how many times was `foo` called? 197 | console.log( foo.count ); // 4 198 | ``` 199 | 200 | However, that approach similarly side-steps *actual* understanding of `this` and relies entirely on the lexical scoping of variable `foo`. 201 | 202 | Yet another way of approaching the issue is to force `this` to actually point at the `foo` function object: 203 | 204 | ```js 205 | function foo(num) { 206 | console.log( "foo: " + num ); 207 | 208 | // keep track of how many times `foo` is called 209 | // Note: `this` IS actually `foo` now, based on 210 | // how `foo` is called (see below) 211 | this.count++; 212 | } 213 | 214 | foo.count = 0; 215 | 216 | var i; 217 | 218 | for (i=0; i<10; i++) { 219 | if (i > 5) { 220 | // using `call(..)`, we ensure the `this` 221 | // points at the function object (`foo`) itself 222 | foo.call( foo, i ); 223 | } 224 | } 225 | // foo: 6 226 | // foo: 7 227 | // foo: 8 228 | // foo: 9 229 | 230 | // how many times was `foo` called? 231 | console.log( foo.count ); // 4 232 | ``` 233 | 234 | **Instead of avoiding `this`, we embrace it.** We'll explain in a little bit *how* such techniques work much more completely, so don't worry if you're still a bit confused! 235 | 236 | ### Its Scope 237 | 238 | The next most common misconception about the meaning of `this` is that it somehow refers to the function's scope. It's a tricky question, because in one sense there is some truth, but in the other sense, it's quite misguided. 239 | 240 | To be clear, `this` does not, in any way, refer to a function's **lexical scope**. It is true that internally, scope is kind of like an object with properties for each of the available identifiers. But the scope "object" is not accessible to JavaScript code. It's an inner part of the *Engine*'s implementation. 241 | 242 | Consider code which attempts (and fails!) to cross over the boundary and use `this` to implicitly refer to a function's lexical scope: 243 | 244 | ```js 245 | function foo() { 246 | var a = 2; 247 | this.bar(); 248 | } 249 | 250 | function bar() { 251 | console.log( this.a ); 252 | } 253 | 254 | foo(); //undefined 255 | ``` 256 | 257 | There's more than one mistake in this snippet. While it may seem contrived, the code you see is a distillation of actual real-world code that has been exchanged in public community help forums. It's a wonderful (if not sad) illustration of just how misguided `this` assumptions can be. 258 | 259 | Firstly, an attempt is made to reference the `bar()` function via `this.bar()`. It is almost certainly an *accident* that it works, but we'll explain the *how* of that shortly. The most natural way to have invoked `bar()` would have been to omit the leading `this.` and just make a lexical reference to the identifier. 260 | 261 | However, the developer who writes such code is attempting to use `this` to create a bridge between the lexical scopes of `foo()` and `bar()`, so that `bar()` has access to the variable `a` in the inner scope of `foo()`. **No such bridge is possible.** You cannot use a `this` reference to look something up in a lexical scope. It is not possible. 262 | 263 | Every time you feel yourself trying to mix lexical scope look-ups with `this`, remind yourself: *there is no bridge*. 264 | 265 | ## What's `this`? 266 | 267 | Having set aside various incorrect assumptions, let us now turn our attention to how the `this` mechanism really works. 268 | 269 | We said earlier that `this` is not an author-time binding but a runtime binding. It is contextual based on the conditions of the function's invocation. `this` binding has nothing to do with where a function is declared, but has instead everything to do with the manner in which the function is called. 270 | 271 | When a function is invoked, an activation record, otherwise known as an execution context, is created. This record contains information about where the function was called from (the call-stack), *how* the function was invoked, what parameters were passed, etc. One of the properties of this record is the `this` reference which will be used for the duration of that function's execution. 272 | 273 | In the next chapter, we will learn to find a function's **call-site** to determine how its execution will bind `this`. 274 | 275 | ## Review (TL;DR) 276 | 277 | `this` binding is a constant source of confusion for the JavaScript developer who does not take the time to learn how the mechanism actually works. Guesses, trial-and-error, and blind copy-n-paste from Stack Overflow answers is not an effective or proper way to leverage *this* important `this` mechanism. 278 | 279 | To learn `this`, you first have to learn what `this` is *not*, despite any assumptions or misconceptions that may lead you down those paths. `this` is neither a reference to the function itself, nor is it a reference to the function's *lexical* scope. 280 | 281 | `this` is actually a binding that is made when a function is invoked, and *what* it references is determined entirely by the call-site where the function is called. 282 | -------------------------------------------------------------------------------- /this & object prototypes/apA.md: -------------------------------------------------------------------------------- 1 | # You Don't Know JS: *this* & Object Prototypes 2 | # Appendix A: ES6 `class` 3 | 4 | If there's any take-away message from the second half of this book (Chapters 4-6), it's that classes are an optional design pattern for code (not a necessary given), and that furthermore they are often quite awkward to implement in a `[[Prototype]]` language like JavaScript. 5 | 6 | This awkwardness is *not* just about syntax, although that's a big part of it. Chapters 4 and 5 examined quite a bit of syntactic ugliness, from verbosity of `.prototype` references cluttering the code, to *explicit pseudo-polymorphism* (see Chapter 4) when you give methods the same name at different levels of the chain and try to implement a polymorphic reference from a lower-level method to a higher-level method. `.constructor` being wrongly interpreted as "was constructed by" and yet being unreliable for that definition is yet another syntactic ugly. 7 | 8 | But the problems with class design are much deeper. Chapter 4 points out that classes in traditional class-oriented languages actually produce a *copy* action from parent to child to instance, whereas in `[[Prototype]]`, the action is **not** a copy, but rather the opposite -- a delegation link. 9 | 10 | When compared to the simplicity of OLOO-style code and behavior delegation (see Chapter 6), which embrace `[[Prototype]]` rather than hide from it, classes stand out as a sore thumb in JS. 11 | 12 | ## `class` 13 | 14 | But we *don't* need to re-argue that case again. I re-mention those issues briefly only so that you keep them fresh in your mind now that we turn our attention to the ES6 `class` mechanism. We'll demonstrate here how it works, and look at whether or not `class` does anything substantial to address any of those "class" concerns. 15 | 16 | Let's revisit the `Widget` / `Button` example from Chapter 6: 17 | 18 | ```js 19 | class Widget { 20 | constructor(width,height) { 21 | this.width = width || 50; 22 | this.height = height || 50; 23 | this.$elem = null; 24 | } 25 | render($where){ 26 | if (this.$elem) { 27 | this.$elem.css( { 28 | width: this.width + "px", 29 | height: this.height + "px" 30 | } ).appendTo( $where ); 31 | } 32 | } 33 | } 34 | 35 | class Button extends Widget { 36 | constructor(width,height,label) { 37 | super( width, height ); 38 | this.label = label || "Default"; 39 | this.$elem = $( "