Eloquent JavaScript

Jan 9, 2017 | Publisher: edocr | Category: Technology |  | Collection: ebooks | Views: 26 | Likes: 1

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 . . . . . . . . . . . . . . . . . . . . . . . 4 What is JavaScript? . . . . . . . . . . . . . . . . . . . . . . . . . 6 Code, and what to do with it . . . . . . . . . . . . . . . . . . . 8 Overview of this book . . . . . . . . . . . . . . . . . . . . . . . . 9 Typographic conventions . . . . . . . . . . . . . . . . . . . . . . 10 1 Values, Types, and Operators 11 Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Unary operators . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 Boolean values . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 Undefined values . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 Automatic type conversion . . . . . . . . . . . . . . . . . . . . . 19 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 2 Program Structure 23 Expressions and statements . . . . . . . . . . . . . . . . . . . . 23 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 Keywords and reserved words . . . . . . . . . . . . . . . . . . . 26 The environment . . . . . . . . . . . . . . . . . . . . . . . . . . 27 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 The console.log function . . . . . . . . . . . . . . . . . . . . . . 28 Return values . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 prompt and confirm . . . . . . . . . . . . . . . . . . . . . . . . . 29 Control flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 Conditional execution . . . . . . . . . . . . . . . . . . . . . . . . 30 while and do loops . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Indenting Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 ii for loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 Breaking Out of a Loop . . . . . . . . . . . . . . . . . . . . . . 36 Updating variables succinctly . . . . . . . . . . . . . . . . . . . 36 Dispatching on a value with switch . . . . . . . . . . . . . . . . 37 Capitalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 3 Functions 42 Defining a function . . . . . . . . . . . . . . . . . . . . . . . . . 42 Parameters and scopes . . . . . . . . . . . . . . . . . . . . . . . 43 Nested scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Functions as values . . . . . . . . . . . . . . . . . . . . . . . . . 46 Declaration notation . . . . . . . . . . . . . . . . . . . . . . . . 47 The call stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 Optional Arguments . . . . . . . . . . . . . . . . . . . . . . . . . 49 Closure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 Growing functions . . . . . . . . . . . . . . . . . . . . . . . . . . 55 Functions and side effects . . . . . . . . . . . . . . . . . . . . . 58 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 4 Data Structures: Objects and Arrays 61 The weresquirrel . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 Data sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 Mutability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 The lycanthrope’s log . . . . . . . . . . . . . . . . . . . . . . . . 69 Computing correlation . . . . . . . . . . . . . . . . . . . . . . . 71 Objects as maps . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 The final analysis . . . . . . . . . . . . . . . . . . . . . . . . . . 74 Further arrayology . . . . . . . . . . . . . . . . . . . . . . . . . . 76 Strings and their properties . . . . . . . . . . . . . . . . . . . . 78 iii The arguments object . . . . . . . . . . . . . . . . . . . . . . . . 79 The Math object . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 The global object . . . . . . . . . . . . . . . . . . . . . . . . . . 82 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 5 Higher-Order Functions 86 Abstraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 Abstracting array traversal . . . . . . . . . . . . . . . . . . . . . 88 Higher-order functions . . . . . . . . . . . . . . . . . . . . . . . 90 Passing along arguments . . . . . . . . . . . . . . . . . . . . . . 91 JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 Filtering an array . . . . . . . . . . . . . . . . . . . . . . . . . . 94 Transforming with map . . . . . . . . . . . . . . . . . . . . . . . 95 Summarizing with reduce . . . . . . . . . . . . . . . . . . . . . . 95 Composability . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 The cost . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 Great-great-great-great-… . . . . . . . . . . . . . . . . . . . . . . 99 Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 6 The Secret Life of Objects 105 History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 Prototypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 Overriding derived properties . . . . . . . . . . . . . . . . . . . 110 Prototype interference . . . . . . . . . . . . . . . . . . . . . . . 112 Prototype-less objects . . . . . . . . . . . . . . . . . . . . . . . . 114 Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 Laying out a table . . . . . . . . . . . . . . . . . . . . . . . . . . 115 Getters and setters . . . . . . . . . . . . . . . . . . . . . . . . . 121 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 The instanceof operator . . . . . . . . . . . . . . . . . . . . . . . 124 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 iv 7 Project: Electronic Life 128 Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 Representing space . . . . . . . . . . . . . . . . . . . . . . . . . 129 A critter’s programming interface . . . . . . . . . . . . . . . . . 131 The world object . . . . . . . . . . . . . . . . . . . . . . . . . . 132 this and its scope . . . . . . . . . . . . . . . . . . . . . . . . . . 134 Animating life . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 It moves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 More life forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 A more lifelike simulation . . . . . . . . . . . . . . . . . . . . . 141 Action handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 Populating the new world . . . . . . . . . . . . . . . . . . . . . 144 Bringing it to life . . . . . . . . . . . . . . . . . . . . . . . . . . 145 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 8 Bugs and Error Handling 149 Programmer mistakes . . . . . . . . . . . . . . . . . . . . . . . . 149 Strict mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 Error propagation . . . . . . . . . . . . . . . . . . . . . . . . . . 154 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 Cleaning up after exceptions . . . . . . . . . . . . . . . . . . . . 157 Selective catching . . . . . . . . . . . . . . . . . . . . . . . . . . 159 Assertions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 9 Regular Expressions 164 Creating a regular expression . . . . . . . . . . . . . . . . . . . 164 Testing for matches . . . . . . . . . . . . . . . . . . . . . . . . . 165 Matching a set of characters . . . . . . . . . . . . . . . . . . . . 165 Repeating parts of a pattern . . . . . . . . . . . . . . . . . . . . 167 Grouping subexpressions . . . . . . . . . . . . . . . . . . . . . . 168 Matches and groups . . . . . . . . . . . . . . . . . . . . . . . . . 168 The date type . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 Word and string boundaries . . . . . . . . . . . . . . . . . . . . 171 v Choice patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . 172 The mechanics of matching . . . . . . . . . . . . . . . . . . . . 172 Backtracking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 The replace method . . . . . . . . . . . . . . . . . . . . . . . . . 176 Greed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 Dynamically creating RegExp objects . . . . . . . . . . . . . . 179 The search method . . . . . . . . . . . . . . . . . . . . . . . . . 180 The lastIndex property . . . . . . . . . . . . . . . . . . . . . . . 180 Parsing an INI file . . . . . . . . . . . . . . . . . . . . . . . . . . 182 International characters . . . . . . . . . . . . . . . . . . . . . . . 184 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186 10 Modules 188 Why modules help . . . . . . . . . . . . . . . . . . . . . . . . . . 188 Using functions as namespaces . . . . . . . . . . . . . . . . . . . 191 Objects as interfaces . . . . . . . . . . . . . . . . . . . . . . . . 192 Detaching from the global scope . . . . . . . . . . . . . . . . . . 193 Evaluating data as code . . . . . . . . . . . . . . . . . . . . . . 194 Require . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195 Slow-loading modules . . . . . . . . . . . . . . . . . . . . . . . . 197 Interface design . . . . . . . . . . . . . . . . . . . . . . . . . . . 200 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 11 Project: A Programming Language 205 Parsing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 The evaluator . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 Special forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 The environment . . . . . . . . . . . . . . . . . . . . . . . . . . 213 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216 Cheating . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 12 JavaScript and the Browser 220 Networks and the Internet . . . . . . . . . . . . . . . . . . . . . 220 vi The Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 HTML and JavaScript . . . . . . . . . . . . . . . . . . . . . . . 225 In the sandbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 Compatibility and the browser wars . . . . . . . . . . . . . . . 227 13 The Document Object Model 229 Document structure . . . . . . . . . . . . . . . . . . . . . . . . . 229 Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230 The standard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232 Moving through the tree . . . . . . . . . . . . . . . . . . . . . . 233 Finding elements . . . . . . . . . . . . . . . . . . . . . . . . . . 234 Changing the document . . . . . . . . . . . . . . . . . . . . . . 235 Creating nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236 Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238 Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240 Styling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242 Cascading styles . . . . . . . . . . . . . . . . . . . . . . . . . . . 244 Query selectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245 Positioning and animating . . . . . . . . . . . . . . . . . . . . . 246 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 14 Handling Events 252 Event handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252 Events and DOM nodes . . . . . . . . . . . . . . . . . . . . . . 253 Event objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 Propagation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 Default actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256 Key events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 Mouse clicks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 Mouse motion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260 Scroll events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 Focus events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 Load event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265 Script execution timeline . . . . . . . . . . . . . . . . . . . . . . 266 Setting timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267 vii Debouncing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 15 Project: A Platform Game 272 The game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 The technology . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 Levels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274 Reading a level . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 Actors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276 Encapsulation as a burden . . . . . . . . . . . . . . . . . . . . . 279 Drawing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280 Motion and collision . . . . . . . . . . . . . . . . . . . . . . . . . 285 Actors and actions . . . . . . . . . . . . . . . . . . . . . . . . . . 288 Tracking keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292 Running the game . . . . . . . . . . . . . . . . . . . . . . . . . . 293 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295 16 Drawing on Canvas 297 SVG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297 The canvas element . . . . . . . . . . . . . . . . . . . . . . . . . 298 Filling and stroking . . . . . . . . . . . . . . . . . . . . . . . . . 300 Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301 Curves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302 Drawing a pie chart . . . . . . . . . . . . . . . . . . . . . . . . . 306 Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307 Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308 Transformation . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 Storing and clearing transformations . . . . . . . . . . . . . . . 313 Back to the game . . . . . . . . . . . . . . . . . . . . . . . . . . 314 Choosing a graphics interface . . . . . . . . . . . . . . . . . . . 320 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322 17 HTTP 324 The protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324 Browsers and HTTP . . . . . . . . . . . . . . . . . . . . . . . . 326 viii XMLHttpRequest . . . . . . . . . . . . . . . . . . . . . . . . . . 328 Sending a request . . . . . . . . . . . . . . . . . . . . . . . . . . 328 Asynchronous Requests . . . . . . . . . . . . . . . . . . . . . . . 330 Fetching XML Data . . . . . . . . . . . . . . . . . . . . . . . . . 330 HTTP sandboxing . . . . . . . . . . . . . . . . . . . . . . . . . . 331 Abstracting requests . . . . . . . . . . . . . . . . . . . . . . . . 332 Promises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335 Appreciating HTTP . . . . . . . . . . . . . . . . . . . . . . . . . 338 Security and HTTPS . . . . . . . . . . . . . . . . . . . . . . . . 338 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340 18 Forms and Form Fields 342 Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342 Focus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344 Disabled fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345 The form as a whole . . . . . . . . . . . . . . . . . . . . . . . . 345 Text fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347 Checkboxes and radio buttons . . . . . . . . . . . . . . . . . . . 348 Select fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349 File fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 Storing data client-side . . . . . . . . . . . . . . . . . . . . . . . 353 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357 19 Project: A Paint Program 359 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . 360 Building the DOM . . . . . . . . . . . . . . . . . . . . . . . . . 360 The foundation . . . . . . . . . . . . . . . . . . . . . . . . . . . 361 Tool selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362 Color and brush size . . . . . . . . . . . . . . . . . . . . . . . . 365 Saving . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367 Loading image files . . . . . . . . . . . . . . . . . . . . . . . . . 368 Finishing up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372 20 Node.js 376 ix Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376 Asynchronicity . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377 The node command . . . . . . . . . . . . . . . . . . . . . . . . . 378 Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380 Installing with NPM . . . . . . . . . . . . . . . . . . . . . . . . 381 The file system module . . . . . . . . . . . . . . . . . . . . . . . 382 The HTTP module . . . . . . . . . . . . . . . . . . . . . . . . . 384 Streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386 A simple file server . . . . . . . . . . . . . . . . . . . . . . . . . 388 Error handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395 21 Project: Skill-Sharing Website 399 Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400 Long polling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401 HTTP interface . . . . . . . . . . . . . . . . . . . . . . . . . . . 402 The server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404 The client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421 Program Structure . . . . . . . . . . . . . . . . . . . . . . . . . 424 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425 Data Structures: Objects and Arrays . . . . . . . . . . . . . . . 426 Higher-Order Functions . . . . . . . . . . . . . . . . . . . . . . . 428 The Secret Life of Objects . . . . . . . . . . . . . . . . . . . . . 429 Project: Electronic Life . . . . . . . . . . . . . . . . . . . . . . . 430 Bugs and Error Handling . . . . . . . . . . . . . . . . . . . . . . 432 Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . 432 Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433 Project: A Programming Language . . . . . . . . . . . . . . . . 435 The Document Object Model . . . . . . . . . . . . . . . . . . . 436 Handling Events . . . . . . . . . . . . . . . . . . . . . . . . . . . 437 Project: A Platform Game . . . . . . . . . . . . . . . . . . . . . 438 Drawing on Canvas . . . . . . . . . . . . . . . . . . . . . . . . . 439 HTTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441 Forms and Form Fields . . . . . . . . . . . . . . . . . . . . . . . 442 Project: A Paint Program . . . . . . . . . . . . . . . . . . . . . 444 x Node.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446 Project: Skill-Sharing Website . . . . . . . . . . . . . . . . . . . 448 xi Introduction This is a book about getting computers to do what you want them to do. Computers are about as common as screwdrivers today, but they contain a lot more hidden complexity and thus are harder to operate and understand. To many, they remain alien, slightly threatening things. We’ve found two effective ways of bridging the communication gap be- tween us, squishy biological organisms with a talent for social and spatial reasoning, and computers, unfeeling manipulators of meaningless data. The first is to appeal to our sense of the physical world and build in- terfaces that mimic that world and allow us to manipulate shapes on a screen with our fingers. This works very well for casual machine inter- action. But we have not yet found a good way to use the point-and-click ap- proach to communicate things to the computer that the designer of the interface did not anticipate. For open-ended interfaces, such as instruct- ing the computer to perform arbitrary tasks, we’ve had more luck with an approach that makes use of our talent for language: teaching the machine a language. Human languages allow words and phrases to be combined in many ways, which allows us to say many different things. Computer languages, though typically less grammatically flexible, follow a similar principle. 1 Casual computing has become much more widespread in the past 20 years, and language-based interfaces, which once were the default way in which people interacted with computers, have largely been replaced with graphical interfaces. But they are still there, if you know where to look. One such language, JavaScript, is built into almost every web browser and is thus available on just about every consumer device. This book intends to make you familiar enough with this language to be able to make a computer do what you want. On programming I do not enlighten those who are not eager to learn, nor arouse those who are not anxious to give an explanation themselves. If I have presented one corner of the square and they cannot come back to me with the other three, I should not go over the points again. —Confucius Besides explaining JavaScript, I also will introduce the basic principles of programming. Programming, it turns out, is hard. The fundamental rules are typically simple and clear. But programs built on top of these rules tend to become complex enough to introduce their own rules and complexity. You’re building your own maze, in a way, and you might just get lost in it. There will be times when reading this book feels terribly frustrating. If you are new to programming, there will be a lot of new material to digest. Much of this material will then be combined in ways that require you to make additional connections. It is up to you to make the necessary effort. When you are struggling to follow the book, do not jump to any conclusions about your own capabilities. You are fine—you just need to keep at it. Take a break, reread some material, and always make sure you read and understand the example programs and exercises. Learning is hard work, but everything you learn is yours and will make subsequent learning easier. The computer programmer is a creator of universes for which he [sic] alone is responsible. Universes of virtually unlimited 2 complexity can be created in the form of computer programs. —Joseph Weizenbaum, Computer Power and Human Reason A program is many things. It is a piece of text typed by a programmer, it is the directing force that makes the computer do what it does, it is data in the computer’s memory, yet it controls the actions performed on this same memory. Analogies that try to compare programs to objects we are familiar with tend to fall short. A superficially fitting one is that of a machine—lots of separate parts tend to be involved, and to make the whole thing tick, we have to consider the ways in which these parts interconnect and contribute to the operation of the whole. A computer is a machine built to act as a host for these immaterial machines. Computers themselves can do only stupidly straightforward things. The reason they are so useful is that they do these things at an incredibly high speed. A program can ingeniously combine an enormous number of these simple actions in order to do very complicated things. To some of us, writing computer programs is a fascinating game. A program is a building of thought. It is costless to build, it is weightless, and it grows easily under our typing hands. But without care, a program’s size and complexity will grow out of control, confusing even the person who created it. Keeping programs under control is the main problem of programming. When a program works, it is beautiful. The art of programming is the skill of controlling complexity. The great program is subdued—made simple in its com- plexity. Many programmers believe that this complexity is best managed by using only a small set of well-understood techniques in their programs. They have composed strict rules (“best practices”) prescribing the form programs should have, and the more zealous among them will consider those who go outside of this safe little zone to be bad programmers. What hostility to the richness of programming—to try to reduce it to something straightforward and predictable, to place a taboo on all the weird and beautiful programs! The landscape of programming tech- niques is enormous, fascinating in its diversity, and still largely unex- plored. It is certainly dangerous going, luring the inexperienced pro- grammer into all kinds of confusion, but that only means you should proceed with caution and keep your wits about you. As you learn there 3 will always be new challenges and new territory to explore. Program- mers who refuse to keep exploring will stagnate, forget their joy, and get bored with their craft. Why language matters In the beginning, at the birth of computing, there were no programming languages. Programs looked something like this: 00110001 00000000 00000000 00110001 00000001 00000001 00110011 00000001 00000010 01010001 00001011 00000010 00100010 00000010 00001000 01000011 00000001 00000000 01000001 00000001 00000001 00010000 00000010 00000000 01100010 00000000 00000000 That is a program to add the numbers from 1 to 10 together and print out the result: 1 + 2 + ... + 10 = 55. It could run on a simple, hypo- thetical machine. To program early computers, it was necessary to set large arrays of switches in the right position or punch holes in strips of cardboard and feed them to the computer. You can probably imagine how tedious and error-prone this procedure was. Even writing simple programs required much cleverness and discipline. Complex ones were nearly inconceivable. Of course, manually entering these arcane patterns of bits (the ones and zeros) did give the programmer a profound sense of being a mighty wizard. And that has to be worth something in terms of job satisfaction. Each line of the previous program contains a single instruction. It could be written in English like this: 1. Store the number 0 in memory location 0. 2. Store the number 1 in memory location 1. 3. Store the value of memory location 1 in memory location 2. 4. Subtract the number 11 from the value in memory location 2. 5. If the value in memory location 2 is the number 0, continue with instruction 9. 4 6. Add the value of memory location 1 to memory location 0. 7. Add the number 1 to the value of memory location 1. 8. Continue with instruction 3. 9. Output the value of memory location 0. Although that is already more readable than the soup of bits, it is still rather unpleasant. It might help to use names instead of numbers for the instructions and memory locations. Set "total" to 0. Set "count" to 1. [loop] Set "compare" to "count". Subtract 11 from "compare ". If "compare" is zero , continue at [end]. Add "count" to "total". Add 1 to "count". Continue at [loop]. [end] Output "total". Can you see how the program works at this point? The first two lines give two memory locations their starting values: total will be used to build up the result of the computation, and count will keep track of the number that we are currently looking at. The lines using compare are probably the weirdest ones. The program wants to see whether count is equal to 11 in order to decide whether it can stop running. Because our hypothetical machine is rather primitive, it can only test whether a number is zero and make a decision (or jump) based on that. So it uses the memory location labeled compare to compute the value of count - 11 and makes a decision based on that value. The next two lines add the value of count to the result and increment count by 1 every time the program has decided that count is not 11 yet. Here is the same program in JavaScript: var total = 0, count = 1; while (count

A Modern Introduction to Programming by Marijn Haverbeke
 

Publishing documents on edocr is a proven way to start demand generation for your products and services. Thousands of professionals and businesses publish marketing (brochures, data sheets, press releases, white papers and case studies), sales (slides, price lists and pro-forma agreements), operations (specifications, operating manuals, installation guides), customer service (user manuals) and financial (annual reports and financial statements) documents making it easier for prospects and customers to find content, helping them to make informed decisions. #SEO #leadgen #content #analytics

info@edocr.com

About edocr

I am an accomplished content marketing professional helping you to build your brand and business. In my current role, I fulfill a multi-faceted solution marketplace including: publishing and sharing your content, embedding a document viewer on your website, improving your content’s search engine optimization, generating leads with gated content and earning money by selling your documents. I gobble up documents, storing them for safekeeping and releasing the text for excellent search engine optimization, lead generation and earned income. 

Publishing documents on edocr.com is a proven way to start demand generation for your products and services. Thousands of professionals and businesses publish marketing, sales, operations, customer service and financial documents making it easier for prospects and customers to find content, helping them to make informed decisions.

Get publishing now!

×

Modal Header

Modal body