100% found this document useful (4 votes)
111 views62 pages

Instant Download Get Programming With JavaScript First Edition John R Larsen PDF All Chapter

JavaScript

Uploaded by

eldeebguenos
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
100% found this document useful (4 votes)
111 views62 pages

Instant Download Get Programming With JavaScript First Edition John R Larsen PDF All Chapter

JavaScript

Uploaded by

eldeebguenos
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 62

Download the full version of the textbook now at textbookfull.

com

Get Programming with JavaScript First Edition


John R Larsen

https://textbookfull.com/product/get-programming-
with-javascript-first-edition-john-r-larsen/

Explore and download more textbook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Get Programming with JavaScript Next New features of


ECMAScript 2015 2016 and beyond 1st Edition Jd Isaacks

https://textbookfull.com/product/get-programming-with-javascript-next-
new-features-of-ecmascript-2015-2016-and-beyond-1st-edition-jd-
isaacks/
textbookfull.com

Reactive Programming with JavaScript 1st Edition Hayward


Jonathan

https://textbookfull.com/product/reactive-programming-with-
javascript-1st-edition-hayward-jonathan/

textbookfull.com

Get Programming with Scala MEAP V05 Daniela Sfregola

https://textbookfull.com/product/get-programming-with-scala-
meap-v05-daniela-sfregola/

textbookfull.com

Human Resources in Healthcare Managing for Success Bruce


J. Fried

https://textbookfull.com/product/human-resources-in-healthcare-
managing-for-success-bruce-j-fried/

textbookfull.com
Kings of Lockdown (Brutal Boys of Everlake Prep #2) 1st
Edition Caroline Peckham & Susanne Valenti [Peckham

https://textbookfull.com/product/kings-of-lockdown-brutal-boys-of-
everlake-prep-2-1st-edition-caroline-peckham-susanne-valenti-peckham/

textbookfull.com

Women Secrets - Collective Wisdom of the Last 5,000 Years


Titansvision

https://textbookfull.com/product/women-secrets-collective-wisdom-of-
the-last-5000-years-titansvision/

textbookfull.com

Methodologies and Intelligent Systems for Technology


Enhanced Learning 10th International Conference Pierpaolo
Vittorini
https://textbookfull.com/product/methodologies-and-intelligent-
systems-for-technology-enhanced-learning-10th-international-
conference-pierpaolo-vittorini/
textbookfull.com

The European World 1500 1800 An Introduction to Early


Modern History Beat Kümin

https://textbookfull.com/product/the-european-world-1500-1800-an-
introduction-to-early-modern-history-beat-kumin/

textbookfull.com

Experiencing ACT from the Inside Out A Self Practice Self


Reflection Workbook for Therapists 1st Edition Dennis
Tirch
https://textbookfull.com/product/experiencing-act-from-the-inside-out-
a-self-practice-self-reflection-workbook-for-therapists-1st-edition-
dennis-tirch/
textbookfull.com
Things My Son Needs to Know About the World 1st Edition
Fredrik Backman

https://textbookfull.com/product/things-my-son-needs-to-know-about-
the-world-1st-edition-fredrik-backman/

textbookfull.com
The Crypt: a running example

Throughout this book, you develop a text-based adventure game called The Crypt.
Players can explore locations on a map, moving from place to place and picking up
items to help them solve challenges and get past obstacles. The last section of each
chapter uses what you’ve learned to develop the game further. You’ll see how the pro-
gramming concepts help you build the pieces that are then combined to produce a
large program.

Game element Task JavaScript Chapter

Players Deciding what information you need to Variables 2


know about each player

Collecting player information in one place Objects 3

Displaying information about players on Functions 4–7


the console

Creating a list of items collected by each Arrays 8


player

Organizing player-creation code Constructors 9

Places Creating lots of places to explore, all with Constructors 9


a similar structure

Joining places with exits Square bracket notation 10

Game Adding simple functions for movement, Square bracket notation 10


collecting items, and displaying informa-
tion

Maps Joining places with exits Square bracket notation 10


Get Programming with JavaScript
Get Programming
with JavaScript
JOHN R. LARSEN

MANNING
SHELTER ISLAND
For online information and ordering of this and other Manning books, please visit
www.manning.com. The publisher offers discounts on this book when ordered in quantity.
For more information, please contact
Special Sales Department
Manning Publications Co.
20 Baldwin Road
PO Box 761
Shelter Island, NY 11964
Email: orders@manning.com

©2016 by Manning Publications Co. All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in


any form or by means electronic, mechanical, photocopying, or otherwise, without prior written
permission of the publisher.

Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial caps
or all caps.

Recognizing the importance of preserving what has been written, it is Manning’s policy to have
the books we publish printed on acid-free paper, and we exert our best efforts to that end.
Recognizing also our responsibility to conserve the resources of our planet, Manning books
are printed on paper that is at least 15 percent recycled and processed without the use of
elemental chlorine.

Manning Publications Co. Development editor: Helen Stergius


20 Baldwin Road Technical development editors: Chuck Henderson, Ozren Harlovic
PO Box 761 Review editor: Ozren Harlovic
Shelter Island, NY 11964 Project editor: Tiffany Taylor
Copyeditor: Linda Recktenwald
Proofreaders: Elizabeth Martin
Bonnie Culverhouse
Technical proofreader: Romin Irani
Typesetter: Dennis Dalinnik
Cover designer: Leslie Haimes

ISBN: 9781617293108
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – EBM – 21 20 19 18 17 16
brief contents
PART 1 CORE CONCEPTS ON THE CONSOLE . .............................1
1 ■ Programming, JavaScript, and JS Bin 3
2 ■ Variables: storing data in your program 16
3 ■ Objects: grouping your data 27
4 ■ Functions: code on demand 40
5 ■ Arguments: passing data to functions 57
6 ■ Return values: getting data from functions 70
7 ■ Object arguments: functions working with objects 83
8 ■ Arrays: putting data into lists 104
9 ■ Constructors: building objects with functions 122
10 ■ Bracket notation: flexible property names 147

PART 2 ORGANIZING YOUR PROGRAMS ..................................169


11 ■ Scope: hiding information 171
12 ■ Conditions: choosing code to run 198
13 ■ Modules: breaking a program into pieces 221
14 ■ Models: working with data 248

v
vi BRIEF CONTENTS

15 ■ Views: displaying data 264


16 ■ Controllers: linking models and views 280

PART 3 JAVASCRIPT IN THE BROWSER .....................................299


17 ■ HTML: building web pages 301
18 ■ Controls: getting user input 323
19 ■ Templates: filling placeholders with data 343
20 ■ XHR: loading data 367
21 ■ Conclusion: get programming with JavaScript 387

22 ■ Node: running JavaScript outside the browser online


23 ■ Express: building an API online
24 ■ Polling: repeating requests with XHR online
25 ■ Socket.IO: real-time messaging online
contents
foreword xvii
preface xix
acknowledgments xxi
about this book xxii

PART 1 CORE CONCEPTS ON THE CONSOLE . ..................1

1 Programming, JavaScript, and JS Bin 3


1.1 Programming 3
1.2 JavaScript 4
1.3 Learning by doing and thinking 5
1.4 JS Bin 5
JS Bin panels 6 Following the code listings on JS Bin 7

Logging to the console 8 Code comments 9 Further


■ ■

Adventures 9 Error messages 9 Line numbers 10


■ ■

Get an account 10
1.5 The Crypt—our running example 11
Playing The Crypt 11 ■
Steps for building The Crypt 12
1.6 Further examples and practice 14
1.7 Browser support 15
1.8 Summary 15

vii
viii CONTENTS

2 Variables: storing data in your program 16


2.1 What is a variable? 17
2.2 Declaring variables and assigning values 17
Declaring variables 17 Assigning values to variables 18

One-step declaration and assignment 20 Using a variable in ■

its own assignment 21


2.3 Choosing good variable names 22
Keywords and reserved words 22 Rules for naming ■

variables 23 camelCase 23 Use descriptive


■ ■

variable names 24
2.4 The Crypt—player variables 24
2.5 Summary 25

3 Objects: grouping your data 27


3.1 A need for organization 28
3.2 Creating objects 29
Creating an empty object 30 ■
Properties as key-value pairs 30
3.3 Accessing object properties 32
3.4 Updating object properties 33
3.5 Further examples 35
Writing a blog 35 Creating a calendar 35 What’s the
■ ■

weather like? 36 The testing effect 37 Create your own


■ ■
37
3.6 The Crypt—a player object 37
3.7 Summary 39

4 Functions: code on demand 40


4.1 Noticing repetition 40
Displaying object properties as text 41 ■
Adding tax and
displaying a summary 42
4.2 Defining and calling functions 43
Defining new functions 44 Function expressions and

function declarations 45 Using functions 46


Functions step by step 47


4.3 Reducing repetition 48
A function for displaying object properties as text 48
Functions for adding tax and displaying a summary 50
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
CONTENTS ix

4.4 Making code easier to read and update 52


Updating the showMovieInfo function 52
4.5 The Crypt—displaying player information 54
A function to display player information 55
4.6 Summary 56

5 Arguments: passing data to functions 57


5.1 Function reuse and versatility 57
5.2 Passing information to functions 59
Passing one argument to a function 59 ■
Passing multiple
arguments to a function 63
5.3 The Crypt—displaying player information 64
Displaying players’ names 65 Displaying players’ health 66

Displaying players’ locations 67 Putting it all together—


displaying players’ information 68


5.4 Summary 69

6 Return values: getting data from functions 70


6.1 Returning data from functions 70
The return value replaces the function call 71 The return ■

keyword 72 Using arguments to determine the return value



72
6.2 Experimenting at the console prompt 75
Calling functions 75 ■
Declaring new variables 76
6.3 The Crypt—building player information strings 77
Building strings for a player’s name, health, and location 78
A function for player information—putting the pieces together 79
6.4 Summary 81

7 Object arguments: functions working with objects 83


7.1 Using objects as arguments 84
Accessing properties of an object argument 84 ■
Adding properties
to an object argument 85
7.2 Returning objects from functions 87
Building planets—an object creation function 87 ■
Points in
2D space 89
x CONTENTS

7.3 Methods—setting functions as properties of objects 91


Namespaces—organizing related functions 91
Math methods 92 String methods 94 spacer—more methods
■ ■

for your namespace 96 Deep namespace exploration 98


7.4 The Crypt–player objects as arguments 101


7.5 Summary 102

8 Arrays: putting data into lists 104


8.1 Creating arrays and accessing elements
Creating an array 105 ■
Accessing array elements
104
106
8.2 Array methods 110
Adding and removing elements 111 Slicing and splicing

arrays 111 Visiting each element with forEach 113


8.3 The Crypt—a player items array 118


8.4 Summary 120

9 Constructors: building objects with functions 122


9.1 Using functions to build objects
Adding properties 124 ■
123
Adding methods 125
9.2 Using constructor functions to build objects 127
Constructor functions 127 ■
World building—making use of
the Planet constructor 130 ■
Telling objects apart with the
instanceof operator 131
9.3 Building mastery—two examples of constructors 132
9.4 The Crypt—providing places to plunder 134
Building the Place constructor—title and description 135
Building the Place constructor—items for your hoard 136
Building the Place constructor—exits to explore 137
9.5 The Crypt—streamlining player creation 140
Organizing player properties 141 Turning functions

into methods 143 Assigning places to players 144


Using null as a placeholder for objects 144


9.6 Summary 145

10 Bracket notation: flexible property names 147


10.1 Using square brackets instead of dots
Brackets in action—people’s names as keys 150
148
■ Making the most
of square bracket notation—word counts 152
CONTENTS xi

10.2 The Crypt—enhancing exit excitement 155


Using an object to hold the exits 156 Creating functions to

add and display exits 158 Giving each place object its own

set of exits 159 Adding the exits object to the full Place

constructor 161 Testing the Place constructor 163


10.3 The Crypt—let the games begin! 164


Updating the display—render 165 Exploring the

map—go 166 Collecting all the things—get 166


Designing a bigger adventure—Jahver’s ship 167


10.4 What’s next? 167
10.5 Summary 167

PART 2 ORGANIZING YOUR PROGRAMS.......................169

11 Scope: hiding information 171


11.1 The dangers of global variables 172
Access all areas—peeking and tweaking 173 Access all areas—

relying on an implementation 174 Naming collisions 176


Crazy bugs 177


11.2 The benefits of local variables 177
11.3 Interfaces—controlling access and providing
functionality 179
Using a function to hide variables 180 Creating multiple

independent counters with getCount 181 Creating multiple


independent counters with a constructor function 182


11.4 Creating a quick quiz app 183
Using an object as a namespace 184 ■ Hiding the questions
array 185
11.5 The Crypt—hiding player info 187
Our current Player constructor—everything is public 187
An updated Player constructor—some variables are hidden 188
11.6 The Crypt—hiding place info 191
11.7 The Crypt—user interaction 193
The interface—go and get 194 ■ Hiding the implementation 195
11.8 Summary 196
xii CONTENTS

12 Conditions: choosing code to run 198


12.1 Conditional execution of code 199
The strict equality operator, === 199 The if statement

200
The else clause 200 Hide the secret number inside a

function 202
12.2 Generating random numbers with Math.random() 204
12.3 Further conditions with else if 206
Comparison operators 208
12.4 Checking answers in the quiz app 210
Multiple declarations with a single var keyword 211
Displaying a question 212 Moving to the next question

213
Checking the player’s answer 213 Handling a player’s

answer 214 Returning the interface object 214


12.5 The Crypt—checking user input 214


Step by step through the go method 215 Never trust ■

user input 216 Safe exploration—using the if statement


to avoid problems 217


12.6 Summary 219

13 Modules: breaking a program into pieces 221


13.1 Understanding bins and files on JS Bin 223
Creating a bin 225 ■
Writing some code 225 Making a note ■

of the filename 225 ■


Viewing an individual code file 226
13.2 Importing files into other projects 226
Creating a bin 227 Writing some code 227
■ ■
Adding a
script element 227 Refreshing the page 228
■ ■
Running the
program 228
13.3 Importing the Number Generator—further
examples 229
Picking random questions in the quiz app 230 ■
Using the between
function in your guessing game 231
13.4 Importing multiple files 232
13.5 Collisions—when imported code overwrites
your variables 234
Variable collisions 236 ■
Minimizing collisions by
using namespaces 237
CONTENTS xiii

13.6 Immediately invoked function expressions (IIFE) 238


Recognizing function expressions 240 Invoking functions 240

Immediately invoking function expressions 241 Returning ■

information from an IIFE 241


13.7 The Crypt—organizing code into modules 242
Sharing a namespace across modules 244
13.8 Summary 246

14 Models: working with data


14.1
248
Building a fitness app—data and models
Defining a User constructor 250 Getting a feel for the

249

data as a JavaScript object 251 Converting the data into


a user model 252 What’s next for the fitness app? 253

14.2 The Crypt—separating map data from the game 253


Map data 255 Adding challenges to the map data 256

Updating the Place constructor to include challenges 258


Using the map data to build a game map 258 Bringing all ■

the pieces together to run the game 262


14.3 Summary 263

15 Views: displaying data 264


15.1 Building a fitness app—displaying the latest user
data 265
Creating your first fitness app view 266 Using modules to switch

fitness app views 267 What’s next for the fitness app? 268

15.2 The Crypt—moving view code from Player and Place 268
Creating a view for players 269 ■
Creating a view for places 274
15.3 Talking to players—a message view 278
15.4 Summary 279

16 Controllers: linking models and views 280


16.1 Building a fitness app—controllers 281
What does the controller do? 281 Building the fitness app

controller 282 Putting the pieces together for a working


fitness app 283 What’s next for the fitness app? 284

16.2 The Crypt—adding a game controller 284


What does the controller do? 285 ■
Approaching the
controller code 286
xiv CONTENTS

16.3 The Crypt—the structure of the controller code 287


16.4 The Crypt—starting and stopping the game 287
Initializing the game 288 Monitoring player health 288

Updating the display—functions that use the view modules 289


16.5 The Crypt—giving commands and solving puzzles 290
Picking up items with game.get 290 Listing the properties

of a challenge 291 Moving with game.go 292


Licking the leopard with game.use 294


16.6 The Crypt—running the game 296
16.7 The Crypt—what’s next for the app? 298
16.8 Summary 298

PART 3 JAVASCRIPT IN THE BROWSER .........................299

17 HTML: building web pages 301


17.1 HTML, CSS, JavaScript—building a web page 302
Loading the layers 303 ■
Loading the layers in JS Bin 304
17.2 HTML—a very short introduction 304
Starting with an empty page 305 Adding some content 305

Marking up a list 306 Some common HTML elements 307


17.3 Adding content to a web page with JavaScript 309


Getting an element by its id 310 ■
Function declarations 311
What, no JavaScript? 311
17.4 Displaying data from an array 311
17.5 The Crypt—displaying players and places with
web views 314
Updating the player and place view modules—the render
method 315 Updating the player and place view modules—

the listings 317 Using JavaScript’s strict mode 318


Loading modules and adding placeholders in the HTML 318


Adding a touch of CSS 319 Playing the game 320

Preparing the message view 320


17.6 Summary 321

18 Controls: getting user input 323


18.1 Working with buttons 324
Adding a button to a page 324 Writing functions to update the

greeting 325 Listening for clicks 325



CONTENTS xv

18.2 Using a select element to choose an option 327


Adding a select element to the page 328 ■ A function to rate movies
and a button to call it 329
18.3 Reading user input with text boxes 330
Adding a text box to the page 331 Adding an unordered

list to display the comments 332 Getting references to the


new elements 332 Updating the rateMovie function 332


Styling the examples with CSS 334


18.4 The Crypt—player commands via a text box 334
Adding controls to the page 335 Mapping text box entries

to game commands 336 Issuing orders with split, join, pop,


and shift 336 Deciding between options with switch 338


Making it so—listening for button clicks 339


Enter The Crypt 340
18.5 Summary 341

19 Templates: filling placeholders with data 343


19.1 Building a news page—breaking news 344
Comparing the news item data and HTML 345 Constructing ■

the HTML by string concatenation 345 Designing with HTML


templates 346 Using script tags for templates 346


19.2 Replacing one string with another 347


Chaining calls to replace 348
19.3 While loops—replacing a string multiple times 349
Repeating code while a condition is met 350 The while ■

loop 351 Replacing a string while it can be found 352


Replacing strings with regular expressions 353


19.4 Automating placeholder replacement for templates 353
Matching template placeholders with object properties 353
Filling all of the placeholders for each key 355 Building a list

of items using a template 355


19.5 Building a news page—news just in 357
Creating the templates and data modules 357 ■ Importing the
modules 359
19.6 The Crypt—improving the views 360
Creating HTML templates for all of the views 361 Updating the ■

views to use the new templates 362 Enter The Crypt 365

19.7 Summary 365


xvi CONTENTS

20 XHR: loading data 367


20.1 Building a fitness app—retrieving user data
Locating the user data 368 Loading the user data—an outline 370

368

Loading the user data—the XMLHttpRequest constructor 370


Loading the user data—parsing the XHR response with JSON.parse 372
Loading JS Bin data—a handy function 373 Building the fitness

app 374 The fitness app—what’s next? 376


20.2 JSON—a simple data format 377


Converting JSON into objects and arrays with JSON.parse 378
20.3 The Crypt—loading a map on demand 378
Specifying exits with JS Bin file codes 379 Using a cache—load

each place only once 380 Replacing the Map Data and Map

Builder modules with Map Manager 380 Updating the game■

controller to use the Map Manager 383 Building the game


page 384 Enter The Crypt 386


20.4 Summary 386

21 Conclusion: get programming with JavaScript 387


21.1 Working locally with files
Writing code 388 ■
387
Saving files 388 Opening your pages

in a browser 390 ■ Concatenating and minifying files 390


21.2 Getting help 391
21.3 What next? 392
The companion site 392 Books ■ 392 ■ Sites 392
Practice makes permanent 392
21.4 Summary 393

22 Node: running JavaScript outside the browser


available online at www.manning.com/books/get-programming-with-javascript

23 Express: building an API


available online at www.manning.com/books/get-programming-with-javascript

24 Polling: repeating requests with XHR


available online at www.manning.com/books/get-programming-with-javascript

25 Socket.IO: real-time messaging


available online at www.manning.com/books/get-programming-with-javascript

index 395
foreword
When John emailed me to ask if I would write a foreword for Get Programming with
JavaScript, I have to admit the main thing that got me on the hook was that he had
used JS Bin throughout the book to let readers try out live demos. JS Bin was created
in 2008 as a place for programmers to collaborate, test, debug, experiment, and share.
Education is close to JS Bin’s heart, so John’s background as a teacher and his practi-
cal approach seemed like a great fit with its ethos and purpose. I’m a firm believer
that getting your hands dirty with real code is a great way to learn, and being encour-
aged to create, extend, play, and rewrite, all in a safe, no-mistakes-barred space,
looked like a good idea for a beginners’ programming book.
As the developer of JS Bin, an application created with JavaScript, I’m always
excited to see JS Bin being used to teach beginners, and that’s exactly what John does
with this book. It goes without saying that different people in different contexts take
different lengths of time to learn programming. But they all benefit from a practical
approach. JS Bin, as a free resource requiring no installation, provides an instantly
accessible environment in which to learn, and this book provides the guidance to get
started, the support to keep practicing, and the encouragement to enjoy the adventure.
I remember seeing object dot notation well over 10 years ago and wondering how I
was supposed to Google “What does . mean?” If I’d had John’s gentle and thorough
introduction to JavaScript back then, I would have saved myself a lot of pain wading
through many failed search attempts! He doesn’t cover everything, but he takes his
time with key concepts, showing patience and consideration for readers and encour-
aging them to stretch their knowledge and build their skills. The variety of examples

xvii
xviii FOREWORD

really helps; there’s lots to get your teeth into, but also plenty of support and sugges-
tions for further practice. Don’t get lost in The Crypt—trust your guide. It builds into a
substantial project and should help you see how little pieces can make big apps.
I’ve had the privilege of creating a number of tools for the programmer commu-
nity, and a number of JavaScript tools in particular. Programming lets us make things
for fun, for profit, and for others, and it’s wonderful to welcome newcomers to the
fold; who knows what great ideas they’ll have as they build the next big thing (or the next
small thing!)? I’m thrilled that their first steps on such an exciting path will be on
JS Bin. Welcome! Create bins for your code, tinker, share, and build up your bank of
modules. Get Programming with JavaScript shows you how to manage your code bins and
combine them into bigger projects. (You even get to play with the HTML and CSS
panels on JS Bin!)
Enjoy the book, dear reader. I expect that by the end of it, you’ll have a firm grasp
of how to write JavaScript.

REMY SHARP
FOUNDER OF JS BIN
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
preface
I started programming using the BASIC language on a Commodore VIC-20 in 1982. It
had 3.5 KB of RAM, and programming involved me copying a program from a maga-
zine, instruction by instruction and line by line. The process was time-consuming and
error-prone, but it certainly built focus and attention to detail! Rather than cut-and-
paste, it was read-and-type; but eventually, the program was transferred from the
printed page to the computer’s memory. Then the moment of truth … and alas, it
never worked the first time. And that’s where my learning really began.
Staring at the code, trying to make sense of the instructions and follow the flow of
the program as it jumped from line to line, I had to think carefully and patiently about
what was going on. Not everything made sense—sometimes squeezing a program into
3.5 KB required some seriously supple code gymnastics—but, bit by bit, the program’s
secrets would start to reveal themselves. Sometimes my typos stopped the program from
running; sometimes there were mistakes in the code itself. Most of the time, but not
always, I eventually got the program to run.
Half the time, the program would turn out to be rubbish! I’d reach out and hit
the VIC-20’s off switch, and the program would be gone forever. (It took five minutes
and a cassette-tape recorder to save, and some programs just weren’t worth it.) I
wasn’t usually upset, and I didn’t see it as a waste of time; from the start, I was amazed
by the transformation of text into a working program (even a rubbish one) on the
computer screen.
Today, in 2016, with our smartphones, tablets, drones, and AI Go champions, that
sense of wonder has grown even stronger. Programming is magical and transformative.

xix
xx PREFACE

Even knowing how it works, I still love how my typed instructions turn into a working
website, a fun game, or a useful utility.
As a teacher in the United Kingdom, I’m privileged to be able to teach 16 - and
17-year-olds programming. My philosophy is to let them get programming from lesson
one: to enter code and see the result as soon as possible. I want them to be curious
and experiment at all times. It’s great to see their eyes widen and their smiles grow as
they start their adventures in code and realize they can convert imagination into real-
ity. Online code-editing environments such as JS Bin allow them to quickly try out
ideas and build projects piece by piece. They don’t learn a long list of language fea-
tures before beginning; they learn a few concepts at a time, often in response to getting
stuck but also directly from me (they don’t know what they don’t know), and they prac-
tice and experiment before moving on. Their skills build day by day and week by week,
and code that might have seemed like cryptic hieroglyphs at the start of the course
becomes second nature by the end. It’s great to be a part of that learning process.
In addition to being a teacher, I’m also a programmer and develop education
applications, including ones for organizing, sharing, and booking resources; creating
online handbooks; planning lessons; managing timetables; and generating quizzes.
It’s great to see people using the applications as part of their day-to-day work; I’m
lucky to understand the target audience, being one of them myself, and to see first-
hand my applications used over an extended period—that’s great feedback!
I’ve reviewed a number of book manuscripts for Manning. Having seen my bio
describing me as a programmer and a teacher, Manning suggested that I write a book
of my own. Get Programming with JavaScript is my attempt at translating my approach to
teaching programming into book form. It’s packed with code listings to get you think-
ing about the concepts as you progress, and there are plenty of exercises and supple-
mentary materials online, as detailed shortly. I hope it fires your imagination and gets
you started on your own programming adventures. Good luck, and have fun!
acknowledgments
Thank you to Robin de Jongh at Manning for suggesting I write a book and to my edi-
tor Helen Stergius for her patience, advice, and support throughout the writing pro-
cess. Thanks also to all of the people who reviewed the book and provided excellent
feedback to make it better, including Philip Arny, Dr. Markus Beckmann, Rocio
Chongtay, Sonya Corcoran, Philip Cusack, Alvin Raj, Conor Redmond, Ivan Rubelj,
Craig Sharkie, and Giselle Stidston; in particular, thanks to Ozren Harlovic, Chuck
Henderson, Al Sherer, Brian Hanafee, and Romin Irani for their attention to detail,
honest reactions, and constructive suggestions.
I’d also like to thank Remy Sharp, the creator of JS Bin, for responding to my ques-
tions and requests quickly and positively, for being kind enough to agree to write the
foreword for this book, and for creating JS Bin!
Finally, I want to thank the people at Manning who made this book possible: pub-
lisher Marjan Bace and everyone on the editorial and production teams, including
Janet Vail, Mary Piergies, Tiffany Taylor, Linda Recktenwald, Dennis Dalinnik, Elizabeth
Martin, Bonnie Culverhouse, and many others who worked behind the scenes.

xxi
about this book
Get Programming with JavaScript is a book for beginners, for those with no programming
experience. It makes extensive use of online code listings on the JS Bin website, a
sandbox where you can experiment with the code and see the results instantly. There’s
no setup or installation required; if you’ve got internet access, you can just get pro-
gramming straight away. If you don’t have internet access, don’t worry, the printed list-
ings include helpful annotations, and all the ideas are explained in the text.
In addition to shorter examples to illustrate the concepts covered, there is an
ongoing example—a text-based adventure game called The Crypt—that you build as
you progress through the book.

Who should read this book


If you are happy working with computers, using a variety of applications, and saving
and organizing your files but haven’t written programs before and would like to learn
how, then this book is for you. It doesn’t try to cover all of JavaScript, or even all parts
of JavaScript; it helps you to get programming with lots of practical examples and
exercises that encourage you to think and explore. If you’re already a programmer
and are looking for a complete JavaScript reference, then move along. But if you
want a patient introduction to the language, then it’s worth sticking around; a strong
understanding of the basics will make it much easier to access some of the other excel-
lent books for programmers.

xxii
ABOUT THIS BOOK xxiii

Roadmap
Get Programming with JavaScript has 21 printed chapters; an additional four chapters
are available online only from the publisher's website at www.manning.com/books/
get-programming-with-javascript. The book makes extensive use of code listings and
exercises, with successive examples building on previous work. I recommend you read
it in order, trying out the examples and exercises online and taking time to under-
stand the ideas presented.
Part 1 covers some of the core concepts of programming with JavaScript. It sticks
to using the text-based Console panel on JS Bin, letting you focus on the JavaScript
and not worry about web pages and HTML:
■ Chapter 1 looks at programming and programming with JavaScript in particular
before introducing JS Bin, a website where you can get programming right away,
and The Crypt, a text-based adventure game that you build as you progress
through the book.
■ Chapter 2 describes variables, a way of labeling and using values in your pro-
grams. Your variables can hold different types of values, like numbers or text,
but their names must follow certain rules.
■ In chapter 3 you learn how to group values into objects. Just like a first-aid kit can
be passed around as a single object and its contents accessed only when needed,
JavaScript objects can be treated as a single item and their properties accessed
when required.
■ Functions are central to JavaScript, helping you to organize your code and exe-
cute sets of instructions on-demand and multiple times. They are introduced
over four chapters, chapters 4 to 7, so that you get a firm grasp of how to define
them and use them, how to pass data to them and from them, and how they
work beautifully with objects.
■ Chapter 8 shows you how to create ordered lists, or arrays, of values. Whether
they hold blog posts, calendar events, users, functions, or movie reviews, lists
are very common in programming, and you learn how to create them and
access, manipulate, and remove their items.
■ Objects are at the heart of JavaScript, and programs often create many objects;
a calendar could have thousands of events and an adventure game dozens of
locations, for example. Constructor functions are a way of streamlining the cre-
ation of many similar objects, and chapter 9 investigates why they’re useful and
how you define them and use them.
■ In chapter 10 you meet square bracket notation, an alternate method of access-
ing the values stored in JavaScript objects. Armed with this more flexible way
of getting and setting object properties, you write some example programs
that can cope with unpredictable values that may appear in external data or
user input.
Random documents with unrelated
content Scribd suggests to you:
LETTER MCCCLXXX.
To Lady S―― S――.

Bath, December 9, 1767.

Honoured Madam,

A LL hath been awful, and more than awful. On Saturday evening,


before the corpse was taken from B――n-House, a word of
exhortation was given, and a hymn sung in the room where the
corpse lay. The young Earl stood with his hands on the head of the
coffin, the Countess Dowager on his right hand, Lady Ann and Lady
Isabella on his left, and their brother Thomas next to their mother,
with Miss O――n, Miss Wh――r, Miss G――e; on one side all
domestics, with a few friends on the other. The word of exhortation
was received with great solemnity, and most wept under the parting
prayer. At ten the corpse was removed to good Lady H――n’s
chapel, where it was deposited within a place railed in for that
purpose, covered with black bays, and the usual funeral
concomitants, except escutcheons. On Sunday morning, all attended
in mourning at early sacrament. They were seated by themselves, at
the feet of the corpse, and with their head servants, received first,
and a particular address was made to them. Immediately after
receiving, these verses were sung for them:
Our lives, our blood, we here present,

If for thy truths they may be spent:

Fulfil thy sovereign counsel, Lord;

Thy will be done, thy name ador’d.

Give them thy strength, O God of power,

Then let men rave or devils roar;

Thy faithful witnesses they’ll be;

’Tis fix’d, they can do all through Thee.

Then they received this blessing, “The Lord bless you and keep you,
the Lord lift up the light of his countenance upon you, the Lord
cause his face to shine upon you, and give you peace,” and so
returned to their places. Sacrament ended (and a blessed sacrament
it was) the Noble Mourners returned to good Lady H――n’s house,
which was lent them for the day. At eleven, public service begun.
The bereaved relations sat in order within, and the domestics around
the outside of the rail. The chapel was more than crouded. Near
three hundred tickets signed by the present Earl, were given out to
the nobility and gentry, to be admitted. All was hush’d and solemn.
Proper hymns were sung, and I preached on these words, “I heard a
voice from heaven, saying unto me, write, blessed are the dead that
die in the Lord.” Attention sat on every face, and deep and almost
universal impressions were made. The like scene, and if possible
more solemn, was exhibited in the evening, and I was enabled to
preach a second time, and a like power attended the word as in the
morning. Ever since, there hath been public service and preaching
twice a day. This is to be continued till Friday morning, then all is to
be removed to Bristol, in order to be shipped off for Scotland. The
inscription on the coffin runs thus;
“His life was honourable,—his death blessed,—he sought
earnestly peace with God,—he found it with unspeakable joy alone in
the merits of Christ Jesus, witnessed by the holy Spirit to his soul,—
he yet speaketh.—Go thou and do likewise.”

I have oftened wished for your Ladyship here. Congregations are


very large, attentive, and deeply impressed. Surely the death of this
noble Earl, thus improved, will prove the life of many. He had great
foretastes of heaven, cried, “Come Holy Ghost;” he came, and filled
him with joy unspeakable. Happy, happy, were his last dying words.
All surviving relatives still feel the influence. They sit round the
corpse attended by their domestics and supporters twice a day.
Good Lady S――x gets fresh spirits. She loves your Ladyship dearly.
I am called to attend, and therefore must hasten to acknowledge
innumerable obligations, and to subscribe myself, honoured Madam,

Your Ladyship’s, &c. &c. &c.

G. W.

LETTER MCCCLXXXI.
Bristol, December 12, 1767.

My dear Captain,

I HOPE this will find you rejoicing with trembling, on account of an


additional careful comfort. Thus it must be in this mixed state of
things. Yet a little while, and our joy will be permanent,
uninterrupted, and without alloy. For five days together we have
been attending at the house of mourning. Many, I trust, were
obliged to say, “How dreadful is this place.” Such a like scene, I
never expect to see opened again on this side eternity. All is quiet, I
trust, with you. But if diamond hath been cutting diamond, it will
only be suitable to a church militant here on earth. Blessed be God
for an almighty Jesus! who can by these mutual cuttings prepare the
jewels for their respective places in the intended crown. Ere long he
will count them up. Not one shall be wanting. Cordial love to all. I
purpose being in town Tuesday se’nnight in the evening. Brethren,
pray for us. I shall make all easy at Kingswood before I leave Bristol.
That you may shine with distinguished lustre above, earnestly prays,
my dear Captain,

Yours, &c. &c. in our Emmanuel,

G. W.

LETTER MCCCLXXXII.
To Mr. R―― K――n.

Bristol, December 16, 1767.

My dear Friend,

W E have been favoured with golden seasons here. I have been


enabled to preach thrice, and to administer the holy
sacrament. Thousands went away on Sunday, because they could
not come in. The word hath been attended with great power. Grace!
grace! What a pity that we cannot stay a week or two longer! But I
must away to Bath to preach to-morrow, and the next Lord’s-day.
Shall write, God willing, to Mr. S――s by Saturday’s post, to tell Rose
where to meet me with the chaise. We come in the two days post-
coach. Mr. A――s is come hither to see me. I thought to have
brought him up with me, but the coach was full. Is it true, that Mr.
J――ss hath two careful comforts at once? I wish him much joy. Pray
tell my wife, that I intend doing myself the pleasure of dining at
Tabernacle-house next Wednesday. Ere long we shall sit down and
eat bread in the kingdom of heaven. Hallelujah! hallelujah! Come,
Lord, come. Hearty love to all. Continue to pray for, my dear friend,

Yours and dear Mr. H――y’s, &c. &c.

G. W.

LETTER MCCCLXXXIII.
To the Reverend Mr. G――.

London, December 28, 1767.

Reverend and dear Sir,

W HY do you and I exchange letters so seldom? Perhaps it would


be better to correspond more frequently. This brings you the
good news of the triumphant death of the late Earl of B――n. He
behaved like the patriarch Jacob, when by faith leaning upon his
staff, he blessed his children. The Earl added, “Yea, and they shall be
blessed.” “Had I strength of body, (cried the Earl) I would not be
ashamed before men and angels to tell what the Lord Jesus hath
done for my soul. Come, holy Ghost, come, holy Ghost; happy,
happy, happy!” and then sweetly slept in Jesus. The present noble
Earl, I believe, hath got the blessing indeed, and seems, upon the
best evidence, to determine to know nothing but Jesus Christ, and
him crucified. He hath behaved in the most delicate manner to the
Countess, and other noble survivors. He stands here in town, against
all opposition, like an impregnable rock; and I humbly hope will
prove the Daniel of the age. He must be, nay he hath been already
thrown into a den of lions; but he hath one with him, that stops the
lions mouths. You will encourage all God’s people to pray for him.
What if you wrote him a line? I am sure it will be taken kindly; for I
know he honours and loves you much. You will communicate this to
dear Mr. M――ch, who, I suppose, like me, is groaning, being
burdened. I am now fifty-three years old. Did you ever hear of such
a fifty-three years old barren fig-tree? So much digging, so much
dunging, and yet so little fruit. God be merciful to me a sinner! A
sinner—a sinner—a sinner. He is merciful; he is gracious: his mercy
endureth for ever. He yet vouchsafes to bless my feeble labours. You
would have been delighted to have seen the awful scene exhibited
at Bath, whilst the late noble Earl lay in state. Two sermons every
day; life and power attended the word; and I verily believe many
dead souls were made to hear the voice of the Son of God. Since
that we have been favoured with comfortable seasons in town. I
hope you are blessed in Glasgow. Who knows but we may have one
more interview in Spring? Whether we meet next on earth or in
heaven, you will find that with great sincerity I subscribe myself,
reverend and very dear Sir,

Yours, &c. &c. &c. in our glorious Jesus,

G. W.

LETTER MCCCLXXXIV.
To Mr. W――b.

London, February 4, 1768.

My dear Sir,

W HO would but converse when together, like persons that may


never meet again till launched into an endless eternity. I hope
this was in some measure our case, when we dined lately at Mr.
H――t’s. One of the company, I find, is gone, and I trust to eat
bread in the kingdom of heaven.

She is happy now, and we

Soon her happiness shall see.

In the midst of all your sorrow for the loss of so near and dear a
relation, methinks such a consideration may make you cry out,
Hallelujah! Amen! Come, Lord Jesus, come quickly. Blessed be God,
our turn will come by and by. Be ye also ready, is the loud call of the
present afflictive providence. That it may be duly heard, and
practically applied, is the hearty prayer of

Your sympathizing friend, and servant in our common Lord,

G. W.

LETTER MCCCLXXXV.
To Mr. D――n.

London, April 6, 1768.

My very dear Friends,

I F you choose it, you may now be released; but the aspect of
affairs at home, is by no means promising. Many, many think of
going abroad. However, you will be so kind as to see the bearers of
this settled before you remove. Mr. C――ne, a worthy disinterested
creature, is to be steward of the house: he is a particular heart-
friend of Mr. W――t’s. Mr. W――t’s sister is an approved
housekeeper, and the little female orphans are to be committed to
her care. Mr. L――y hath had an university education, is a good
writer and accomptant, hath been with me some time, and is to be a
school-master. I long to know how poor Peter and Ephraim go on,
and likewise his sister at Savannah. I and Mr. W――t hope to follow
soon. But future things belong to Him who orders all things well. I
believe; Lord, help my unbelief. His work prospers. That is all in all.
Be pleased to have all accounts settled and audited, and take what
you please for your passage, if determined to return. But—but—God
keep you, through too fond affection, from taking a false step! My
heart is full. If you come away, and Mr. S――k also goes away, I
would have a letter of attorney given to Mr. C――ne. But it would be
well if I could hear from you first. God direct and bless you all. I can
only commend you to God and the word of his grace, and with ten
thousand thanks for all your labours of love, subscribe myself, very
dear friends,

Yours, &c. &c. &c. in our glorious Jesus,

G. W.

LETTER MCCCLXXXVI.
To Mr. J――ss.

London, May 17, 1768.

My dear Man,

G O forward, go forward, is the watch-word of the present day.


Never mind the envious cry of elder brethren. Had they been
harkened to, the prodigal must never have come home, nor Goliah’s
head have been cut off. All temple builders, especially when called
out to work in the field, must endure not only the contradictions of
sinners, but the contradiction of saints also. Happy are they who are
so deeply engaged in building, as not to have time to hearken to
either. I long to come and lend an helping, though feeble hand. But
Welch horses move slowly. If the Welch apostle comes, I purpose, in
the Whitsun week, to make a short excursion into Sussex and Kent,
and then for Bristol. Blessed be God, the shout of a king is heard in
our camps! All your family is well. All will be more than well, when
we come to our house in heaven. Let us march forward with palms
of victory in our hands, crying, “Hallelujah! the Lord God omnipotent
reigneth!” Tender love to all. I hope to answer Mrs. R――s person.
The Lord Jesus be with your spirits! Cease not to pray for, my dear
man,

Less than the least of all,

G. W.

LETTER MCCCLXXXVII.
To Mr. R―― K――n.

Edinburgh, June 15, 1768.

My dear Mr. K――n,

I HOPE this will find you and yours safe returned to London. I am
glad to hear by dear Mr. H――, that you left your daughter
better: may she be spared, not in judgment, but in mercy! Then all
will be well: nay, at all events, you may be assured all shall work for
good, because you love God. Glorious assurance this! Thanks be to
God for this unspeakable gift. Thanks be to his great name, for
ordering my steps this way. You would be delighted to see our
Orphan-house park assemblies; as large, attentive, and affectionate
as ever. Twenty-seven year old friends and spiritual children,
remember the days of old; they are seeking after their first love, and
there seems to be a stirring among the dry bones. I cannot yet tell
when I shall move. Probably within this fortnight. I must away to my
throne. Love to all at Tabernacle, and to all that are so kind as to
enquire after,

Less than the least of all,

G. W.

LETTER MCCCLXXXVIII.
To Mr. A―― K――n.

Edinburgh, July 2, 1768.

My dear Timothy,

I AM much obliged to you for staying at London, till I return from


Scotland. My journey hither was certainly of God. Could I preach
ten times a day, thousands and thousands would attend. I have
been confined for a few days, but on Monday or Tuesday next hope
to mount my throne again. O to die there! Too great, too great an
honour to be expected. My wife will see my letter to Mr. S――ks. I
thank her for her kind letter just received. Pray tell Mr. K――n that
no Indian money will be remitted to the London trust from hence.
The interest of what is collected, which is near two thousand
pounds, is to be sent, as occasion requires, to Mr. Wheelock and the
Connecticut trust. Be pleased to send to Mr. Dilly, and desire him to
forward by the first ship, fifty of my letters to the Archbishop,
directed to Mr. Herdie at the custom-house, Leith. I am here only in
danger of being hugged to death. Friends of all ranks seem heartier
and more friendly than ever. All is of grace. Grace! grace! I thought
to write you a long letter: but company forbids. I go on in my old
way, without turning to the right hand or to the left. Providence says
every day, “This is the way, walk in it.” Tender love to all, particularly
to my dear wife. Next post she may expect to hear from,

Less than the least of all,

G. W.

LETTER MCCCLXXXIX.
To the Reverend Mr. T――.

Edinburgh, July 4, 1768.

My dear Friend,

W HAT various interruptions do we meet with in this lower world!


Sickness, preaching, and company, have prevented my
answering your kind letter more speedily. I strive to stir and fly as
formerly; but the earthly house of this tabernacle pulls me down.

Strange, that a harp of thousand strings,

Should keep in tune so long!

However, this is my comfort, the Redeemer still vouchsafes to smile


upon my feeble efforts. In London the word runs and is glorified,
and in Edinburgh, I trust, the prospect is promising. The fields are
white ready unto harvest. Who knows but some wheat may be
gathered into the heavenly garner? Many of my old friends are safely
housed.

They are happy now, and we

Soon their happiness shall see.

Hallelujah!

Perhaps we may have one interview. I have thoughts of going to


M――. A week or a fortnight, at most, is the longest time I can stay
here. I desire to move, till I can move no more. O to die in the field!
I pray God to send Mrs. T―― a safe delivery. My wife is as well as
can be expected. Both descending in order to ascend

Where sin and pain and sorrow cease,

And all is calm and joy and peace.

I add one more hallelujah; and must hasten to subscribe myself, my


dear friend,

Less than the least of all,

G. W.

LETTER MCCCXC.
To Mr. R―― K――n.

Edinburgh, July 9, 1768.

My very dear Friend,


G OD be praised that all is so well at London. Every thing goes on
better and better here. But I am so worn down by preaching
abroad, and by talking at home almost all the day long, that I have
determined, God willing, to set off for London next Tuesday noon. I
shall mind all you say. You have acted quite right. As you do not
mention my wife, I suppose she is out of town. God prepare you and
yours for whatever he hath prepared for you, and support you under
your present and impending trial. Company prevents my enlarging.
Thus it is continually. Grace! grace! Hoping to see you soon, with
tender love to all, I beg leave to subscribe myself, my dear friend,

Ever yours, &c. &c. &c.

G. W.

LETTER MCCCXCI.
To Mr. J――ss.

London, August 16, 1768.

Dear Mr. J――ss,

B LESSED be the God and Father of our Lord Jesus Christ, who hath
so mercifully preserved you in your going out and coming in,
and caused you to triumph in every place! You may continue your
gospel range, till Mr. E――ds leaves London; then we must think of
Winter quarters. Let us work whilst it is day. The late very
unexpected breach, is a fresh proof that the night soon cometh
when no man can work ¹. Pray where may I find that grand promise
made to Abraham after Sarah’s death? May it be fulfilled in you,
whilst your Sarah is yet alive! Sweet bereavements, when God
himself fills up the chasm! Through mercy I find it so. Adieu. Tender
love to all. Brethren, pray for us. I suppose I must direct to brother
Adams at Rodborough. He expects you there. That you may be
owned in every place more and more, heartily prays, my dear man,

Yours, &c. &c. in our Jesus,

G. W.

¹ Mr. Whitefield’s wife died August 9th.

LETTER MCCCXCII.
To Mr. R―― K――n.

Trevekka, August 26, 1768.

My dear Friend,

I HAVE had the return of my old disorder; but blessed be God, I am


strengthened to preach the unsearchable riches of Jesus Christ.
We reached Gloucester on Monday, and came hither on Wednesday
afternoon. All we have met with exceeds description. Early next
Monday I purpose to set off for Bristol, and soon after shall return to
London. Brethren, pray for us. I believe you do; for God is with us of
a truth. I hope you and yours are supported. The Redeemer is a
present help in every time of need. Cordial respects await all that
love him in sincerity. Mr. L――d and a Londonner left us to-day. I
hope Mr. P――d and B――s make all possible dispatch. God send
dear Mr. H――y a good passage and safe return! Amen! Amen! Lord,
quicken my tardy pace!

Ever yours, &c. in Jesus,


G. W.

LETTER MCCCXCIII.
To the Same.

Bristol, August 30, 1768.

My very dear Friend,

W HAT we have seen and felt at the college is unspeakable.


Through mercy last night we came hither. My disorder has
returned. This may hasten me up: or rather hasten me to heaven. I
hope your daughter will have it revealed in her before she goes
hence. That is all in all. Is there any thing too hard for the Lord?

Surely, O God, thy grace is free,

For, O my God, it found out me!

In a day’s time my rout may be determined. P――d, &c. must make


haste. Captain J――ss comes up at the appointed time. Hearty love
awaits dear Mr. E――s, &c. &c. &c. Cease not to pray for, my very
dear friend,

Yours, &c. &c. in Jesus,

G. W.

P. S. Since writing the above I received yours. I find the


threatened blow is given. I hope both are enabled to say, “The Lord
hath given, and the Lord hath taken away: and blessed be the name
of the Lord.” Be pleased to send what letters you have for me, and
accept these few lines of condolance from, my dear Sir,

Yours, &c. &c. in an all-compassionate Jesus,

G. W.

LETTER MCCCXCIV.
To Mr. D――n.

London, September 1, 1768.

My very dear Mr. D――n,

I WAS exceeding glad to find, by your last kind favour, that you and
Mrs. D――n thought of deferring your embarkation for England
till the Spring. You will then see the newcomers quite settled, and I
wish I could add, see also your reasons for leaving Bethesda but of
little weight. I know your mind. Would to God your dear yoke-fellow
was like-minded. She will certainly be so very soon after her arrival
in her native country: but I would not grieve her. God bless you
both! Brownhill’s situation I much approve of. Poor Peter often
engages my thoughts. It pleases me to find that he goes on well;
but I want to have him settled. If not likely to make a scholar, or be
in some good station in the house, I wish he was put out to some
proper business. Not one prize as yet among all the young relations
I have endeavoured to provide for. Father, not my but thy sovereign
will be done! I wish you could enquire what is become of ――, sent
over with Mr. Wooldridge, Provost-Marshall at Augustine. You may
guess that I long to see the accompts. I doubt not of their being
quite compleat. Could you not send me a duplicate before your
intended embarkation, it would be very acceptable for many
reasons. All your dear relations on this side the water are well. My
nearest relation hath been quite well above a month. Mr. Middleton
hath soon followed after. His wife died a few weeks before him.

They are happy now, and we

Soon their happiness shall see.

Hallelujah! Hallelujah! Come, Lord, come! Praying still that, if it be


the divine will, you may be constrained to abide at Bethesda, I
subscribe myself, dear and faithful friends,

Yours, &c. &c. &c.

G. W.

LETTER MCCCXCV.
To Mr. S―― S――.

London, September 6, 1768.

My very dear Friend,

W HY should not one invalid write to another? What if we should


meet in our way to heaven unembodied, and consequently
freed from every thing that at present weighs down our precious and
immortal souls? But perhaps we are yet to sojourn a little longer on
earth. For these two days past, I have been unable almost to write.
To-day I am what they call better, and must improve my first
strength in sending a few lines to him whom I dearly love in the
bowels of Jesus Christ. May they find you and your dear partner
leaning on his bosom, who alone is able to bring out of every
wilderness. Neither are forgotten before his throne. Though absent
in body, I am present in spirit. Accept of love and sympathy
unfeigned. I am persuaded you are not unmindful of, very dear
friend,

Less than the least of all,

G. W.

LETTER MCCCXCVI.
To Mr. R―― K――n.

London, September 19, 1768.

My dear Sir,

I APPROVE very much of Mr. Brooksbank’s motion, especially as


dear Mr. Middleton is gone. His burying is fixed for Wednesday
evening. Would you choose (with some other friends to whom I shall
write) to condescend to be a pallbearer. The conference to follow the
children as mourners. The children to be sent for in my carriage, and
sit with the pall bearers in my parlour. All to be invited that have a
mind to follow in mourning. The corpse to be brought privately to
Tabernacle on Tuesday night. I must away, for fear of the evening
air. I should be glad to see you at Tottenham-Court to-morrow
afternoon. By that time, I shall know Dr. C――r’s answer to Mr.
Middleton’s daughter’s letter. By which we shall judge the better how
to act, in regard to opening the intended subscription for the benefit
of his fatherless children. Blessed be God, I am better, but am
ordered to decline preaching. God’s will be done! Pray let Mrs.
K――n make free at Tabernacle-house as usual. God bless you both!
God give me patience to wait till my change comes! I am, my dear
friend,

Yours most affectionately in our glorious Emmanuel,

G. W.
LETTER MCCCXCVII.
To Mr. S―― S――.

London, September 26, 1768.

My very dear Friend,

B LESSED be God for the art of writing! blessed be God for skill to
read and understand what is written! Thus we understand each
other, though at a thousand miles distance; thus I understand, and
by understanding learn to sympathize with my dear fellow-sufferer
Mr. S――. This is my comfort, that underneath him are the almighty
Redeemer’s everlasting arms. Therefore, being the beloved of the
Lord, he must dwell in safety. Though prevented by the weather
from using or drinking the Ramsgate waters, nothing can prevent his
using or drinking the waters of life freely. No, no: in every true
believer’s heart the Holy Ghost is a well of water springing up to life
eternal. Hence it is, that though he killeth, he maketh alive; though
he wounds, yet he heals. These words I was enabled to feel and
enlarge upon yesterday morning from my Tottenham-Court throne.
For some days the flux of blood hath stopped entirely. Praise the
Lord, O my soul! Lord Jesus, if it be thy blessed will, let me hear of
the recovery of my dear friend! Most cordial respects attend dear
Mrs. S――. God bless, support, and comfort her under her present
circumstances. Mr. Middleton is now made perfectly whole. He was
buried from the Tabernacle last Wednesday evening, and a
subscription is opened for his four orphans. In the midst of his
torturing pains, being asked by his daughter how he was, he
answered, “A heaven upon earth.” Soon afterwards he fell asleep in
Jesus. In Him I am, my very dear dear Sir,
Yours, yours, &c. &c. in our never-failing Jesus,

G. W.

LETTER MCCCXCVIII.
To Mr. R―― K――n.

Bristol, November 12, 1768.

My dear Mr. K――n,

T HROUGH infinite mercy we arrived here in due season. Last night


I hope the Redeemer manifested forth his glory. God willing, I
stay till next Thursday or Friday morning. Friday evening, and the
following Sunday, I shall preach at Bath. In three weeks expect to
reach London, except called before that period to reside at the New-
Jerusalem. The pleasing prospect lies day and night open before me.
On Monday, I suppose, dear Mr. H――y sets out for Bath. All proper
enquiry hath been made about his house. Particulars he will be
acquainted with on his arrival. Pray for me. Bethesda lies upon my
heart night and day. Something must be determined speedily. As I
trust my eye is single, God will assuredly direct my goings in his way.
Hitherto he hath helped: he will do so to the end. Hallelujah!
Hallelujah! God bless you and yours! Wonted cordial christian
salutations to all, who are so kind as to be concerned for, and
enquire after, my dear steady friend,

Less than the least of all,

G. W.
LETTER MCCCXCIX.
To Mr. A――s.

London, November 30, 1768.

My very dear Tommy,

T EN thousand thanks for your kind sympathy. Many thought I


should not hold out from Bath to London. But I cannot as yet
go to him whom, I trust, my soul loveth. Last Sunday I creeped up
to my gospel throne: this evening the same honour is to be
conferred upon me. Why me, Lord? why me? The prayers of God’s
people detain me here: for what end, the event only can discover. To
be tried, we may be assured. Mr. W――t is going with his brothers to
Georgia, in order to finish the wings of the intended college, and
repair the present buildings. I suppose they will sail in about a
fortnight. You will pray that Abraham’s God may be my God and my
guide unto death. He will, he will.

I would believe thy promise, Lord;

Lord, help my unbelief.

Cordial, most cordial respects await your whole self, and all who are
so kind as to enquire after, my very dear Tommy,

Less than the least of all,

G. W.
LETTER MCCCC.
To W―― P――, Esq.

London, December 14, 1768.

H OW unexpected a letter! what a kind present! Both came safe to


hand; both call for most grateful acknowledgments. My poor
prayers shall follow them: may they enter into the ears of the Lord
of Sabaoth! They will, they will. He is a God hearing prayer. You and
yours know it; otherwise how would you have been translated from
darkness to light! Marvellous, soul-transforming light! This, I trust,
you prove by daily experience, passing from glory to glory by the
Spirit of the Lord. Hence you increase in boldness; hence your
readiness to follow the Lamb whithersoever he goeth, though it
should be without the camp. Blessed be his name, for this honour
conferred upon ill and hell-deserving me. This may make dear Mr.
S――t easy, should I ever be called to Shropshire. I love the open
bracing air. Preaching within doors is apt to make us nervous,
especially to crouded auditories. These, I hope, he is blessed with.
God make him a successful fisher of men! I hope he and his are
enabled to walk in all the ordinances and commandments of the
Lord blameless. Blessed saving fruits of a living faith! blessed proofs
of having our past sins forgiven! As for those to come, I dare not to
mention their being forgiven, till committed. Moderate Calvinism I
take to be a medium between two extremes. I should not choose to
use expressions that need an apology. This seems to be a blemish in
Dr. Caisp, and other supralapsarian writers. A word to the wise is
enough. You will excuse this freedom, because it proceeds from love
unfeigned in, dear friend,

Less than the least of all,

G. W.
LETTER MCCCCI.
London, December 15, 1768.

My dear Friend,

Y OU will see the contents of my letter to Dr. E――e. I have


considered the affair of the picture. What think you? A limner
who lately drew me, and hung the picture up in the exhibition, asks
forty guineas for a copy. I shall not mind him, but send a bust taken
several years ago. It shall be paid for here, and presented as a token
of my hearty, hearty love to the Orphan-house at Edinburgh, and its
never-to-be-forgotten friends. Nothing but my disorder of body, God
willing, shall prevent my engagement in the plains of Philippi: But, I
fear, that will be an obstruction to so long a journey. You cannot tell
how low my late excursion only to Bristol and Bath brought me. But
I serve a God who killeth and maketh alive. I would leave future
events to Him, and like you merchants improve the present Now:
time is short; eternity is endless. The Judge hath sent this awful
message, “Behold, I come quickly.” That we all may be ready to go
forth to meet him, earnestly prays, my dear friend,

Less than the least of all,

G. W.

LETTER MCCCCII.
To Mr. T―― A――ms.

London, December 29, 1768.


My very dear Tommy,

M ANY thanks for your kind sympathetic congratulatory letter. Mr.


Wright is gone, or rather lies yet in the Downs. He is gone to
build for Him, who shed his precious heart’s-blood for ill and hell-
deserving me. Whether the unworthy Founder lives or dies,
Bethesda affair, I trust, will now be compleated. Strange, that I am
now living! Fifty-four years old last Tuesday. God be merciful to me a
sinner! a sinner! a sinner! Less than the least of all, must be my
motto still. As such, continue to pray for me. That you and yours,
and all the elect people of God around you, may increase with all the
increase of God, continually prays, my very dear Tommy,

Ever yours, &c. &c. in our Jesus,

G. W.

LETTER MCCCCIII.
London, January 13, 1769.

My dear Sir,

W ITH regret I send the inclosed; but alas! they were borrowed.
May the prayers put up for the writers, enter into the ears of
the Lord of Sabaoth. They will, they will. And what then? What then?
Why, they will turn out good soldiers of Jesus Christ. That this may
be their happy lot, earnestly prays,

Less than the least of all,

G. W.
LETTER MCCCCIV.
To Mr. C―― H――y.

London, February 4, 1769.

My dear Sir,

I HOPE this will find you safe arrived at Bath, in your way to
London. I thank God that matters have turned out no worse at
Plymouth. I see more and more every day, that things and persons
are only what an all-wise, almighty Jesus is pleased to make them.
Happy, happy they that have their all in Him, who is indeed our All in
All! This, I believe, is your happy lot. Grace! grace! This may teach
us to look to Jesus in all our concerns and motions. What his will may
be concerning my voyage to Georgia, I know not. At present the
cloud doth not move that way. But you may be assured, it never
entered my heart to think of embarking without settling the minutest
matter to mutual satisfaction. But more of this when we meet. Lord,
hasten our glorious meeting in the kingdom of heaven.

There sin and strife and sorrow cease,

And all is calm and joy and peace.

I hope all is well in Green-street. Hearty love to all. All here send
greeting. A good time at Mercer’s chapel. Grace! grace! I know you
will join in saying Amen, with, my dear Sir,

Less than the least of all,

G. W.
LETTER MCCCCV.
To Mr. S――e.

London, February 27, 1769.

My dear Mr. S――e,

N OT want of love, but of leisure, hath prevented my making


proper acknowledgments for your kind letter, and late
publication. I think it is well written; and I earnestly pray, that it may
be blessed to many. One passage seems exceptionable, where you
say, “That all believers were originally endowed with the
extraordinary gifts of the Holy Ghost.” The instances urged to prove
it, seem quite deficient. This is not written to find fault, but to
prevent fault finding. That you may be much owned in every thing
you undertake, and, with all the Christian Sheerness brethren,
increase with all the increase of God, is the hearty prayer of,

Less than the least of all,

G. W.

P. S. Blessed be God, the shout of the King of kings is yet to be


heard amongst us. Grace! grace!

LETTER MCCCCVI.
To Mr. A――s.

London, March 11, 1769.


My very dear Tommy,

Y OUR consciousness of my settled friendship, will not permit you


to interpret my silence to a want of love. How great that is, and
on what a solid basis it is founded, the great day will discover.
Through infinite mercy, I am enabled to preach thrice a week,
besides other occasional exercises; and indeed (O amazing
condescension!) the shout of the King of kings is amongst us. After
Easter, I hope to make an elopement to Gloucestershire, and some
western parts. Could you, upon the receipt of this, go to Bristol? Mr.
B――s must come immediately to London. I feel the loss of my right
hand daily; but right hands and right eyes must be parted with for
Him, who ordereth all things well.

I would believe thy promise, Lord;

O help my unbelief!

Leaving you to add a heart-felt Amen, I am, my very dear Tommy,

Less than the least of all,

G. W.

LETTER MCCCCVII.
To Mr. and Mrs. D――.

London, March 17, 1769.

My dear Friends,
I HOPE this will find you not only at, but fixed at Bethesda. Your
brother James yesterday told me, “He thought it best.” It is not a
time to think of leaving a happy wilderness now. There’s more noise
in great cities. I am every day, every hour, almost every moment,
thinking of and preparing for America. A pilgrim life to me is the
sweetest on this side eternity. I am daily expecting Bethesda
accompts. I am daily waiting for the kingdom of God. God bless my
poor negroes. I am always, my dear friends,

Yours, &c. &c. in the Friend of all,

G. W.

LETTER MCCCCVIII.
To Mr. A――s.

London, March 31, 1769.

My very dear Tommy,

Y OU will be glad to hear, that frequent preaching hath prevented


writing. Through infinite mercy I have been enabled to preach
four days successively. And indeed we have been favoured with a
blessed passover season. All to make us shout louder and louder,
Grace! grace! I have some thoughts of making Gloucestershire my
first excursion: but at present the cloud abides over London. Lord
Jesus, direct my goings in thy way! The books will be sent. Mr. S――e
hath done as desired: I believe he goes to Bath next week. B――’s
coming was, I think, of God. She seems happy in her present
situation. In heaven we shall be perfectly so. Till then, some right
hand or eye must be cutting off, and plucking out, and we shall feel
the smart and want of both. But all is well, because all will end well.
Hallelujah! Hallelujah! Come, Lord, come! I can now no more. Adieu.
God bless you all! Cease not to pray, my very dear Tommy, for

Less than the least of all,

G. W.

LETTER MCCCCIX.
To the Reverend Mr. S――y.

London, April 1, 1769.

Reverend and very dear Sir,

H OW much am I obliged to you, for your two kind letters, and


more especially for the repeated offers of your ministerial
assistance. They will be most gratefully accepted, and I humbly hope
remarkably succeeded, by Him who hath promised to be with us
always even to the end of the world. Blessed be his name, we have
been favoured with delightful passover feasts. The shout of the King
of kings is still heard in the midst of our Methodist camps; and the
shout of Grace, grace! resounds from many quarters. Our almighty
Jesus knows how to build his temple in troublous times. His work
prospers in the hands of the elect Countess, who is now gone to
Bath, much recovered from her late indisposition. Worthy Lady
F――y proposes soon to follow, in order to reside there. Some more
coronets, I hear, are likely to be laid at the Redeemer’s feet. They
glitter gloriously when set in, and surrounded with a crown of
thorns.

You might also like