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 MacGregor. Regular expression diagrams in Chapter 9 generated with regexper.com by Jeff Avallone. Game concept for Chapter 15 by 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 ........................... 3 What is JavaScript? ............................. 6 Code, and what to do with it ....................... 7 Overview of this book ............................ 8 Typographic conventions .......................... 9 1 Values, Types, and Operators 10 Values ..................................... 10 Numbers ................................... 11 Strings .................................... 14 Unary operators ............................... 15 Boolean values ................................ 15 Undefined values ............................... 17 Automatic type conversion ......................... 18 Summary ................................... 20 2 Program Structure 21 Expressions and statements ........................ 21 Variables ................................... 22 Keywords and reserved words ....................... 24 The environment .............................. 24 Functions ................................... 24 The console.log function .......................... 25 Return values ................................ 25 prompt and confirm ............................. 26 Control flow ................................. 27 Conditional execution ............................ 27 while and do loops .............................. 29 Indenting Code ............................... 31 for loops ................................... 31 Breaking Out of a Loop .......................... 32 Updating variables succinctly ....................... 32 ii Dispatching on a value with switch .................... 33 Capitalization ................................ 34 Comments .................................. 34 Summary ................................... 35 Exercises ................................... 36 3 Functions 38 Defining a function ............................. 38 Parameters and scopes ........................... 39 Nested scope ................................. 40 Functions as values ............................. 42 Declaration notation ............................ 42 The call stack ................................ 43 Optional Arguments ............................. 44 Closure .................................... 45 Recursion ................................... 47 Growing functions .............................. 49 Functions and side effects ......................... 52 Summary ................................... 52 Exercises ................................... 53 4 Data Structures: Objects and Arrays 55 The weresquirrel ............................... 55 Data sets ................................... 56 Properties .................................. 57 Methods ................................... 58 Objects .................................... 59 Mutability .................................. 62 The lycanthrope’s log ............................ 63 Computing correlation ........................... 64 Objects as maps ............................... 66 The final analysis .............................. 67 Further arrayology .............................. 69 Strings and their properties ........................ 70 The arguments object ............................ 71 The Math object ............................... 72 The global object .............................. 74 Summary ................................... 74 Exercises ................................... 75 iii 5 Higher-Order Functions 78 Abstraction .................................. 78 Abstracting array traversal ......................... 79 Higher-order functions ........................... 81 Passing along arguments .......................... 83 JSON ..................................... 84 Filtering an array .............................. 85 Transforming with map ........................... 86 Summarizing with reduce .......................... 86 Composability ................................ 87 The cost ................................... 88 Great-great-great-great-… .......................... 89 Binding .................................... 92 Summary ................................... 93 Exercises ................................... 93 6 The Secret Life of Objects 95 History .................................... 95 Methods ................................... 97 Prototypes .................................. 98 Constructors ................................. 99 Overriding derived properties . 100 Prototype interference . 101 Prototype-less objects ............................103 Polymorphism ................................104 Laying out a table ..............................104 Getters and setters .............................110 Inheritance ..................................111 The instanceof operator . 113 Summary ...................................113 Exercises ...................................114 7 Project: Electronic Life 115 Definition ...................................115 Representing space .............................116 A critter’s programming interface . 117 The world object ..............................119 this and its scope ..............................121 Animating life ................................122 It moves ...................................125 iv More life forms ................................125 A more lifelike simulation . 127 Action handlers ...............................128 Populating the new world . 129 Bringing it to life ..............................130 Exercises ...................................132 8 Bugs and Error Handling 134 Programmer mistakes ............................134 Strict mode ..................................135 Testing ....................................136 Debugging ..................................137 Error propagation ..............................139 Exceptions ..................................140 Cleaning up after exceptions . 141 Selective catching ..............................142 Assertions ..................................145 Summary ...................................145 Exercises ...................................146 9 Regular Expressions 147 Creating a regular expression . 147 Testing for matches .............................148 Matching a set of characters . 148 Repeating parts of a pattern . 150 Grouping subexpressions . 151 Matches and groups .............................151 The date type ................................152 Word and string boundaries . 153 Choice patterns ...............................154 The mechanics of matching . 154 Backtracking .................................156 The replace method .............................158 Greed .....................................159 Dynamically creating RegExp objects . 160 The search method .............................161 The lastIndex property . 162 Parsing an INI file ..............................163 International characters . 165 Summary ...................................166 v Exercises ...................................167 10 Modules 169 Why modules help ..............................169 Using functions as namespaces . 171 Objects as interfaces ............................173 Detaching from the global scope . 174 Evaluating data as code . 174 Require ....................................175 Slow-loading modules ............................177 Interface design ...............................180 Summary ...................................182 Exercises ...................................182 11 Project: A Programming Language 184 Parsing ....................................184 The evaluator ................................188 Special forms .................................190 The environment ..............................191 Functions ...................................193 Compilation .................................194 Cheating ...................................194 Exercises ...................................195 12 JavaScript and the Browser 198 Networks and the Internet . 198 The Web ...................................199 HTML ....................................200 HTML and JavaScript . 202 In the sandbox ................................203 Compatibility and the browser wars . 204 13 The Document Object Model 206 Document structure .............................206 Trees .....................................207 The standard .................................209 Moving through the tree . 209 Finding elements