eloquent javascriptdddd

Upload: ddgdfgdfgd

Post on 02-Mar-2018

227 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/26/2019 Eloquent JavaScriptdddd

    1/489

    Eloquent JavaScript

    A Modern Introduction to Programming

    Marijn Haverbeke

  • 7/26/2019 Eloquent JavaScriptdddd

    2/489

    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 thebook may also be considered licensed under an MIT license (http://opensource.org/licenses/MIT).

    The illustrations are contributed by various artists: Cover by WasifHyder. Computer (introduction) and unicycle people (Chapter 21) byMax Xiantu. Sea of bits (Chapter 1) and weresquirrel (Chapter 4) byMargarita Martnez and Jos Menor. Octopuses (Chapter 2 and 4) byJim Tierney. Object with on/o switch (Chapter 6) by Dyle MacGregor.Regular expression diagrams in Chapter 9 generated with regexper.comby Je 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

    nancial backers.

    You can buy a print version of this book, with an extra bonus chapterincluded, 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

    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=VPXXXSRYC5COG5R5http://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=VPXXXSRYC5COG5R5http://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=VPXXXSRYC5COG5R5http://eloquentjavascript.net/backers.htmlhttp://eloquentjavascript.net/backers.htmlhttp://lessmilk.com/http://regexper.com/http://opensource.org/licenses/MIThttp://opensource.org/licenses/MIThttp://creativecommons.org/licenses/by-nc/3.0/
  • 7/26/2019 Eloquent JavaScriptdddd

    3/489

    Contents

    On programming . . . . . . . . . . . . . . . . . . . . . . . . . . 2Why language matters . . . . . . . . . . . . . . . . . . . . . . . 4What is JavaScript? . . . . . . . . . . . . . . . . . . . . . . . . . 6Code, and what to do with it . . . . . . . . . . . . . . . . . . . 8Overview of this book . . . . . . . . . . . . . . . . . . . . . . . . 9

    Typographic conventions . . . . . . . . . . . . . . . . . . . . . . 101 Values, Types, and Operators 11

    Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Unary operators . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Boolean values . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17Undened values . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Automatic type conversion . . . . . . . . . . . . . . . . . . . . . 19

    Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

    2 Program Structure 23

    Expressions and statements . . . . . . . . . . . . . . . . . . . . 23Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24Keywords and reserved words . . . . . . . . . . . . . . . . . . . 26The environment . . . . . . . . . . . . . . . . . . . . . . . . . . 27Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27The console.log function . . . . . . . . . . . . . . . . . . . . . . 28Return values . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

    prompt and conrm . . . . . . . . . . . . . . . . . . . . . . . . . 29Control ow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30Conditional execution . . . . . . . . . . . . . . . . . . . . . . . . 30while and do loops . . . . . . . . . . . . . . . . . . . . . . . . . . 32Indenting Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

    ii

  • 7/26/2019 Eloquent JavaScriptdddd

    4/489

    for loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35Breaking Out of a Loop . . . . . . . . . . . . . . . . . . . . . . 36Updating variables succinctly . . . . . . . . . . . . . . . . . . . 36

    Dispatching on a value with switch . . . . . . . . . . . . . . . . 37Capitalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

    3 Functions 42

    Dening a function . . . . . . . . . . . . . . . . . . . . . . . . . 42Parameters and scopes . . . . . . . . . . . . . . . . . . . . . . . 43Nested scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

    Functions as values . . . . . . . . . . . . . . . . . . . . . . . . . 46Declaration notation . . . . . . . . . . . . . . . . . . . . . . . . 47The call stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48Optional Arguments . . . . . . . . . . . . . . . . . . . . . . . . . 49Closure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52Growing functions . . . . . . . . . . . . . . . . . . . . . . . . . . 55Functions and side eects . . . . . . . . . . . . . . . . . . . . . 58Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

    Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

    4 Data Structures: Objects and Arrays 61

    The weresquirrel . . . . . . . . . . . . . . . . . . . . . . . . . . . 61Data sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65Mutability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68The lycanthropes log . . . . . . . . . . . . . . . . . . . . . . . . 69

    Computing correlation . . . . . . . . . . . . . . . . . . . . . . . 71Objects as maps . . . . . . . . . . . . . . . . . . . . . . . . . . . 73The nal analysis . . . . . . . . . . . . . . . . . . . . . . . . . . 74Further arrayology . . . . . . . . . . . . . . . . . . . . . . . . . . 76Strings and their properties . . . . . . . . . . . . . . . . . . . . 78

    iii

  • 7/26/2019 Eloquent JavaScriptdddd

    5/489

    The arguments object . . . . . . . . . . . . . . . . . . . . . . . . 79The Math object . . . . . . . . . . . . . . . . . . . . . . . . . . . 80The global object . . . . . . . . . . . . . . . . . . . . . . . . . . 82

    Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

    5 Higher-Order Functions 86

    Abstraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87Abstracting array traversal . . . . . . . . . . . . . . . . . . . . . 88Higher-order functions . . . . . . . . . . . . . . . . . . . . . . . 90Passing along arguments . . . . . . . . . . . . . . . . . . . . . . 91JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92Filtering an array . . . . . . . . . . . . . . . . . . . . . . . . . . 94

    Transforming with map . . . . . . . . . . . . . . . . . . . . . . . 95Summarizing with reduce . . . . . . . . . . . . . . . . . . . . . . 95Composability . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96The cost . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98Great-great-great-great- . . . . . . . . . . . . . . . . . . . . . . 99Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103

    6 The Secret Life of Objects 105

    History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107Prototypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109Overriding derived properties . . . . . . . . . . . . . . . . . . . 110Prototype interference . . . . . . . . . . . . . . . . . . . . . . . 112Prototype-less objects . . . . . . . . . . . . . . . . . . . . . . . . 114Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115Laying out a table . . . . . . . . . . . . . . . . . . . . . . . . . . 115

    Getters and setters . . . . . . . . . . . . . . . . . . . . . . . . . 121Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122The instanceof operator . . . . . . . . . . . . . . . . . . . . . . . 124Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

    iv

  • 7/26/2019 Eloquent JavaScriptdddd

    6/489

    7 Project: Electronic Life 128

    Denition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128Representing space . . . . . . . . . . . . . . . . . . . . . . . . . 129

    A critters programming interface . . . . . . . . . . . . . . . . . 131The world object . . . . . . . . . . . . . . . . . . . . . . . . . . 132this and its scope . . . . . . . . . . . . . . . . . . . . . . . . . . 134Animating life . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136It moves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139More life forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140A more lifelike simulation . . . . . . . . . . . . . . . . . . . . . 141Action handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . 142Populating the new world . . . . . . . . . . . . . . . . . . . . . 144Bringing it to life . . . . . . . . . . . . . . . . . . . . . . . . . . 145Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147

    8 Bugs and Error Handling 149

    Programmer mistakes . . . . . . . . . . . . . . . . . . . . . . . . 149Strict mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153Error propagation . . . . . . . . . . . . . . . . . . . . . . . . . . 154Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156

    Cleaning up after exceptions . . . . . . . . . . . . . . . . . . . . 157Selective catching . . . . . . . . . . . . . . . . . . . . . . . . . . 159Assertions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163

    9 Regular Expressions 164

    Creating a regular expression . . . . . . . . . . . . . . . . . . . 164Testing for matches . . . . . . . . . . . . . . . . . . . . . . . . . 165Matching a set of characters . . . . . . . . . . . . . . . . . . . . 165

    Repeating parts of a pattern . . . . . . . . . . . . . . . . . . . . 167Grouping subexpressions . . . . . . . . . . . . . . . . . . . . . . 168Matches and groups . . . . . . . . . . . . . . . . . . . . . . . . . 168The date type . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170Word and string boundaries . . . . . . . . . . . . . . . . . . . . 171

    v

  • 7/26/2019 Eloquent JavaScriptdddd

    7/489

    Choice patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . 172The mechanics of matching . . . . . . . . . . . . . . . . . . . . 172Backtracking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174

    The replace method . . . . . . . . . . . . . . . . . . . . . . . . . 176Greed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177Dynamically creating RegExp objects . . . . . . . . . . . . . . 179The search method . . . . . . . . . . . . . . . . . . . . . . . . . 180The lastIndex property . . . . . . . . . . . . . . . . . . . . . . . 180Parsing an INI le . . . . . . . . . . . . . . . . . . . . . . . . . . 182International characters . . . . . . . . . . . . . . . . . . . . . . . 184Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186

    10 Modules 188Why modules help . . . . . . . . . . . . . . . . . . . . . . . . . . 188Using functions as namespaces . . . . . . . . . . . . . . . . . . . 191Objects as interfaces . . . . . . . . . . . . . . . . . . . . . . . . 192Detaching from the global scope . . . . . . . . . . . . . . . . . . 193Evaluating data as code . . . . . . . . . . . . . . . . . . . . . . 194Require . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195Slow-loading modules . . . . . . . . . . . . . . . . . . . . . . . . 197Interface design . . . . . . . . . . . . . . . . . . . . . . . . . . . 200

    Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203

    11 Project: A Programming Language 205

    Parsing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205The evaluator . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210Special forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211The environment . . . . . . . . . . . . . . . . . . . . . . . . . . 213Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216

    Cheating . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218

    12 JavaScript and the Browser 220

    Networks and the Internet . . . . . . . . . . . . . . . . . . . . . 220

    vi

  • 7/26/2019 Eloquent JavaScriptdddd

    8/489

    The Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223HTML and JavaScript . . . . . . . . . . . . . . . . . . . . . . . 225

    In the sandbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226Compatibility and the browser wars . . . . . . . . . . . . . . . 227

    13 The Document Object Model 229

    Document structure . . . . . . . . . . . . . . . . . . . . . . . . . 229Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230The standard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232Moving through the tree . . . . . . . . . . . . . . . . . . . . . . 233Finding elements . . . . . . . . . . . . . . . . . . . . . . . . . . 234Changing the document . . . . . . . . . . . . . . . . . . . . . . 235

    Creating nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240Styling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242Cascading styles . . . . . . . . . . . . . . . . . . . . . . . . . . . 244Query selectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245Positioning and animating . . . . . . . . . . . . . . . . . . . . . 246Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249

    14 Handling Events 252

    Event handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252Events and DOM nodes . . . . . . . . . . . . . . . . . . . . . . 253Event objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254Propagation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254Default actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256Key events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257Mouse clicks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259Mouse motion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260

    Scroll events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263Focus events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264Load event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265Script execution timeline . . . . . . . . . . . . . . . . . . . . . . 266Setting timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267

    vii

  • 7/26/2019 Eloquent JavaScriptdddd

    9/489

    Debouncing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270

    15 Project: A Platform Game 272

    The game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272The technology . . . . . . . . . . . . . . . . . . . . . . . . . . . 273Levels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274Reading a level . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275Actors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276Encapsulation as a burden . . . . . . . . . . . . . . . . . . . . . 279Drawing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280Motion and collision . . . . . . . . . . . . . . . . . . . . . . . . . 285

    Actors and actions . . . . . . . . . . . . . . . . . . . . . . . . . . 288Tracking keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292Running the game . . . . . . . . . . . . . . . . . . . . . . . . . . 293Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295

    16 Drawing on Canvas 297

    SVG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297The canvas element . . . . . . . . . . . . . . . . . . . . . . . . . 298Filling and stroking . . . . . . . . . . . . . . . . . . . . . . . . . 300

    Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301Curves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302Drawing a pie chart . . . . . . . . . . . . . . . . . . . . . . . . . 306Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308Transformation . . . . . . . . . . . . . . . . . . . . . . . . . . . 310Storing and clearing transformations . . . . . . . . . . . . . . . 313Back to the game . . . . . . . . . . . . . . . . . . . . . . . . . . 314Choosing a graphics interface . . . . . . . . . . . . . . . . . . . 320Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321

    Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322

    17 HTTP 324

    The protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324Browsers and HTTP . . . . . . . . . . . . . . . . . . . . . . . . 326

    viii

  • 7/26/2019 Eloquent JavaScriptdddd

    10/489

    XMLHttpRequest . . . . . . . . . . . . . . . . . . . . . . . . . . 328Sending a request . . . . . . . . . . . . . . . . . . . . . . . . . . 328Asynchronous Requests . . . . . . . . . . . . . . . . . . . . . . . 330

    Fetching XML Data . . . . . . . . . . . . . . . . . . . . . . . . . 330HTTP sandboxing . . . . . . . . . . . . . . . . . . . . . . . . . . 331Abstracting requests . . . . . . . . . . . . . . . . . . . . . . . . 332Promises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335Appreciating HTTP . . . . . . . . . . . . . . . . . . . . . . . . . 338Security and HTTPS . . . . . . . . . . . . . . . . . . . . . . . . 338Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340

    18 Forms and Form Fields 342

    Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342Focus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344Disabled elds . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345The form as a whole . . . . . . . . . . . . . . . . . . . . . . . . 345Text elds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347Checkboxes and radio buttons . . . . . . . . . . . . . . . . . . . 348Select elds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349File elds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351Storing data client-side . . . . . . . . . . . . . . . . . . . . . . . 353

    Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357

    19 Project: A Paint Program 359

    Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . 360Building the DOM . . . . . . . . . . . . . . . . . . . . . . . . . 360The foundation . . . . . . . . . . . . . . . . . . . . . . . . . . . 361Tool selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362Color and brush size . . . . . . . . . . . . . . . . . . . . . . . . 365Saving . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367

    Loading image les . . . . . . . . . . . . . . . . . . . . . . . . . 368Finishing up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372

    20 Node.js 376

    ix

  • 7/26/2019 Eloquent JavaScriptdddd

    11/489

    Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376Asynchronicity . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377The node command . . . . . . . . . . . . . . . . . . . . . . . . . 378

    Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380Installing with NPM . . . . . . . . . . . . . . . . . . . . . . . . 381The le system module . . . . . . . . . . . . . . . . . . . . . . . 382The HTTP module . . . . . . . . . . . . . . . . . . . . . . . . . 384Streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386A simple le server . . . . . . . . . . . . . . . . . . . . . . . . . 388Error handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395

    21 Project: Skill-Sharing Website 399Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400Long polling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401HTTP interface . . . . . . . . . . . . . . . . . . . . . . . . . . . 402The server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404The client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421Program Structure . . . . . . . . . . . . . . . . . . . . . . . . . 424Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425

    Data Structures: Objects and Arrays . . . . . . . . . . . . . . . 426Higher-Order Functions . . . . . . . . . . . . . . . . . . . . . . . 428The Secret Life of Objects . . . . . . . . . . . . . . . . . . . . . 429Project: Electronic Life . . . . . . . . . . . . . . . . . . . . . . . 430Bugs and Error Handling . . . . . . . . . . . . . . . . . . . . . . 432Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . 432Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433Project: A Programming Language . . . . . . . . . . . . . . . . 435The Document Object Model . . . . . . . . . . . . . . . . . . . 436Handling Events . . . . . . . . . . . . . . . . . . . . . . . . . . . 437

    Project: A Platform Game . . . . . . . . . . . . . . . . . . . . . 438Drawing on Canvas . . . . . . . . . . . . . . . . . . . . . . . . . 439HTTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441Forms and Form Fields . . . . . . . . . . . . . . . . . . . . . . . 442Project: A Paint Program . . . . . . . . . . . . . . . . . . . . . 444

    x

  • 7/26/2019 Eloquent JavaScriptdddd

    12/489

    Node.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446Project: Skill-Sharing Website . . . . . . . . . . . . . . . . . . . 448

    xi

  • 7/26/2019 Eloquent JavaScriptdddd

    13/489

    Introduction

    This is a book about getting computers to do what you want them todo. Computers are about as common as screwdrivers today, but theycontain a lot more hidden complexity and thus are harder to operate andunderstand. To many, they remain alien, slightly threatening things.

    Weve found two eective ways of bridging the communication gap be-tween us, squishy biological organisms with a talent for social and spatialreasoning, and computers, unfeeling manipulators of meaningless data.The rst 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 ascreen with our ngers. 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 theinterface did not anticipate. For open-ended interfaces, such as instruct-ing the computer to perform arbitrary tasks, weve had more luck with

    an approach that makes use of our talent for language: teaching themachine a language.

    Human languages allow words and phrases to be combined in manyways, which allows us to say many dierent things. Computer languages,though typically less grammatically exible, follow a similar principle.

    1

  • 7/26/2019 Eloquent JavaScriptdddd

    14/489

    Casual computing has become much more widespread in the past 20years, and language-based interfaces, which once were the default wayin which people interacted with computers, have largely been replaced

    with graphical interfaces. But they are still there, if you know whereto look. One such language, JavaScript, is built into almost every webbrowser and is thus available on just about every consumer device.

    This book intends to make you familiar enough with this language tobe 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 cannotcome back to me with the other three, I should not go overthe points again.

    Confucius

    Besides explaining JavaScript, I also will introduce the basic principlesof programming. Programming, it turns out, is hard. The fundamentalrules are typically simple and clear. But programs built on top of theserules tend to become complex enough to introduce their own rules and

    complexity. Youre building your own maze, in a way, and you mightjust 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 todigest. Much of this material will then becombinedin ways that requireyou to make additional connections.

    It is up to you to make the necessary eort. When you are strugglingto follow the book, do not jump to any conclusions about your owncapabilities. You are neyou just need to keep at it. Take a break,

    reread some material, andalwaysmake sure you read and understand theexample programs and exercises. Learning is hard work, but everythingyou learn is yours and will make subsequent learning easier.

    The computer programmer is a creator of universes for whichhe [sic] alone is responsible. Universes of virtually unlimited

    2

  • 7/26/2019 Eloquent JavaScriptdddd

    15/489

    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 isdata in the computers memory, yet it controls the actions performed onthis same memory. Analogies that try to compare programs to objectswe are familiar with tend to fall short. A supercially tting one is thatof a machinelots of separate parts tend to be involved, and to makethe whole thing tick, we have to consider the ways in which these partsinterconnect and contribute to the operation of the whole.

    A computer is a machine built to act as a host for these immaterialmachines. Computers themselves can do only stupidly straightforwardthings. The reason they are so useful is that they do these things at anincredibly high speed. A program can ingeniously combine an enormousnumber of these simple actions in order to do very complicated things.

    To some of us, writing computer programs is a fascinating game. Aprogram 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 programs size and complexity will grow out ofcontrol, confusing even the person who created it. Keeping programsunder control is the main problem of programming. When a program

    works, it is beautiful. The art of programming is the skill of controllingcomplexity. The great program is subduedmade simple in its com-plexity.

    Many programmers believe that this complexity is best managed byusing only a small set of well-understood techniques in their programs.They have composed strict rules (best practices) prescribing the formprograms should have, and the more zealous among them will considerthose who go outside of this safe little zone to bebadprogrammers.

    What hostility to the richness of programmingto try to reduce itto something straightforward and predictable, to place a taboo on allthe 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 shouldproceed with caution and keep your wits about you. As you learn there

    3

  • 7/26/2019 Eloquent JavaScriptdddd

    16/489

    will always be new challenges and new territory to explore. Program-mers who refuse to keep exploring will stagnate, forget their joy, and getbored with their craft.

    Why language matters

    In the beginning, at the birth of computing, there were no programminglanguages. Programs looked something like this:

    0 0 1 10 0 01 0 0 00 0 0 00 0 0 00 0 0 00

    0 0 1 10 0 01 0 0 00 0 0 01 0 0 00 0 0 01

    0 0 1 10 0 11 0 0 00 0 0 01 0 0 00 0 0 10

    0 1 0 10 0 01 0 0 00 1 0 11 0 0 00 0 0 10

    0 0 1 00 0 10 0 0 00 0 0 10 0 0 00 1 0 000 1 0 00 0 11 0 0 00 0 0 01 0 0 00 0 0 00

    0 1 0 00 0 01 0 0 00 0 0 01 0 0 00 0 0 01

    0 0 0 10 0 00 0 0 00 0 0 10 0 0 00 0 0 00

    0 1 1 00 0 10 0 0 00 0 0 00 0 0 00 0 0 00

    That is a program to add the numbers from 1 to 10 together and printout the result: 1 + 2 + . . . + 1 0 = 5 5. It could run on a simple, hypo-thetical machine. To program early computers, it was necessary to setlarge arrays of switches in the right position or punch holes in strips ofcardboard and feed them to the computer. You can probably imaginehow tedious and error-prone this procedure was. Even writing simpleprograms required much cleverness and discipline. Complex ones werenearly inconceivable.

    Of course, manually entering these arcane patterns of bits (the onesand zeros) did give the programmer a profound sense of being a mightywizard. And that has to be worth something in terms of job satisfaction.

    Each line of the previous program contains a single instruction. Itcould be written in English like this:

    1 . S to re t he n um be r 0 i n m em or y l oc at io n 0 .

    2 . S to re t he n um be r 1 i n m em or y l oc at io n 1 .

    3 . S to re t he v al ue o f m em or y l oc a ti on 1 i n m em or y l oc a ti on 2 .

    4 . S u bt ra c t t he n um be r 1 1 f ro m t he v al ue i n m em or y l oc a ti o n 2 .

    5 . I f t he v al ue in m em or y l oc at io n 2 is t he n um be r 0 ,

    c o n ti n u e w i th i n s tr u c ti o n 9 .

    4

  • 7/26/2019 Eloquent JavaScriptdddd

    17/489

    6 . A dd t he v al ue of m em or y l oc at io n 1 to m em or y l oc at io n 0.

    7 . A dd t he n um be r 1 t o t he v al ue o f m em or y l oc at io n 1 .

    8 . C o nt in u e w it h i n st r uc t io n 3 .

    9 . O ut pu t t he v al ue o f m em or y l oc a ti on 0 .

    Although that is already more readable than the soup of bits, it is stillrather unpleasant. It might help to use names instead of numbers forthe instructions and memory locations.

    S et " t ot al " t o 0.

    S et " c ou nt " t o 1.

    [ l o o p ]

    S et " c o mp ar e " t o " c ou nt " .

    S u b tr a c t 1 1 f r om " c o m pa r e " .

    I f " c o mp ar e " i s z er o , c o nt in u e a t [ e nd ] .

    A dd " c o un t " t o " t o ta l ".

    A dd 1 to " c ou nt " .

    C o n ti n u e a t [ l o op ] .

    [ e n d ]

    O u tp u t " t o t al " .

    Can you see how the program works at this point? The rst two linesgive two memory locations their starting values: total will be used tobuild up the result of the computation, and count will keep track of thenumber that we are currently looking at. The lines using compare are

    probably the weirdest ones. The program wants to see whether countis equal to 11 in order to decide whether it can stop running. Becauseour hypothetical machine is rather primitive, it can only test whethera number is zero and make a decision (or jump) based on that. So ituses the memory location labeled compareto compute the value of count- 11and makes a decision based on that value. The next two lines addthe value of count to the result and increment count by 1 every time theprogram has decided that countis not 11 yet.

    Here is the same program in JavaScript:

    var t ot al = 0 , c ou nt = 1;w hi le ( c ou nt

  • 7/26/2019 Eloquent JavaScriptdddd

    18/489

    // 55

    This version gives us a few more improvements. Most importantly, there

    is no need to specify the way we want the program to jump back and forthanymore. The while language construct takes care of that. It continuesexecuting the block (wrapped in braces) below it as long as the conditionit was given holds. That condition is count

  • 7/26/2019 Eloquent JavaScriptdddd

    19/489

    applications possibleapplications with which you can interact directly,without doing a page reload for every action. But it is also used inmore traditional websites to provide various forms of interactivity and

    cleverness.It is important to note that JavaScript has almost nothing to do

    with the programming language named Java. The similar name was in-spired by marketing considerations, rather than good judgment. WhenJavaScript was being introduced, the Java language was being heavilymarketed and was gaining popularity. Someone thought it was a goodidea to try to ride along on this success. Now we are stuck with thename.

    After its adoption outside of Netscape, a standard document was writ-ten to describe the way the JavaScript language should work to makesure the various pieces of software that claimed to support JavaScriptwere actually talking about the same language. This is called the EC-MAScript standard, after the Ecma International organization that didthe standardization. In practice, the terms ECMAScript and JavaScriptcan be used interchangeablythey are two names for the same language.

    There are those who will say terriblethings about the JavaScript lan-guage. Many of these things are true. When I was required to writesomething in JavaScript for the rst time, I quickly came to despise it.It would accept almost anything I typed but interpret it in a way that

    was completely dierent from what I meant. This had a lot to do withthe fact that I did not have a clue what I was doing, of course, but thereis a real issue here: JavaScript is ridiculously liberal in what it allows.The idea behind this design was that it would make programming inJavaScript easier for beginners. In actuality, it mostly makes ndingproblems in your programs harder because the system will not pointthem out to you.

    This exibility also has its advantages, though. It leaves space for alot of techniques that are impossible in more rigid languages, and as youwill see (for example in Chapter 10) it can be used to overcome someof JavaScripts shortcomings. After learning the language properly andworking with it for a while, I have learned to actually likeJavaScript.

    There have been several versions of JavaScript. ECMAScript version3 was the widely supported version in the time of JavaScripts ascentto dominance, roughly between 2000 and 2010. During this time, work

    7

  • 7/26/2019 Eloquent JavaScriptdddd

    20/489

    was underway on an ambitious version 4, which planned a number ofradical improvements and extensions to the language. Changing a living,widely used language in such a radical way turned out to be politically

    dicult, and work on the version 4 was abandoned in 2008, leading tothe much less ambitious version 5 coming out in 2009. Were now at thepoint where all major browsers support version 5, which is the languageversion that this book will be focusing on. A version 6 is in the process ofbeing nalized, and some browsers are starting to support new featuresfrom this version.

    Web browsers are not the only platforms on which JavaScript is used.Some databases, such as MongoDB and CouchDB, use JavaScript astheir scripting and query language. Several platforms for desktop andserver programming, most notably the Node.js project (the subject ofChapter 20) are providing a powerful environment for programmingJavaScript outside of the browser.

    Code, and what to do with it

    Code is the text that makes up programs. Most chapters in this bookcontain quite a lot of it. In my experience, reading code and writing codeare indispensable parts of learning to program, so try to not just glanceover the examples. Read them attentively and understand them. Thismay be slow and confusing at rst, but I promise that you will quicklyget the hang of it. The same goes for the exercises. Dont assume youunderstand them until youve actually written a working solution.

    I recommend you try your solutions to exercises in an actual JavaScriptinterpreter. That way, youll get immediate feedback on whether whatyou are doing is working, and, I hope, youll be tempted to experimentand go beyond the exercises.

    The easiest way to run the example code in the book, and to ex-periment with it, is to look it up in the online version of the book at

    eloquentjavascript.net. There, you can click any code example to editand run it and to see the output it produces. To work on the exercises,go to eloquentjavascript.net/code, which provides starting code for eachcoding exercise and allows you to look at the solutions.

    If you want to run the programs dened in this book outside of the

    8

    http://eloquentjavascript.net/codehttp://eloquentjavascript.net/
  • 7/26/2019 Eloquent JavaScriptdddd

    21/489

    books sandbox, some care is required. Many examples stand on theirown and should work in any JavaScript environment. But code in laterchapters is mostly written for a specic environment (the browser or

    Node.js) and can run only there. In addition, many chapters denebigger programs, and the pieces of code that appear in them depend oneach other or on external les. The sandbox on the website provideslinks to Zip les containing all of the scripts and data les necessary torun the code for a given chapter.

    Overview of this book

    This book contains roughly three parts. The rst 11 chapters discuss

    the JavaScript language itself. The next eight chapters are about webbrowsers and the way JavaScript is used to program them. Finally,two chapters are devoted to Node.js, another environment to programJavaScript in.

    Throughout the book, there are ve project chapters, which describelarger example programs to give you a taste of real programming. Inorder of appearance, we will work through building an articial life sim-ulation, a programming language, a platform game, a paint program,and a dynamic website.

    The language part of the book starts with four chapters to introducethe basic structure of the JavaScript language. They introduce controlstructures (such as the whileword you saw in this introduction), functions(writing your own operations), and data structures. After these, youwill be able to write simple programs. Next, Chapters 5 and 6 introducetechniques to use functions and objects to write moreabstractcode andthus keep complexity under control.

    After a rst project chapter, the rst part of the book continues withchapters on error handling and xing, on regular expressions (an im-portant tool for working with text data), and on modularityanother

    weapon against complexity. The second project chapter concludes therst part of the book.

    The second part, Chapters 12 to 19, describes the tools that browserJavaScript has access to. Youll learn to display things on the screen(Chapters 13 and 16), respond to user input (Chapters 14 and 18), and

    9

    http://eloquentjavascript.net/code
  • 7/26/2019 Eloquent JavaScriptdddd

    22/489

    communicate over the network (Chapter 17). There are again two projectchapters in this part.

    After that, Chapter 20 describes Node.js, and Chapter 21 builds a

    simple web system using that tool.

    Typographic conventions

    In this book, text written in a monospaced font will represent elements ofprogramssometimes they are self-sucient fragments, and sometimesthey just refer to part of a nearby program. Programs (of which youhave already seen a few), are written as follows:

    f un c ti on f ac ( n ) {

    if ( n = = 0)

    r e tu r n 1 ;

    else

    r et ur n fac (n - 1) * n ;

    }

    Sometimes, in order to show the output that a program produces, theexpected output is written after it, with two slashes and an arrow infront.

    c o n s o l e . l o g ( f a c ( 8 ) ) ;

    // 40320

    Good luck!

    10

  • 7/26/2019 Eloquent JavaScriptdddd

    23/489

    Below the surface of the machine, the program moves.Without eort, it expands and contracts. In great harmony,electrons scatter and regroup. The forms on the monitor arebut ripples on the water. The essence stays invisibly below.

    Master Yuan-Ma,The Book of Programming

    1 Values, Types, and Operators

    Inside the computers world, there is only data. You can read data,modify data, create new databut anything that isnt data simply doesnot exist. All this data is stored as long sequences of bits and is thusfundamentally alike.

    Bits are any kind of two-valued things, usually described as zeros and

    ones. Inside the computer, they take forms such as a high or low electricalcharge, a strong or weak signal, or a shiny or dull spot on the surface ofa CD. Any piece of discrete information can be reduced to a sequence ofzeros and ones and thus represented in bits.

    For example, think about how you might show the number 13 in bits.It works the same way you write decimal numbers, but instead of 10dierent digits, you have only 2, and the weight of each increases by afactor of 2 from right to left. Here are the bits that make up the number13, with the weights of the digits shown below them:

    0 0 0 0 1 1 0 1

    128 64 32 16 8 4 2 1

    So thats the binary number 00001101, or 8 + 4 + 1, which equals 13.

    Values

    Imagine a sea of bits. An ocean of them. A typical modern computerhas more than 30 billion bits in its volatile data storage. Nonvolatilestorage (the hard disk or equivalent) tends to have yet a few orders of

    magnitude more.

    11

  • 7/26/2019 Eloquent JavaScriptdddd

    24/489

    To be able to work with such quantities of bits without getting lost, youcan separate them into chunks that represent pieces of information. Ina JavaScript environment, those chunks are called values. Though all

    values are made of bits, they play dierent roles. Every value has a typethat determines its role. There are six basic types of values in JavaScript:numbers, strings, Booleans, objects, functions, and undened values.

    To create a value, you must merely invoke its name. This is convenient.You dont have to gather building material for your values or pay forthem. You just call for one, andwoosh, you have it. They are not createdfrom thin air, of course. Every value has to be stored somewhere, and ifyou want to use a gigantic amount of them at the same time, you mightrun out of bits. Fortunately, this is a problem only if you need them allsimultaneously. As soon as you no longer use a value, it will dissipate,

    leaving behind its bits to be recycled as building material for the nextgeneration of values.

    This chapter introduces the atomic elements of JavaScript programs,that is, the simple value types and the operators that can act on suchvalues.

    Numbers

    Values of the number type are, unsurprisingly, numeric values. In a

    JavaScript program, they are written as follows:

    13

    Use that in a program, and it will cause the bit pattern for the number13 to come into existence inside the computers memory.

    12

  • 7/26/2019 Eloquent JavaScriptdddd

    25/489

    JavaScript uses a xed number of bits, namely 64 of them, to storea single number value. There are only so many patterns you can makewith 64 bits, which means that the amount of dierent numbers that can

    be represented is limited. For Ndecimal digits, the amount of numbersthat can be represented is 10N. Similarly, given 64 binary digits, youcan represent 264 dierent numbers, which is about 18 quintillion (an 18with 18 zeros after it). This is a lot.

    Computer memory used to be a lot smaller, and people tended touse groups of 8 or 16 bits to represent their numbers. It was easy toaccidentally overow such small numbersto end up with a numberthat did not t into the given amount of bits. Today, even personalcomputers have plenty of memory, so you are free to use 64-bit chunks,which means you need to worry about overow only when dealing withtruly astronomical numbers.

    Not all whole numbers below 18 quintillion t in a JavaScript number,though. Those bits also store negative numbers, so one bit indicatesthe sign of the number. A bigger issue is that nonwhole numbers mustalso be represented. To do this, some of the bits are used to store theposition of the decimal point. The actual maximum whole number thatcan be stored is more in the range of 9 quadrillion (15 zeros), which isstill pleasantly huge.

    Fractional numbers are written by using a dot.

    9.81

    For very big or very small numbers, you can also use scientic notation byadding an e (for exponent), followed by the exponent of the number:

    2.998e8

    That is 2.998 108 = 299,800,000.Calculations with whole numbers (also called integers) smaller than

    the aforementioned 9 quadrillion are guaranteed to always be precise.Unfortunately, calculations with fractional numbers are generally not.Just as (pi) cannot be precisely expressed by a nite number of decimaldigits, many numbers lose some precision when only 64 bits are availableto store them. This is a shame, but it causes practical problems only inspecic situations. The important thing is to be aware of it and treat

    13

  • 7/26/2019 Eloquent JavaScriptdddd

    26/489

    fractional digital numbers as approximations, not as precise values.

    Arithmetic

    The main thing to do with numbers is arithmetic. Arithmetic operationssuch as addition or multiplication take two number values and producea new number from them. Here is what they look like in JavaScript:

    100 + 4 * 11

    The + and * symbols are called operators. The rst stands for addition,and the second stands for multiplication. Putting an operator betweentwo values will apply it to those values and produce a new value.

    Does the example mean add 4 and 100, and multiply the result by11, or is the multiplication done before the adding? As you might haveguessed, the multiplication happens rst. But as in mathematics, youcan change this by wrapping the addition in parentheses.

    (100 + 4) * 11

    For subtraction, there is the - operator, and division can be done withthe /operator.

    When operators appear together without parentheses, the order inwhich they are applied is determined by the precedenceof the operators.

    The example shows that multiplication comes before addition. The /operator has the same precedence as *. Likewise for + and -. Whenmultiple operators with the same precedence appear next to each other,as in 1 - 2 + 1, they are applied left to right: ( 1 - 2 ) + 1.

    These rules of precedence are not something you should worry about.When in doubt, just add parentheses.

    There is one more arithmetic operator, which you might not immedi-ately recognize. The % symbol is used to represent the remainder oper-ation. X % Y is the remainder of dividing X by Y. For example, 314 % 100produces 14, and 144 % 12gives 0. Remainders precedence is the same asthat of multiplication and division. Youll often see this operator referredto asmodulo, though technically remainderis more accurate.

    14

  • 7/26/2019 Eloquent JavaScriptdddd

    27/489

    Special numbers

    There are three special values in JavaScript that are considered numbers

    but dont behave like normal numbers.The rst two are Infinity and -Infinity, which represent the positiveand negative innities. Infinity - 1is still Infinity, and so on. Dont puttoo much trust in innity-based computation. It isnt mathematicallysolid, and it will quickly lead to our next special number: NaN.

    NaNstands for not a number, even though it is a value of the numbertype. Youll get this result when you, for example, try to calculate 0/ 0 (zero divided by zero), Infinity - Infinity, or any number of othernumeric operations that dont yield a precise, meaningful result.

    Strings

    The next basic data type is the string. Strings are used to representtext. They are written by enclosing their content in quotes.

    " P at ch m y b oa t w it h c he wi ng g um "

    M o nk e y s w a ve g o od by e

    Both single and double quotes can be used to mark strings as long asthe quotes at the start and the end of the string match.

    Almost anything can be put between quotes, and JavaScript will makea string value out of it. But a few characters are more dicult. You canimagine how putting quotes between quotes might be hard. Newlines(the characters you get when you press Enter) also cant be put betweenquotes. The string has to stay on a single line.

    To make it possible to include such characters in a string, the followingnotation is used: whenever a backslash (\) is found inside quoted text,it indicates that the character after it has a special meaning. This iscalled escaping the character. A quote that is preceded by a backslashwill not end the string but be part of it. When an n character occurs

    after a backslash, it is interpreted as a newline. Similarly, a t after abackslash means a tab character. Take the following string:

    " T hi s i s t he f ir st l in e \ nA nd t hi s i s t he s ec on d "

    The actual text contained is this:

    15

  • 7/26/2019 Eloquent JavaScriptdddd

    28/489

    T hi s i s t he f ir st l in e

    A nd t hi s i s t he s ec on d

    There are, of course, situations where you want a backslash in a stringto be just a backslash, not a special code. If two backslashes follow eachother, they will collapse together, and only one will be left in the resultingstring value. This is how the string A newline character is written like"\n". can be expressed:

    " A n ew l in e c h ar a ct e r i s w ri t te n l ik e \ "\ \ n \" ."

    Strings cannot be divided, multiplied, or subtracted, but the +operatorcanbe used on them. It does not add, but it concatenatesit glues twostrings together. The following line will produce the string "concatenate":

    " con " + " cat " + " e" + " na te "

    There are more ways of manipulating strings, which we will discuss whenwe get to methods in Chapter 4.

    Unary operators

    Not all operators are symbols. Some are written as words. One exampleis the typeofoperator, which produces a string value naming the type of

    the value you give it.

    c o n s o le . l o g ( t y p e o f 4 . 5 )

    // number

    c o n s o le . l o g ( t y p e o f " x " )

    // string

    We will use console.log in example code to indicate that we want to seethe result of evaluating something. When you run such code, the valueproduced should be shown on the screen, though how it appears willdepend on the JavaScript environment you use to run it.

    The other operators we saw all operated on two values, but typeoftakesonly one. Operators that use two values are called binary operators,while those that take one are calledunaryoperators. The minus operatorcan be used both as a binary operator and as a unary operator.

    16

  • 7/26/2019 Eloquent JavaScriptdddd

    29/489

    c on so le . l og ( - ( 10 - 2 ) )

    // -8

    Boolean values

    Often, you will need a value that simply distinguishes between two pos-sibilities, like yes and no or on and o. For this, JavaScript hasa Boolean type, which has just two values: true and false (which arewritten simply as those words).

    Comparisons

    Here is one way to produce Boolean values:

    c o ns o le . l o g ( 3 > 2 )

    // true

    c o ns o le . l o g ( 3 < 2 )

    // false

    The > and < signs are the traditional symbols for is greater than andis less than, respectively. They are binary operators. Applying themresults in a Boolean value that indicates whether they hold true in thiscase.

    Strings can be compared in the same way.

    c o ns o le . l o g ( " A a r dv a r k " < " Z o r o as t e r " )

    // true

    The way strings are ordered is more or less alphabetic: uppercase lettersare always less than lowercase ones, so "Z" < "a" is true, and non-alphabetic characters (!, -, and so on) are also included in the ordering.The actual comparison is based on the Unicode standard. This stan-dard assigns a number to virtually every character you would ever need,

    including characters from Greek, Arabic, Japanese, Tamil, and so on.Having such numbers is useful for storing strings inside a computer be-cause it makes it possible to represent them as a sequence of numbers.When comparing strings, JavaScript goes over them from left to right,comparing the numeric codes of the characters one by one.

    17

  • 7/26/2019 Eloquent JavaScriptdddd

    30/489

    Other similar operators are >=(greater than or equal to),

  • 7/26/2019 Eloquent JavaScriptdddd

    31/489

    operators (>, ==, and so on), and then the rest. This order has beenchosen such that, in typical expressions like the following one, as fewparentheses as possible are necessary:

    1 + 1 == 2 & & 10 * 1 0 > 50

    The last logical operator I will discuss is not unary, not binary, butternary, operating on three values. It is written with a question markand a colon, like this:

    c on so le . l og ( t ru e ? 1 : 2 ) ;

    // 1

    c on so le . l og ( f al se ? 1 : 2 );

    // 2

    This one is called the conditional operator (or sometimes just ternaryoperator since it is the only such operator in the language). The valueon the left of the question mark picks which of the other two valueswill come out. When it is true, the middle value is chosen, and when itis false, the value on the right comes out.

    Undened values

    There are two special values, written nulland undefined, that are used to

    denote the absence of a meaningful value. They are themselves values,but they carry no information.

    Many operations in the language that dont produce a meaningful value(youll see some later) yield undefined simply because they have to yieldsomevalue.

    The dierence in meaning between undefinedand nullis an accident ofJavaScripts design, and it doesnt matter most of the time. In the caseswhere you actually have to concern yourself with these values, I recom-mend treating them as interchangeable (more on that in a moment).

    Automatic type conversion

    In the introduction, I mentioned that JavaScript goes out of its wayto accept almost any program you give it, even programs that do odd

    19

  • 7/26/2019 Eloquent JavaScriptdddd

    32/489

    things. This is nicely demonstrated by the following expressions:

    c o ns o le . l o g ( 8 * n u ll )

    // 0

    c o ns o le . l o g ( " 5" - 1 )

    // 4

    c o ns o le . l o g ( " 5" + 1 )

    // 51

    c o ns o le . l o g ( " f i ve " * 2 )

    // Na N

    c o ns o le . l o g ( f a ls e = = 0 )

    // true

    When an operator is applied to the wrong type of value, JavaScript willquietly convert that value to the type it wants, using a set of rules that

    often arent what you want or expect. This is calledtype coercion. So thenullin the rst expression becomes 0, and the "5"in the second expressionbecomes 5 (from string to number). Yet in the third expression, + triesstring concatenation before numeric addition, so the 1is converted to "1"(from number to string).

    When something that doesnt map to a number in an obvious way(such as "five" or undefined) is converted to a number, the value NaN isproduced. Further arithmetic operations on NaN keep producing NaN, soif you nd yourself getting one of those in an unexpected place, look for

    accidental type conversions.When comparing values of the same type using ==, the outcome is easyto predict: you should get true when both values are the same, except inthe case ofNaN. But when the types dier, JavaScript uses a complicatedand confusing set of rules to determine what to do. In most cases, it justtries to convert one of the values to the other values type. However,when null or undefinedoccurs on either side of the operator, it producestrue only if both sides are one of nullor undefined.

    c o ns o le . l o g ( n u ll = = u n d ef i n ed ) ;

    // true

    c o ns o le . l o g ( n u ll = = 0 ) ;

    // false

    That last piece of behavior is often useful. When you want to testwhether a value has a real value instead of null or undefined, you can

    20

  • 7/26/2019 Eloquent JavaScriptdddd

    33/489

    simply compare it to null with the ==(or !=) operator.But what if you want to test whether something refers to the precise

    value false? The rules for converting strings and numbers to Boolean

    values state that 0, NaN, and the empty string ("") count as false, whileall the other values count as true. Because of this, expressions like 0== falseand "" == false are also true. For cases like this, where you donotwant any automatic type conversions to happen, there are two extraoperators: ===and !==. The rst tests whether a value is precisely equalto the other, and the second tests whether it is not precisely equal. So"" === falseis false as expected.

    I recommend using the three-character comparison operators defen-sively to prevent unexpected type conversions from tripping you up.But when youre certain the types on both sides will be the same, thereis no problem with using the shorter operators.

    Short-circuiting of logical operators

    The logical operators && and || handle values of dierent types in apeculiar way. They will convert the value on their left side to Booleantype in order to decide what to do, but depending on the operator andthe result of that conversion, they return either the original left-handvalue or the right-hand value.

    The ||operator, for example, will return the value to its left when thatcan be converted to true and will return the value on its right otherwise.This conversion works as youd expect for Boolean values and should dosomething analogous for values of other types.

    c o ns o le . l o g ( n u ll | | " u s er " )

    // user

    c o ns o le . l o g ( " K a rl " | | " u s er " )

    // Karl

    This functionality allows the || operator to be used as a way to fall

    back on a default value. If you give it an expression that might producean empty value on the left, the value on the right will be used as areplacement in that case.

    The &&operator works similarly, but the other way around. When thevalue to its left is something that converts to false, it returns that value,

    21

  • 7/26/2019 Eloquent JavaScriptdddd

    34/489

    and otherwise it returns the value on its right.Another important property of these two operators is that the expres-

    sion to their right is evaluated only when necessary. In the case of true

    || X, no matter what Xiseven if its an expression that does somethingterriblethe result will be true, and Xis never evaluated. The same goesfor false && X, which is false and will ignore X. This is calledshort-circuitevaluation.

    The conditional operator works in a similar way. The rst expressionis always evaluated, but the second or third value, the one that is notpicked, is not.

    Summary

    We looked at four types of JavaScript values in this chapter: numbers,strings, Booleans, and undened values.

    Such values are created by typing in their name (true, null) or value (13,"abc"). You can combine and transform values with operators. We sawbinary operators for arithmetic (+, -, *, /, and %), string concatenation(+), comparison (==, !=, ===, !==, , =), and logic (&&, ||), as well asseveral unary operators (-to negate a number, !to negate logically, andtypeof to nd a values type) and a ternary operator (?:) to pick one oftwo values based on a third value.

    This gives you enough information to use JavaScript as a pocket cal-culator, but not much more. The next chapter will start tying theseexpressions together into basic programs.

    22

  • 7/26/2019 Eloquent JavaScriptdddd

    35/489

    And my heart glows bright red under my lmy, translucentskin and they have to administer 10cc of JavaScript to get meto come back. (I respond well to toxins in the blood.) Man,that stu will kick the peaches right out your gills!

    _why, Whys (Poignant) Guide to Ruby

    2 Program Structure

    In this chapter, we will start to do things that can actually be calledprogramming. We will expand our command of the JavaScript languagebeyond the nouns and sentence fragments weve seen so far, to the pointwhere we can express some meaningful prose.

    Expressions and statements

    In Chapter 1, we made some values and then applied operators to themto get new values. Creating values like this is an essential part of everyJavaScript program, but it is only a part.

    A fragment of code that produces a value is called an expression. Ev-ery value that is written literally (such as 22 or "psychoanalysis") is anexpression. An expression between parentheses is also an expression,as is a binary operator applied to two expressions or a unary operatorapplied to one.

    This shows part of the beauty of a language-based interface. Expres-sions can nest in a way very similar to the way subsentences in humanlanguages are nesteda subsentence can contain its own subsentences,and so on. This allows us to combine expressions to express arbitrarilycomplex computations.

    If an expression corresponds to a sentence fragment, a JavaScriptstate-mentcorresponds to a full sentence in a human language. A program issimply a list of statements.

    The simplest kind of statement is an expression with a semicolon after

    it. This is a program:

    1;

    ! f a l s e ;

    It is a useless program, though. An expression can be content to just

    23

  • 7/26/2019 Eloquent JavaScriptdddd

    36/489

    produce a value, which can then be used by the enclosing expression. Astatement stands on its own and amounts to something only if it aectsthe world. It could display something on the screenthat counts as

    changing the worldor it could change the internal state of the machinein a way that will aect the statements that come after it. These changesare called side eects. The statements in the previous example justproduce the values 1 and true and then immediately throw them away.This leaves no impression on the world at all. When executing theprogram, nothing observable happens.

    In some cases, JavaScript allows you to omit the semicolon at the endof a statement. In other cases, it has to be there, or the next line willbe treated as part of the same statement. The rules for when it canbe safely omitted are somewhat complex and error-prone. In this book,every statement that needs a semicolon will always be terminated byone. I recommend you do the same in your own programs, at least untilyouve learned more about subtleties involved in leaving out semicolons.

    Variables

    How does a program keep an internal state? How does it rememberthings? We have seen how to produce new values from old values, butthis does not change the old values, and the new value has to be immedi-ately used or it will dissipate again. To catch and hold values, JavaScriptprovides a thing called a variable.

    var c au gh t = 5 * 5;

    And that gives us our second kind of statement. The special word (key-word) varindicates that this sentence is going to dene a variable. It isfollowed by the name of the variable and, if we want to immediately giveit a value, by an =operator and an expression.

    The previous statement creates a variable called caught and uses it to

    grab hold of the number that is produced by multiplying 5 by 5.After a variable has been dened, its name can be used as an expres-

    sion. The value of such an expression is the value the variable currentlyholds. Heres an example:

    24

  • 7/26/2019 Eloquent JavaScriptdddd

    37/489

    var ten = 10;

    c o ns o le . l o g ( t en * t en ) ;

    // 10 0

    Variable names can be any word that isnt a reserved word (such asvar). They may not include spaces. Digits can also be part of variablenamescatch22 is a valid name, for examplebut the name must notstart with a digit. A variable name cannot include punctuation, exceptfor the characters $ and _.

    When a variable points at a value, that does not mean it is tied tothat value forever. The = operator can be used at any time on existingvariables to disconnect them from their current value and have thempoint to a new one.

    v ar m oo d = " l ig ht " ;

    c o n s o l e . l o g ( m o o d ) ;

    // light

    m oo d = " d ar k ";

    c o n s o l e . l o g ( m o o d ) ;

    // dark

    You should imagine variables as tentacles, rather than boxes. They donotcontainvalues; theygraspthemtwo variables can refer to the samevalue. A program can access only the values that it still has a hold on.

    When you need to remember something, you grow a tentacle to hold onto it or you reattach one of your existing tentacles to it.

    25

  • 7/26/2019 Eloquent JavaScriptdddd

    38/489

    Lets look at an example. To remember the number of dollars that Luigistill owes you, you create a variable. And then when he pays back $35,you give this variable a new value.

    v ar l u ig is D eb t = 1 40 ;

    l u ig i sD e bt = l u ig is D eb t - 3 5;

    c o n s o l e . l o g ( l u i g i s D e b t ) ;

    // 10 5

    When you dene a variable without giving it a value, the tentacle hasnothing to grasp, so it ends in thin air. If you ask for the value of anempty variable, youll get the value undefined.

    A single var statement may dene multiple variables. The denitionsmust be separated by commas.

    var one = 1 , t wo = 2;

    c o ns o le . l o g ( o ne + t wo ) ;

    // 3

    Keywords and reserved words

    Words with a special meaning, such as var, are keywords, and they maynot be used as variable names. There are also a number of words that are

    reserved for use in future versions of JavaScript. These are also o-cially not allowed to be used as variable names, though some JavaScriptenvironments do allow them. The full list of keywords and reservedwords is rather long.

    b r ea k c a se c a tc h c l as s c o ns t c o nt i n ue d e bu g g er

    d ef au lt d el et e d o e ls e e nu m e xp or t e x te nd s f al se

    f in al ly f or f u nc ti o n i f i m pl em e nt s i mp or t i n

    i n s ta n c eo f i n t er f a ce l et n e w n u ll p a c ka g e p r iv a t e

    p r o te c t ed p u bl i c r e tu r n s t at i c s u pe r s w it c h t h is

    t hr ow t ru e t ry t yp eo f v ar v oi d w hi le w it h y ie ld

    Dont worry about memorizing these, but remember that this might bethe problem when a variable denition does not work as expected.

    26

  • 7/26/2019 Eloquent JavaScriptdddd

    39/489

    The environment

    The collection of variables and their values that exist at a given time is

    called the environment. When a program starts up, this environment isnot empty. It always contains variables that are part of the languagestandard, and most of the time, it has variables that provide ways tointeract with the surrounding system. For example, in a browser, thereare variables and functions to inspect and inuence the currently loadedwebsite and to read mouse and keyboard input.

    Functions

    A lot of the values provided in the default environment have the typefunction. A function is a piece of program wrapped in a value. Suchvalues can beappliedin order to run the wrapped program. For example,in a browser environment, the variable alertholds a function that showsa little dialog box with a message. It is used like this:

    a l e r t ( " G o o d m o r n i n g ! " ) ;

    Executing a function is called invoking, calling, or applying it. You cancall a function by putting parentheses after an expression that producesa function value. Usually youll directly use the name of the variablethat holds the function. The values between the parentheses are givento the program inside the function. In the example, the alert functionuses the string that we give it as the text to show in the dialog box.Values given to functions are calledarguments. The alertfunction needsonly one of them, but other functions might need a dierent number or

    dierent types of arguments.

    27

  • 7/26/2019 Eloquent JavaScriptdddd

    40/489

    The console.log function

    Thealertfunction can be useful as an output device when experimenting,

    but clicking away all those little windows will get on your nerves. In pastexamples, weve used console.logto output values. Most JavaScript sys-tems (including all modern web browsers and Node.js) provide a console.log function that writes out its arguments to some text output device.In browsers, the output lands in the JavaScript console. This part ofthe browser interface is hidden by default, but most browsers open itwhen you press F12 or, on Mac, when you press Command-Option-I. Ifthat does not work, search through the menus for an item named webconsole or developer tools.

    var x = 30;c on so le . l og ( " th e v al ue o f x i s ", x ) ;

    // the va lu e of x is 30

    Though variable names cannot contain period characters, console.logclearly has one. This is because console.log isnt a simple variable. Itis actually an expression that retrieves the log property from the valueheld by the console variable. We will nd out exactly what this meansin Chapter 4.

    Return values

    Showing a dialog box or writing text to the screen is aside eect. A lot offunctions are useful because of the side eects they produce. Functionsmay also produce values, and in that case, they dont need to have a sideeect to be useful. For example, the function Math.maxtakes any numberof number values and gives back the greatest.

    c o n s o le . l o g ( M a t h . m a x ( 2 , 4 ) ) ;

    // 4

    When a function produces a value, it is said toreturnthat value. Any-thing that produces a value is an expression in JavaScript, which meansfunction calls can be used within larger expressions. Here a call to Math.min, which is the opposite of Math.max, is used as an input to the plus

    28

  • 7/26/2019 Eloquent JavaScriptdddd

    41/489

    operator:

    c o ns o le . l o g ( M a th . m i n ( 2 , 4 ) + 1 0 0) ;

    // 10 2

    The next chapter explains how to write your own functions.

    prompt and conrm

    Browser environments contain other functions besides alertfor poppingup windows. You can ask the user an OK/Cancel question using confirm.This returns a Boolean: true if the user clicks OK and false if the userclicks Cancel.

    c o nf i rm ( " S h a l l w e , t h en ? " ) ;

    The prompt function can be used to ask an open question. The rstargument is the question, the second one is the text that the user startswith. A line of text can be typed into the dialog window, and the function

    will return this text as a string.

    p r om p t ( " T el l m e e v e ry t h in g y o u k n ow . " , " . .. " ) ;

    These two functions arent used much in modern web programming,

    mostly because you have no control over the way the resulting windowslook, but they are useful for toy programs and experiments.

    29

  • 7/26/2019 Eloquent JavaScriptdddd

    42/489

    Control ow

    When your program contains more than one statement, the statements

    are executed, predictably, from top to bottom. As a basic example, thisprogram has two statements. The rst one asks the user for a number,and the second, which is executed afterward, shows the square of thatnumber.

    v ar t h eN u mb e r = N um be r ( p ro mp t ( " Pi ck a n um be r " , " ") ) ;

    a le rt ( " Yo ur n um be r i s t he s qu ar e r oo t of " +

    t h e Nu m b er * t h e Nu m b er ) ;

    The function Numberconverts a value to a number. We need that conver-sion because the result of promptis a string value, and we want a number.

    There are similar functions called String and Booleanthat convert valuesto those types.

    Here is the rather trivial schematic representation of straight controlow:

    Conditional execution

    Executing statements in straight-line order isnt the only option we have.An alternative is conditional execution, where we choose between twodierent routes based on a Boolean value, like this:

    Conditional execution is written with the if keyword in JavaScript. In

    the simple case, we just want some code to be executed if, and only if,a certain condition holds. For example, in the previous program, wemight want to show the square of the input only if the input is actuallya number.

    v ar t h eN u mb e r = N um be r ( p ro mp t ( " Pi ck a n um be r " , " ") ) ;

    30

  • 7/26/2019 Eloquent JavaScriptdddd

    43/489

    i f ( ! i s Na N ( t h e N um b e r ) )

    a le rt ( " Yo ur n um be r i s t he s qu ar e r oo t o f " +

    t h e Nu m b er * t h e Nu m b er ) ;

    With this modication, if you enter cheese, no output will be shown.The keyword ifexecutes or skips a statement depending on the value

    of a Boolean expression. The deciding expression is written after thekeyword, between parentheses, followed by the statement to execute.

    The isNaN function is a standard JavaScript function that returns trueonly if the argument it is given is NaN. The Number function happens toreturn NaNwhen you give it a string that doesnt represent a valid number.Thus, the condition translates to unless theNumber is not-a-number, dothis.

    You often wont just have code that executes when a condition holdstrue, but also code that handles the other case. This alternate path isrepresented by the second arrow in the diagram. The else keyword canbe used, together with if, to create two separate, alternative executionpaths.

    v ar t h eN u mb e r = N um be r ( p ro mp t ( " Pi ck a n um be r " , " ") ) ;

    i f ( ! i s Na N ( t h e N um b e r ) )

    a le rt ( " Yo ur n um be r i s t he s qu ar e r oo t o f " +

    t h e Nu m b er * t h e Nu m b er ) ;

    else

    a l er t ( " H ey . W hy d id n t y ou g iv e me a n um be r ?" ) ;

    If we have more than two paths to choose from, multiple if/else pairscan be chained together. Heres an example:

    v ar n um = N um be r ( p ro mp t ( " Pi ck a n um be r " , " 0" ) ) ;

    if ( num < 10)

    a l e r t ( " S m a l l " ) ;

    e ls e if ( nu m < 1 00 )

    a l e r t ( " M e d i u m " ) ;

    elsea l e r t ( " L a r g e " ) ;

    The program will rst check whether num is less than 10. If it is, itchooses that branch, shows "Small", and is done. If it isnt, it takes theelse branch, which itself contains a second if. If the second condition

    31

  • 7/26/2019 Eloquent JavaScriptdddd

    44/489

    (< 100) holds, that means the number is between 10 and 100, and "Medium"is shown. If it doesnt, the second, and last, elsebranch is chosen.

    The ow chart for this program looks something like this:

    while and do loops

    Consider a program that prints all even numbers from 0 to 12. One wayto write this is as follows:

    c o n s o l e . l o g ( 0 ) ;

    c o n s o l e . l o g ( 2 ) ;

    c o n s o l e . l o g ( 4 ) ;

    c o n s o l e . l o g ( 6 ) ;

    c o n s o l e . l o g ( 8 ) ;

    c o n s o l e . l o g ( 1 0 ) ;

    c o n s o l e . l o g ( 1 2 ) ;

    That works, but the idea of writing a program is to make something

    lesswork, not more. If we needed all even numbers less than 1,000, theprevious would be unworkable. What we need is a way to repeat somecode. This form of control ow is called a loop:

    Looping control ow allows us to go back to some point in the programwhere we were before and repeat it with our current program state. If

    we combine this with a variable that counts, we can do something likethis:

    v ar n um be r = 0 ;

    w hi le ( n um be r

  • 7/26/2019 Eloquent JavaScriptdddd

    45/489

    n um be r = n um be r + 2 ;

    }

    // 0

    // 2

    // ... e tc et er a

    A statement starting with the keyword while creates a loop. The wordwhile is followed by an expression in parentheses and then a statement,much like if. The loop executes that statement as long as the expressionproduces a value that is true when converted to Boolean type.

    In this loop, we want to both print the current number and add two toour variable. Whenever we need to execute multiple statements inside aloop, we wrap them in curly braces ({ and }). Braces do for statementswhat parentheses do for expressions: they group them together, makingthem count as a single statement. A sequence of statements wrapped inbraces is called ablock.

    Many JavaScript programmers wrap every single loop or if body inbraces. They do this both for the sake of consistency and to avoidhaving to add or remove braces when changing the number of statementsin the body later. In this book, I will write most single-statement bodieswithout braces, since I value brevity. You are free to go with whicheverstyle you prefer.

    The variable number demonstrates the way a variable can track the

    progress of a program. Every time the loop repeats, number is incre-mented by 2. Then, at the beginning of every repetition, it is comparedwith the number 12to decide whether the program has done all the workit intended to do.

    As an example that actually does something useful, we can now write aprogram that calculates and shows the value of 210 (2 to the 10th power).We use two variables: one to keep track of our result and one to counthow often we have multiplied this result by 2. The loop tests whetherthe second variable has reached 10 yet and then updates both variables.

    v a