A Modern Introduction to Programming
Total Page:16
File Type:pdf, Size:1020Kb
Eloquent JavaScript A Modern Introduction to Programming Marijn Haverbeke Copyright © 2014 by Marijn Haverbeke This work is licensed under a Creative Commons attribution-noncommercial license (http://creativecommons.org/licenses/by-nc/3.0/). All code in the book may also be considered licensed under an MIT license (http://opensource. org/licenses/MIT). The illustrations are contributed by various artists: Cover by Wasif Hyder. Computer (introduction) and unicycle people (Chapter 21) by Max Xiantu. Sea of bits (Chapter 1) and weresquirrel (Chapter 4) by Margarita Martínez and José Menor. Octopuses (Chapter 2 and 4) by Jim Tierney. Object with on/off switch (Chapter 6) by Dyle MacGre- gor. Regular expression diagrams in Chapter 9 generated with regex- per.com by Jeff Avallone. Game concept for Chapter 15by Thomas Palef. Pixel art in Chapter 16 by Antonio Perdomo Pastor. The second edition of Eloquent JavaScript was made possible by 454 financial backers. You can buy a print version of this book, with an extra bonus chapter included, printed by No Starch Press at http://www.amazon.com/gp/product/ 1593275846/ref=as_li_qf_sp_asin_il_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN= 1593275846&linkCode=as2&tag=marijhaver-20&linkId=VPXXXSRYC5COG5R5. i Contents On programming .......................... 2 Why language matters ....................... 5 What is JavaScript? ......................... 9 Code, and what to do with it ................... 11 Overview of this book ........................ 12 Typographic conventions ...................... 14 1 Values, Types, and Operators 15 Values ................................. 16 Numbers ............................... 17 Strings ................................ 21 Unary operators ........................... 22 Boolean values ............................ 23 Undefined values ........................... 26 Automatic type conversion ..................... 27 Summary ............................... 30 2 Program Structure 32 Expressions and statements .................... 32 Variables ............................... 34 ii Keywords and reserved words ................... 37 The environment .......................... 37 Functions ............................... 38 The console.log function ...................... 39 Return values ............................ 39 prompt and confirm ......................... 40 Control flow ............................. 41 Conditional execution ........................ 42 while and do loops .......................... 44 Indenting Code ........................... 48 for loops ............................... 48 Breaking Out of a Loop ...................... 49 Updating variables succinctly ................... 51 Dispatching on a value with switch . 51 Capitalization ............................ 53 Comments .............................. 53 Summary ............................... 55 Exercises ............................... 55 3 Functions 59 Defining a function ......................... 59 Parameters and scopes ....................... 61 Nested scope ............................. 63 Functions as values ......................... 65 Declaration notation ........................ 66 The call stack ............................ 67 Optional Arguments ......................... 69 iii Closure ................................ 71 Recursion ............................... 73 Growing functions .......................... 77 Functions and side effects ..................... 81 Summary ............................... 82 Exercises ............................... 83 4 Data Structures: Objects and Arrays 85 The weresquirrel ........................... 86 Data sets ............................... 87 Properties .............................. 88 Methods ............................... 90 Objects ................................ 91 Mutability .............................. 96 The lycanthrope’s log ........................ 97 Computing correlation . 100 Objects as maps . 102 The final analysis . 104 Further arrayology . 107 Strings and their properties . 109 The arguments object . 110 The Math object . 112 The global object . 115 Summary ...............................115 Exercises ...............................116 iv 5 Higher-Order Functions 120 Abstraction ..............................121 Abstracting array traversal . 122 Higher-order functions . 126 Passing along arguments . 128 JSON .................................129 Filtering an array . 131 Transforming with map . 132 Summarizing with reduce . 133 Composability ............................135 The cost ...............................136 Great-great-great-great-… . 138 Binding ................................142 Summary ...............................143 Exercises ...............................144 6 The Secret Life of Objects 146 History ................................146 Methods ...............................148 Prototypes ..............................150 Constructors .............................152 Overriding derived properties . 153 Prototype interference . 155 Prototype-less objects . 158 Polymorphism ............................159 Laying out a table . 160 Getters and setters . 168 v Inheritance ..............................170 The instanceof operator . 172 Summary ...............................173 Exercises ...............................174 7 Project: Electronic Life 176 Definition ...............................176 Representing space . 178 A critter’s programming interface . 180 The world object . 183 this and its scope . 185 Animating life ............................188 It moves ...............................192 More life forms ............................193 A more lifelike simulation . 195 Action handlers . 197 Populating the new world . 199 Bringing it to life . 201 Exercises ...............................203 8 Bugs and Error Handling 205 Programmer mistakes . 205 Strict mode ..............................207 Testing ................................209 Debugging ..............................210 Error propagation . 213 Exceptions ..............................214 vi Cleaning up after exceptions . 217 Selective catching . 219 Assertions ..............................222 Summary ...............................224 Exercises ...............................224 9 Regular Expressions 226 Creating a regular expression . 226 Testing for matches . 228 Matching a set of characters . 228 Repeating parts of a pattern . 230 Grouping subexpressions . 232 Matches and groups . 233 The date type ............................234 Word and string boundaries . 236 Choice patterns . 237 The mechanics of matching . 238 Backtracking .............................240 The replace method . 243 Greed .................................245 Dynamically creating RegExp objects . 247 The search method . 248 The lastIndex property . 249 Parsing an INI file . 251 International characters . 254 Summary ...............................255 Exercises ...............................257 vii 10 Modules 260 Why modules help . 260 Using functions as namespaces . 264 Objects as interfaces . 266 Detaching from the global scope . 268 Evaluating data as code . 269 Require ................................270 Slow-loading modules . 273 Interface design . 277 Summary ...............................280 Exercises ...............................281 11 Project: A Programming Language 284 Parsing ................................284 The evaluator ............................291 Special forms .............................293 The environment . 295 Functions ...............................298 Compilation .............................299 Cheating ...............................300 Exercises ...............................302 12 JavaScript and the Browser 305 Networks and the Internet . 306 The Web ...............................308 HTML ................................309 HTML and JavaScript . 312 viii In the sandbox ............................314 Compatibility and the browser wars . 315 13 The Document Object Model 317 Document structure . 317 Trees .................................320 The standard .............................322 Moving through the tree . 323 Finding elements . 325 Changing the document . 326 Creating nodes ............................327 Attributes ..............................330 Layout ................................334 Styling ................................336 Cascading styles . 339 Query selectors ............................341 Positioning and animating . 342 Summary ...............................346 Exercises ...............................346 14 Handling Events 349 Event handlers ............................349 Events and DOM nodes . 350 Event objects .............................352 Propagation .............................353 Default actions ............................355 Key events ..............................356 ix Mouse clicks .............................359 Mouse motion ............................360 Scroll events .............................364 Focus events .............................366 Load event ..............................367 Script execution timeline . 368 Setting timers ............................370 Debouncing ..............................372 Summary ...............................374 Exercises ...............................375 15 Project: A Platform Game 377 The game ...............................378 The technology . 379 Levels .................................380 Reading a level ............................381 Actors .................................383 Encapsulation as a burden . 387 Drawing ................................388