100% found this document useful (2 votes)
198 views

Eloquent JavaScript 4th Edition Marijn Haverbekedownload

The document provides information about the 4th edition of 'Eloquent JavaScript' by Marijn Haverbeke, including links for downloading the book and other related JavaScript resources. It also mentions the licensing details and contributions from various artists. Additionally, it outlines the book's contents, covering topics such as programming fundamentals, functions, and data structures.

Uploaded by

bildikstaisy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
198 views

Eloquent JavaScript 4th Edition Marijn Haverbekedownload

The document provides information about the 4th edition of 'Eloquent JavaScript' by Marijn Haverbeke, including links for downloading the book and other related JavaScript resources. It also mentions the licensing details and contributions from various artists. Additionally, it outlines the book's contents, covering topics such as programming fundamentals, functions, and data structures.

Uploaded by

bildikstaisy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Eloquent JavaScript 4th Edition Marijn Haverbeke

pdf download

https://ebookmass.com/product/eloquent-javascript-4th-edition-
marijn-haverbeke/

Explore and download more ebooks at ebookmass.com


We have selected some products that you may be interested in
Click the link to download now or visit ebookmass.com
for more options!.

JavaScript T. J. Crowder

https://ebookmass.com/product/javascript-t-j-crowder/

Javascript: Crash Course - The Complete Beginners Guide To


Learning JavaScript Programming In No Time! (Angularjs,
jQuery, JavaScript Visually) Nathaniel Hill
https://ebookmass.com/product/javascript-crash-course-the-complete-
beginners-guide-to-learning-javascript-programming-in-no-time-
angularjs-jquery-javascript-visually-nathaniel-hill/

JavaScript: A Beginner's Guide, Fifth Edition Pollock

https://ebookmass.com/product/javascript-a-beginners-guide-fifth-
edition-pollock/

How JavaScript Works: Master the Basics of JavaScript and


Modern Web App Development 1st Edition Jonathon Simpson

https://ebookmass.com/product/how-javascript-works-master-the-basics-
of-javascript-and-modern-web-app-development-1st-edition-jonathon-
simpson-2/
How JavaScript Works: Master the Basics of JavaScript and
Modern Web App Development 1st Edition Jonathon Simpson

https://ebookmass.com/product/how-javascript-works-master-the-basics-
of-javascript-and-modern-web-app-development-1st-edition-jonathon-
simpson/

JavaScript A Beginner's Guide Fifth Edition John Pollock

https://ebookmass.com/product/javascript-a-beginners-guide-fifth-
edition-john-pollock/

JavaScript Design Patterns Hugo Di Francesco

https://ebookmass.com/product/javascript-design-patterns-hugo-di-
francesco/

JavaScript: The New Toys T. J. Crowder

https://ebookmass.com/product/javascript-the-new-toys-t-j-crowder/

JavaScript All-in-One For Dummies 1st Edition Chris


Minnick

https://ebookmass.com/product/javascript-all-in-one-for-dummies-1st-
edition-chris-minnick/
Eloquent JavaScript
4th edition

Marijn Haverbeke
Copyright © 2024 by Marijn Haverbeke

This work is licensed under a Creative Commons attribution-noncommercial


license (http://creativecommons.org/licenses/by-nc/3.0/). All code in the
book may also be considered licensed under an MIT license (https://eloquentjavascript.
net/code/LICENSE).
The illustrations are contributed by various artists: Cover by Péchane Sumi-
e. Chapter illustrations by Madalina Tantareanu. Pixel art in Chapters 7 and
16 by Antonio Perdomo Pastor. Regular expression diagrams in Chapter 9
generated with regexper.com by Jeff Avallone. Village photograph in Chapter
11 by Fabrice Creuzot. Game concept for Chapter 16 by Thomas Palef.

You can buy a print version of this book, with an extra bonus chapter included,
printed by No Starch Press at http://a-fwd.com/com=marijhaver-20&asin-
com=1593279507.

i
Contents
Introduction 1
On programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Why language matters . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
What is JavaScript? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Code, and what to do with it . . . . . . . . . . . . . . . . . . . . . . . 7
Overview of this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Typographic conventions . . . . . . . . . . . . . . . . . . . . . . . . . . 8

1 Values, Types, and Operators 10


Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Unary operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Boolean values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Empty values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Automatic type conversion . . . . . . . . . . . . . . . . . . . . . . . . . 18
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

2 Program Structure 21
Expressions and statements . . . . . . . . . . . . . . . . . . . . . . . . 21
Bindings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Binding names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
The environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
The console.log function . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Return values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Control flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Conditional execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
while and do loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Indenting Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
for loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Breaking Out of a Loop . . . . . . . . . . . . . . . . . . . . . . . . . . 32

ii
Updating bindings succinctly . . . . . . . . . . . . . . . . . . . . . . . 32
Dispatching on a value with switch . . . . . . . . . . . . . . . . . . . . 33
Capitalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

3 Functions 38
Defining a function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Bindings and scopes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Nested scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Functions as values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Declaration notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Arrow functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
The call stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Optional Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Closure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Growing functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Functions and side effects . . . . . . . . . . . . . . . . . . . . . . . . . 52
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

4 Data Structures: Objects and Arrays 55


The weresquirrel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Data sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Mutability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
The lycanthrope’s log . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Computing correlation . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Array loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
The final analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Further arrayology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Strings and their properties . . . . . . . . . . . . . . . . . . . . . . . . 69
Rest parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
The Math object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
Destructuring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Optional property access . . . . . . . . . . . . . . . . . . . . . . . . . . 74

iii
JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76

5 Higher-Order Functions 79
Abstraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Abstracting repetition . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Higher-order functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Script data set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Filtering arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Transforming with map . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Summarizing with reduce . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Composability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Strings and character codes . . . . . . . . . . . . . . . . . . . . . . . . 88
Recognizing text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

6 The Secret Life of Objects 93


Abstract Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Prototypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Private Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Overriding derived properties . . . . . . . . . . . . . . . . . . . . . . . 99
Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
Getters, setters, and statics . . . . . . . . . . . . . . . . . . . . . . . . 103
Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
The iterator interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
The instanceof operator . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

7 Project: A Robot 112


Meadowfield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
The task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
Persistent data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116

iv
The mail truck’s route . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
Pathfinding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

8 Bugs and Errors 123


Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Strict mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Error propagation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
Cleaning up after exceptions . . . . . . . . . . . . . . . . . . . . . . . . 131
Selective catching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Assertions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136

9 Regular Expressions 138


Creating a regular expression . . . . . . . . . . . . . . . . . . . . . . . 138
Testing for matches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
Sets of characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
International characters . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Repeating parts of a pattern . . . . . . . . . . . . . . . . . . . . . . . . 142
Grouping subexpressions . . . . . . . . . . . . . . . . . . . . . . . . . . 143
Matches and groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
The Date class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
Boundaries and look-ahead . . . . . . . . . . . . . . . . . . . . . . . . . 145
Choice patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
The mechanics of matching . . . . . . . . . . . . . . . . . . . . . . . . 147
Backtracking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
The replace method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
Greed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
Dynamically creating RegExp objects . . . . . . . . . . . . . . . . . . 152
The search method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
The lastIndex property . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Parsing an INI file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
Code units and characters . . . . . . . . . . . . . . . . . . . . . . . . . 157
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159

v
10 Modules 161
Modular programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
ES modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
CommonJS modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
Building and bundling . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
Module design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171

11 Asynchronous Programming 173


Asynchronicity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
Callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
Promises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
Failure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
Carla . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Breaking In . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Async functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
Generators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
A Corvid Art Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
The event loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
Asynchronous bugs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191

12 Project: A Programming Language 193


Parsing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
The evaluator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
Special forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
The environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
Cheating . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204

13 JavaScript and the Browser 206


Networks and the Internet . . . . . . . . . . . . . . . . . . . . . . . . . 206
The Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
HTML and JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . 211

vi
In the sandbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
Compatibility and the browser wars . . . . . . . . . . . . . . . . . . . 212

14 The Document Object Model 214


Document structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
The standard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
Moving through the tree . . . . . . . . . . . . . . . . . . . . . . . . . . 217
Finding elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
Changing the document . . . . . . . . . . . . . . . . . . . . . . . . . . 219
Creating nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
Styling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
Cascading styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
Query selectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
Positioning and animating . . . . . . . . . . . . . . . . . . . . . . . . . 228
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230

15 Handling Events 233


Event handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
Events and DOM nodes . . . . . . . . . . . . . . . . . . . . . . . . . . 234
Event objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
Propagation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
Default actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Key events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Pointer events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
Scroll events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
Focus events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
Load event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
Events and the event loop . . . . . . . . . . . . . . . . . . . . . . . . . 245
Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
Debouncing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249

16 Project: A Platform Game 251


The game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
The technology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252

vii
Levels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
Reading a level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
Actors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
Drawing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
Motion and collision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
Actor updates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
Tracking keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
Running the game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271

17 Drawing on Canvas 273


SVG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
The canvas element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
Lines and surfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
Curves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
Drawing a pie chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
Transformation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
Storing and clearing transformations . . . . . . . . . . . . . . . . . . . 286
Back to the game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
Choosing a graphics interface . . . . . . . . . . . . . . . . . . . . . . . 292
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294

18 HTTP and Forms 296


The protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
Browsers and HTTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
Fetch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
HTTP sandboxing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
Appreciating HTTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
Security and HTTPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
Form fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
Focus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
Disabled fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
The form as a whole . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
Text fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
Checkboxes and radio buttons . . . . . . . . . . . . . . . . . . . . . . . 308
Select fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309

viii
Visit https://ebookmass.com today to explore
a vast collection of ebooks across various
genres, available in popular formats like
PDF, EPUB, and MOBI, fully compatible with
all devices. Enjoy a seamless reading
experience and effortlessly download high-
quality materials in just a few simple steps.
Plus, don’t miss out on exciting offers that
let you access a wealth of knowledge at the
best prices!
File fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Storing data client-side . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315

19 Project: A Pixel Art Editor 317


Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
The state . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
DOM building . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
The canvas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
The application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
Drawing tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
Saving and loading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
Undo history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
Let’s draw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
Why is this so hard? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335

20 Node.js 337
Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
The node command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
Installing with NPM . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
The file system module . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
The HTTP module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
Streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
A file server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352

21 Project: Skill-Sharing Website 354


Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
Long polling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
HTTP interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
The server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
The client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371

Exercise Hints 373


Program Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373

ix
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
Data Structures: Objects and Arrays . . . . . . . . . . . . . . . . . . . 375
Higher-Order Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
The Secret Life of Objects . . . . . . . . . . . . . . . . . . . . . . . . . 378
Project: A Robot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
Bugs and Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
Asynchronous Programming . . . . . . . . . . . . . . . . . . . . . . . . 382
Project: A Programming Language . . . . . . . . . . . . . . . . . . . . 384
The Document Object Model . . . . . . . . . . . . . . . . . . . . . . . 385
Handling Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
Project: A Platform Game . . . . . . . . . . . . . . . . . . . . . . . . . 387
Drawing on Canvas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
HTTP and Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
Project: A Pixel Art Editor . . . . . . . . . . . . . . . . . . . . . . . . 391
Node.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
Project: Skill-Sharing Website . . . . . . . . . . . . . . . . . . . . . . . 394

x
“We think we are creating the system for our own purposes. We
believe we are making it in our own image... But the computer is
not really like us. It is a projection of a very slim part of ourselves:
that portion devoted to logic, order, rule, and clarity.”
—Ellen Ullman, Close to the Machine: Technophilia and its
Discontents

Introduction
This is a book about instructing computers. Computers are about as common
as screwdrivers today, but they are quite a bit more complex, and making them
do what you want them to do isn’t always easy.
If the task you have for your computer is a common, well-understood one,
such as showing you your email or acting like a calculator, you can open the
appropriate application and get to work. But for unique or open-ended tasks,
there often is no appropriate application.
That is where programming may come in. Programming is the act of con-
structing a program—a set of precise instructions telling a computer what to do.
Because computers are dumb, pedantic beasts, programming is fundamentally
tedious and frustrating.
Fortunately, if you can get over that fact—and maybe even enjoy the rigor
of thinking in terms that dumb machines can deal with—programming can be
rewarding. It allows you to do things in seconds that would take forever by
hand. It is a way to make your computer tool do things that it couldn’t do
before. On top of that, it makes for a wonderful game of puzzle solving and
abstract thinking.
Most programming is done with programming languages. A programming
language is an artificially constructed language used to instruct computers. It
is interesting that the most effective way we’ve found to communicate with a
computer borrows so heavily from the way we communicate with each other.
Like human languages, computer languages allow words and phrases to be
combined in new ways, making it possible to express ever new concepts.
At one point, language-based interfaces, such as the BASIC and DOS prompts
of the 1980s and 1990s, were the main method of interacting with computers.
For routine computer use, these have largely been replaced with visual inter-
faces, which are easier to learn but offer less freedom. But if you know where
to look, the languages are still there. One of them, JavaScript, is built into
every modern web browser—and is thus available on almost every device.
This book will try to make you familiar enough with this language to do
useful and amusing things with it.

1
On programming
Besides explaining JavaScript, I will introduce the basic principles of program-
ming. Programming, it turns out, is hard. The fundamental rules are simple
and clear, but programs built on top of these rules tend to become complex
enough to introduce their own rules and complexity. You’re building your own
maze, in a way, and you can easily get lost in it.
There will be times when reading this book feels terribly frustrating. If you
are new to programming, there will be a lot of new material to digest. Much of
this material will then be combined in ways that require you to make additional
connections.
It is up to you to make the necessary effort. When you are struggling to
follow the book, do not jump to any conclusions about your own capabilities.
You are fine—you just need to keep at it. Take a break, reread some material,
and make sure you read and understand the example programs and exercises.
Learning is hard work, but everything you learn is yours and will make further
learning easier.

When action grows unprofitable, gather information; when infor-


mation grows unprofitable, sleep.
—Ursula K. Le Guin, The Left Hand of Darkness

A program is many things. It is a piece of text typed by a programmer, it is


the directing force that makes the computer do what it does, it is data in the
computer’s memory, and at the same time it controls the actions performed
on this memory. Analogies that try to compare programs to familiar objects
tend to fall short. A superficially fitting one is to compare a program to a
machine—lots of separate parts tend to be involved, and to make the whole
thing tick, we have to consider the ways in which these parts interconnect and
contribute to the operation of the whole.
A computer is a physical machine that acts as a host for these immaterial
machines. Computers themselves can do only stupidly straightforward things.
The reason they are so useful is that they do these things at an incredibly
high speed. A program can ingeniously combine an enormous number of these
simple actions to do very complicated things.
A program is a building of thought. It is costless to build, it is weightless,
and it grows easily under our typing hands. But as a program grows, so does
its complexity. The skill of programming is the skill of building programs
that don’t confuse yourself. The best programs are those that manage to do
something interesting while still being easy to understand.

2
Some programmers believe that this complexity is best managed by using
only a small set of well-understood techniques in their programs. They have
composed strict rules (“best practices”) prescribing the form programs should
have and carefully stay within their safe little zone.
This is not only boring, it is ineffective. New problems often require new
solutions. The field of programming is young and still developing rapidly, and
it is varied enough to have room for wildly different approaches. There are
many terrible mistakes to make in program design, and you should go ahead
and make them at least once so that you understand them. A sense of what a
good program looks like is developed with practice, not learned from a list of
rules.

Why language matters


In the beginning, at the birth of computing, there were no programming lan-
guages. Programs looked something like this:
00110001 00000000 00000000
00110001 00000001 00000001
00110011 00000001 00000010
01010001 00001011 00000010
00100010 00000010 00001000
01000011 00000001 00000000
01000001 00000001 00000001
00010000 00000010 00000000
01100010 00000000 00000000

This is a program to add the numbers from 1 to 10 together and print the
result: 1 + 2 + ... + 10 = 55. It could run on a simple hypothetical machine.
To program early computers, it was necessary to set large arrays of switches
in the right position or punch holes in strips of cardboard and feed them to
the computer. You can imagine how tedious and error-prone this procedure
was. Even writing simple programs required much cleverness and discipline.
Complex ones were nearly inconceivable.
Of course, manually entering these arcane patterns of bits (the ones and
zeros) did give the programmer a profound sense of being a mighty wizard.
And that has to be worth something in terms of job satisfaction.
Each line of the previous program contains a single instruction. It could be
written in English like this:

1. Store the number 0 in memory location 0.

3
2. Store the number 1 in memory location 1.
3. Store the value of memory location 1 in memory location 2.
4. Subtract the number 11 from the value in memory location 2.
5. If the value in memory location 2 is the number 0, continue with instruc-
tion 9.
6. Add the value of memory location 1 to memory location 0.
7. Add the number 1 to the value of memory location 1.
8. Continue with instruction 3.
9. Output the value of memory location 0.

Although that is already more readable than the soup of bits, it is still rather
obscure. Using names instead of numbers for the instructions and memory
locations helps:
Set “total” to 0.
Set “count” to 1.
[loop]
Set “compare” to “count”.
Subtract 11 from “compare”.
If “compare” is zero, continue at [end].
Add “count” to “total”.
Add 1 to “count”.
Continue at [loop].
[end]
Output “total”.

Can you see how the program works at this point? The first two lines give
two memory locations their starting values: total will be used to build up the
result of the computation, and count will keep track of the number that we are
currently looking at. The lines using compare are probably the most confusing
ones. The program wants to see whether count is equal to 11 to decide whether
it can stop running. Because our hypothetical machine is rather primitive, it
can only test whether a number is zero and make a decision based on that.
It therefore uses the memory location labeled compare to compute the value
of count - 11 and makes a decision based on that value. The next two lines
add the value of count to the result and increment count by 1 every time the
program decides that count is not 11 yet.
Here is the same program in JavaScript:

4
let total = 0, count = 1;
while (count <= 10) {
total += count;
count += 1;
}
console.log(total);
// → 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 forth
anymore—the while construct takes care of that. It continues executing the
block (wrapped in braces) below it as long as the condition it was given holds.
That condition is count <= 10, which means “the count is less than or equal
to 10”. We no longer have to create a temporary value and compare that to
zero, which was just an uninteresting detail. Part of the power of programming
languages is that they can take care of uninteresting details for us.
At the end of the program, after the while construct has finished, the console
.log operation is used to write out the result.
Finally, here is what the program could look like if we happened to have
the convenient operations range and sum available, which respectively create a
collection of numbers within a range and compute the sum of a collection of
numbers:
console.log(sum(range(1, 10)));
// → 55

The moral of this story is that the same program can be expressed in both long
and short, unreadable and readable ways. The first version of the program was
extremely obscure, whereas this last one is almost English: log the sum of the
range of numbers from 1 to 10. (We will see in later chapters how to define
operations like sum and range.)
A good programming language helps the programmer by allowing them to
talk about the actions that the computer has to perform on a higher level.
It helps omit details, provides convenient building blocks (such as while and
console.log), allows you to define your own building blocks (such as sum and
range), and makes those blocks easy to compose.

What is JavaScript?
JavaScript was introduced in 1995 as a way to add programs to web pages in the
Netscape Navigator browser. The language has since been adopted by all other
major graphical web browsers. It has made modern web applications possible—

5
that is, applications with which you can interact directly without doing a page
reload for every action. JavaScript is also used in more 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 inspired by mar-
keting considerations rather than good judgment. When JavaScript was being
introduced, the Java language was being heavily marketed and was gaining
popularity. Someone thought it was a good idea to try to ride along on this
success. Now we are stuck with the name.
After its adoption outside of Netscape, a standard document was written to
describe the way the JavaScript language should work so that the various pieces
of software that claimed to support JavaScript could make sure they actually
provided the same language. This is called the ECMAScript standard, after
the Ecma International organization that conducted the standardization. In
practice, the terms ECMAScript and JavaScript can be used interchangeably—
they are two names for the same language.
There are those who will say terrible things about JavaScript. Many of these
things are true. When I was required to write something in JavaScript for the
first time, I quickly came to despise it. It would accept almost anything I typed
but interpret it in a way that was completely different from what I meant. This
had a lot to do with the fact that I did not have a clue what I was doing, of
course, but there is a real issue here: JavaScript is ridiculously liberal in what
it allows. The idea behind this design was that it would make programming in
JavaScript easier for beginners. In actuality, it mostly makes finding problems
in your programs harder because the system will not point them out to you.
This flexibility also has its advantages, though. It leaves room for techniques
that are impossible in more rigid languages and makes for a pleasant, informal
style of programming. After learning the language properly and working with
it for a while, I have come to actually like JavaScript.
There have been several versions of JavaScript. ECMAScript version 3 was
the widely supported version during JavaScript’s ascent to dominance, roughly
between 2000 and 2010. During this time, work was underway on an ambitious
version 4, which planned a number of radical improvements and extensions to
the language. Changing a living, widely used language in such a radical way
turned out to be politically difficult, and work on the version 4 was abandoned
in 2008. A much less ambitious version 5, which made only some uncontro-
versial improvements, came out in 2009. In 2015, version 6 came out, a major
update that included some of the ideas planned for version 4. Since then we’ve
had new, small updates every year.
The fact that JavaScript is evolving means that browsers have to constantly

6
keep up. If you’re using an older browser, it may not support every feature.
The language designers are careful to not make any changes that could break
existing programs, so new browsers can still run old programs. In this book,
I’m using the 2023 version of JavaScript.
Web browsers are not the only platforms on which JavaScript is used. Some
databases, such as MongoDB and CouchDB, use JavaScript as their scripting
and query language. Several platforms for desktop and server programming,
most notably the Node.js project (the subject of Chapter 20), provide an envi-
ronment for programming JavaScript outside of the browser.

Code, and what to do with it


Code is the text that makes up programs. Most chapters in this book contain
quite a lot of code. I believe reading code and writing code are indispensable
parts of learning to program. Try to not just glance over the examples—read
them attentively and understand them. This may be slow and confusing at
first, but I promise that you’ll quickly get the hang of it. The same goes for
the exercises. Don’t assume you understand them until you’ve actually written
a working solution.
I recommend you try your solutions to exercises in an actual JavaScript
interpreter. That way, you’ll get immediate feedback on whether what you are
doing is working, and, I hope, you’ll be tempted to experiment and go beyond
the exercises.
The easiest way to run the example code in the book—and to experiment
with it—is to look it up in the online version of the book at https://eloquentjavascript.net.
There, you can click any code example to edit and run it and to see the output
it produces. To work on the exercises, go to https://eloquentjavascript.net/
code, which provides starting code for each coding exercise and allows you to
look at the solutions.
Running the programs defined in this book outside of the book’s website
requires some care. Many examples stand on their own and should work in
any JavaScript environment. But code in later chapters is often written for
a specific environment (the browser or Node.js) and can run only there. In
addition, many chapters define bigger programs, and the pieces of code that
appear in them depend on each other or on external files. The sandbox on
the website provides links to ZIP files containing all the scripts and data files
necessary to run the code for a given chapter.

7
Overview of this book
This book contains roughly three parts. The first 12 chapters discuss the
JavaScript language. The next seven chapters are about web browsers and the
way JavaScript is used to program them. Finally, two chapters are devoted to
Node.js, another environment to program JavaScript in. There are five project
chapters in the book that describe larger example programs to give you a taste
of actual programming.
The language part of the book starts with four chapters that introduce the
basic structure of the JavaScript language. They discuss control structures
(such as the while word you saw in this introduction), functions (writing your
own building blocks), and data structures. After these, you will be able to write
basic programs. Next, Chapters 5 and 6 introduce techniques to use functions
and objects to write more abstract code and keep complexity under control.
After a first project chapter that builds a crude delivery robot, the language
part of the book continues with chapters on error handling and bug fixing,
regular expressions (an important tool for working with text), modularity (an-
other defense against complexity), and asynchronous programming (dealing
with events that take time). The second project chapter, where we implement
a programming language, concludes the first part of the book.
The second part of the book, Chapters 13 to 19, describes the tools that
browser JavaScript has access to. You’ll learn to display things on the screen
(Chapters 14 and 17), respond to user input (Chapter 15), and communicate
over the network (Chapter 18). There are again two project chapters in this
part, building a platform game and a pixel paint program.
Chapter 20 describes Node.js, and Chapter 21 builds a small website using
that tool.

Typographic conventions
In this book, text written in a monospaced font will represent elements of pro-
grams. Sometimes these are self-sufficient fragments, and sometimes they just
refer to part of a nearby program. Programs (of which you have already seen
a few) are written as follows:
function factorial(n) {
if (n == 0) {
return 1;
} else {
return factorial(n - 1) * n;
}

8
Visit https://ebookmass.com today to explore
a vast collection of ebooks across various
genres, available in popular formats like
PDF, EPUB, and MOBI, fully compatible with
all devices. Enjoy a seamless reading
experience and effortlessly download high-
quality materials in just a few simple steps.
Plus, don’t miss out on exciting offers that
let you access a wealth of knowledge at the
best prices!
Exploring the Variety of Random
Documents with Different Content
injurious to boilers. 3dly, The only attention required is to fill the coal
receiver, every two or three hours, and clean the fire when
necessary. 4thly, The coal is more completely consumed than by the
common furnace, as all the effect of what is termed stirring up the
fire (by which no inconsiderable quantity of coal is passed into the
ash-pit) is attained without moving the coal upon the grate."

The fire-place is a circular grate placed on a vertical shaft in a


horizontal position. It is capable of revolving, and is made to do so
by the vertical shaft, which is turned by wheelwork, which is worked
by the engine itself; or this shaft or spindle may be turned by a
water-wheel, on which a stream of water is allowed to flow from a
reservoir into which it is pumped by the power of the engine; and by
regulating the quantity of water in the stream, the grate may be
made to revolve with a greater or less speed. In that part of the
boiler which is over the grate, there is an aperture, in which is
placed a hopper, through which fuel is let down upon the grate at
the rate of any quantity per minute that may be required. The
apparatus which admits the coals through this hopper is worked by
the engine also, and by the same means as the grate is turned so
that the grate revolves with a speed proportional to the rapidity with
which the fuel is admitted through the hopper, and by this ingenious
arrangement the fuel falls equally thick upon the grate.

The supply of water which turns the wheel which works the grate
and the machinery in the hopper, is regulated by a cock connected
with the self-regulating damper; so that when the steam is being
produced too fast, the supply of water will be diminished, and by
that means the supply of fuel to the grate will be diminished, and
the grate will revolve less rapidly: and when the steam is being
produced too slowly for the demands of the engine, the contrary
effects take place. In this way the fuel which is introduced into the
furnace is exactly proportioned to the work which the engine has to
perform. The hopper may be made large enough to hold coals for a
day's work, so that the furnace requires no other attendance than to
deposite coals in the hopper each morning.
The coals are let down from the hopper on the grate at that part
which is most remote from the flue; and as they descend in very
small quantities at a time, they are almost immediately ignited. But
until their ignition is complete, a smoke will arise, which, passing to
the flue over the vividly burning fuel, will be ignited. Air is admitted
through proper apertures, and its quantity regulated by the damper
in the same manner as the supply of fuel.

The superiority of this beautiful invention over the common


smoke-consuming furnaces is very striking. Its principle of self-
adjustment as to the supply of coals and atmospheric air, and the
proportioning of these to the quantity of work to be performed by
the engine, not only independent of human labour, but with a
greater degree of accuracy than any human skill or attention could
possibly effect, produces saving of expense, both in fuel and labour.

(75.) Mr. Oldham, engineer to the Bank of Ireland, has proposed


another modification of the self-regulating furnace, which seems to
possess several advantages, and evinces considerable ingenuity.

He uses a slightly inclined grate, at the back or lower end of which


is the flue, and at the front or higher end, the hopper for admitting
the coals. In the bottom or narrow end of the hopper is a moveable
shelf, worked by the engine. Upon drawing back this shelf, a small
quantity of fuel is allowed to descend upon a fixed shelf under it;
and upon the return of the moveable shelf, this fuel is protruded
forward upon the grate. Every alternate bar of the grate is fixed, but
the intermediate ones are connected with levers, by which they are
moved alternately up and down.[22] The effect is, that the coals
upon the bars are continually stirred, and gradually advanced by
their own weight from the front of the grate, where they fall from
the hopper, to the back, where they are deposited in the ash-pit. By
the shape and construction of the bars, the air is conducted upwards
between them, and rushes through the burning fuel, so as to act in
the manner of a blowpipe, and the entire surface of the fire presents
a sheet of flame.
We cannot fail to be struck with the beauty of all these
contrivances, by which the engine is made to regulate itself, and
supply its own wants. It is in fact, all but alive. It was observed by
Belidor, long before the steam engine reached the perfection which it
has now acquired, that it resembled an animal, and that no mere
work of man ever approached so near to actual life. Heat is the
principle of its existence. The boiler acts the part of the heart, from
which its vivifying fluid rushes copiously through all the tubes, where
having discharged the various functions of life, and deposited its
heat in the proper places, it returns again to the source it sprung
from, to be duly prepared for another circulation. The healthfulness
of its action is indicated by the regularity of its pulsations; it
procures its own food by its own labour; it selects those parts which
are fit for its support, both as to quantity and quality; and has its
natural evacuations, by which all the useless and innutritious parts
are discharged. It frequently cures its own diseases, and corrects the
irregularity of its own actions, exerting something like moral
faculties. Without designing to carry on the analogy, Mr. Farey, in
speaking of the variations incident to the work performed by
different steam engines, states some further particulars in which it
maybe curiously extended. "We must observe," says he, "that the
variation in the performance of different steam engines, which are
constructed on the same principle, working under the same
advantages, is the same as would be found in the produce of the
labour of so many different horses or other animals when compared
with their consumption of food; for the effects of different steam
engines will vary as much from small differences in the proportion of
their parts, as the strength of animals from the vigour of their
constitutions; and again, there will be as great differences in the
performance of the same engine when in good and bad order, from
all the parts being tight and well oiled, so as to move with little
friction, as there is in the labour of an animal from his being in good
or bad health, or excessively fatigued: but in all these cases there
will be a maximum which cannot be exceeded, and an average
which we ought to expect to obtain."
CHAPTER IX.
DOUBLE-CYLINDER ENGINES.

Hornblower's Engine. — Woolf's Engine. — Cartwright's Engine.

(76.) The expansive property of steam, of which Watt availed


himself in his single engine by cutting off the supply of steam before
the descent of the piston was completed, was applied in a peculiar
manner by an engineer named Hornblower, about the year 1781,
and at a later period by Woolf. Hornblower was the first who
conceived the idea of working an engine with two cylinders of
different sizes, by allowing the steam to flow freely from the boiler
until it fills the smaller cylinder, and then permitting it to expand into
the greater one, employing it thus to press down two pistons in the
manner which we shall presently describe. The condensing
apparatus of Hornblower, as well as the other appendages of the
engine, do not differ materially from those of Watt; so that it will be
sufficient for our present purpose to explain the manner in which the
steam is made to act in moving the piston.

Let C, fig. 41., be the centre of the great working beam, carrying
two arch heads, on which the chains of the piston rods play. The
distances of these arch heads from the centre C must be in the same
proportion as the length of the cylinders, in order that the same play
of the beam may correspond to the plays of both pistons. Let F be
the steam-pipe from the boiler, and G a valve to admit the steam
above the lesser piston, H is a tube by which a communication may
be opened by the valve I between the top and bottom of the lesser
cylinder B. K is a tube communicating, by the valve L, between the
bottom of the lesser cylinder B and the top of the greater cylinder A.
M is a tube communicating, by the valve N, between the top and
bottom of the greater cylinder A; and P a tube leading to the
condenser by the exhausting valve O.

At the commencement of the operation, suppose all the valves


opened, and steam allowed to flow through the entire engine until
the air be completely expelled, and then let all the valves be closed.
To start the engine, let the exhausting valve O and the steam valves
G and L be opened, as in fig. 41. The steam will flow freely from the
boiler, and press upon the lesser piston, and at the same time the
steam below the greater piston will flow into the condenser, leaving
a vacuum in the greater cylinder. The valve L being opened, the
steam which is under the piston in the lesser cylinder will flow
through K, and press on the greater piston, which, having a vacuum
beneath it, will consequently descend. At the commencement of the
motion, the lesser piston is as much resisted by the steam below it
as it is urged by the steam above it; but after a part of the descent
has been effected, the steam below the lesser piston passing into
the greater, expands into an increased space, and therefore loses its
elastic force proportionally. The steam above the lesser piston
retaining its full force by having a free communication with the boiler
by the valve G, the lesser piston will be urged by a force equal to the
excess of the pressure of this steam above the diminished pressure
of the expanded steam below it. As the pistons descend, the steam
which is between it continually increasing in its bulk, and therefore
decreasing in its pressure, from whence it follows, that the force
which resists the lesser piston is continually decreasing, while that
which presses it down remains the same, and therefore the effective
force which impels it must be continually increasing.

On the other hand, the force which urges the greater piston is
continually decreasing, since there is a vacuum below it, and the
steam which presses it is continually expanding into an increased
bulk.

Impelled in this way, let us suppose the pistons to have arrived at


the bottoms of the cylinders, as in fig. 42., and let the valves G, L,
and O be closed, and the valves I and N opened. No steam is
allowed to flow from the boiler, G being closed, nor any allowed to
pass into the condenser, since O is closed, and all communications
between the cylinders is stopped by closing L. By opening the valve
I, a free communication is made between the top and bottom of the
lesser piston through the tube H, so that the steam which presses
above the lesser piston will exert the same pressure below it, and
the piston is in a state of indifference. In the same manner the valve
N being open, a free communication is made between the top and
bottom of the greater piston, and the steam circulates above and
below the piston, and leaves it free to rise. A counterpoise attached
to the pump-rods in this case, draws up the piston, as in Watt's
single engine; and when they arrive at the top, the valves I and N
are closed, and G, L, and O opened, and the next descent of the
pistons is produced in the manner already described, and so the
process is continued.

The valves are worked by the engine itself, by means similar to


some of those already described. By computation, we find the power
of this engine to be nearly the same as a similar engine on Watt's
expansive principle. It does not however appear, that any adequate
advantage was gained by this modification of the principle, since no
engines of this construction are now made.

(77.) The use of two cylinders was revived by Arthur Woolf, in


1804, who, in this and the succeeding year, obtained patents for the
application of steam raised under a high pressure to double-cylinder
engines. The specification of his patent states, that he has proved by
experiment that steam raised under a safety-valve loaded with any
given number of pounds upon the square inch, will, if allowed to
expand into as many times its bulk as there are pounds of pressure
on the square inch, have a pressure equal to that of the atmosphere.
Thus, if the safety-valve be loaded with four pounds on the square
inch, the steam, after expanding into four times its bulk, will have
the atmospheric pressure. If it be loaded with 5, 6, or 10 lbs. on the
square inch, it will have the atmospheric pressure when it has
expanded into 5, 6, or 10 times its bulk, and so on. It was, however,
understood in this case, that the vessel into which it was allowed to
expand should have the same temperature as the steam before it
expands.

It is very unaccountable how a person of Mr. Woolf's experience in


the practical application of steam could be led into errors so gross as
those involved in the averments of this patent; and it is still more
unaccountable how the experiments could have been conducted
which led him to conclusions not only incompatible with all the
established properties of elastic fluids—properties which at that time
were perfectly understood—but even involving in themselves
palpable contradiction and absurdity. If it were admitted that every
additional pound avoirdupois which should be placed upon the
safety-valve would enable steam, by its expansion into a
proportionally enlarged space, to attain a pressure equal to the
atmosphere, the obvious consequence would be, that a physical
relation would subsist between the atmospheric pressure and the
pound avoirdupois! It is wonderful that it did not occur to Mr. Woolf,
that, granting his principle to be true at any given place, it would
necessarily be false at another place where the barometer would
stand at a different height. Thus if the principle were true at the foot
of a mountain, it would be false at the top of it; and if it were true in
fair weather, it would be false in foul weather, since these
circumstances would be attended by a change in the atmospheric
pressure, without making any change in the pound avoirdupois.[23]

The method by which Mr. Woolf proposed to apply the principle


which he imagined himself to have discovered was by an
arrangement of cylinders similar to those of Hornblower, but having
their magnitudes proportioned to the greater extent of expansion
which he proposed to use. Two cylinders, like those of Hornblower,
were placed under the working beam, having their piston-rods at
distances from the axis proportioned to the lengths of their
respective strokes. The relative magnitudes of the cylinders A and B
must be adjusted according to the extent to which the principle of
expansion is intended to be used. The valves C C´ were placed at
each end of the lesser cylinder in tubes communicating with the
boiler, so as to admit steam on each side of the lesser piston, and
cut it off at pleasure. A tube, D´, formed a communication between
the upper end of the lesser and lower end of the greater cylinder,
which communication is opened and closed at pleasure by the valve
E´. In like manner, the tube D forms a communication between the
lower end of the lesser cylinder and the upper end of the greater,
which may be opened and closed by the valve E. The top and
bottom of the greater cylinder communicated with the condenser by
valves F´ F.

Let us suppose that the air is blown from the engine in the usual
way, all the valves closed, and the engine ready to start, the pistons
being at the top of the cylinders. Open the valves C, E, and F. The
steam which occupies the greater cylinder below the piston will now
pass into the condenser through F, leaving a vacuum below the
piston. The steam which is in the lesser cylinder below the piston
will pass through D and open the valve E, and will press down the
greater piston. The steam from the boiler will flow in at C, and press
on the lesser piston. At first the whole motion will proceed from the
pressure upon the greater piston, since the steam, both above and
below the lesser piston, has the same pressure. But, as the pistons
descend, the steam below the less passing into the greater cylinder,
expands into a greater space, and consequently exerts a diminished
pressure, and, therefore, the steam on the other side exerting an
undiminished pressure, acquires an impelling force exactly equal to
the pressure lost in the expansion of the steam between the two
pistons. Thus both pistons will be pressed to the bottoms of their
respective cylinders. It will be observed that in the descent the
greater piston is urged by a continually decreasing force, while the
lesser is urged by continually increasing force.

Upon the arrival of the pistons at the bottoms of the cylinders, let
the valves, C, E, F be closed, and C´, E´, F´ be opened, as in fig.
44. The steam which is above the greater piston now flows through
F´ into the condenser, leaving the space above the piston a vacuum.
The steam which is above the lesser piston passes through E´ and D
´ below the greater, while the steam from the boiler is admitted
through C´ below the lesser piston. The pressure of the steam
entering through E´ below the greater piston, pressing on it against
the vacuum above it, commences the ascent. In the mean time the
steam above the lesser piston passing into the enlarged space of the
greater cylinder, loses gradually its elastic force, so that the steam
entering from the boiler at C´ becomes in part effective, and the
ascent is completed under exactly the same circumstances as the
descent, and in this way the process is continued.

It is evident that the valves may be easily worked by the


mechanism of the engine itself.

In this arrangement the pistons ascend and descend together, and


their rods must consequently be attached to the beam at the same
side of the centre. It is sometimes desirable that they should act on
different sides of the centre of the beam, and consequently that one
should ascend while the other descends. It is easy to arrange the
valves so as to effect this. In fig. 45., the lesser piston is at the
bottom of the cylinder, and the greater at the top. On opening the
valves C´, E´, F´, a vacuum is produced below the greater piston,
and steam flows from the lesser cylinder, through E´, above the
greater piston, and presses it down. At the same time steam being
admitted from the boiler through C´ below the lesser piston, forces
it up against the diminishing force of the steam above it, which
expands into the greater cylinder. Thus as the greater piston
descends the lesser ascends. When each has traversed its cylinder,
the valves C´, E´, F´ being closed, and C, E, F opened, the lesser
piston will descend, and the greater ascend, and so on.

(78.) The law according to which the elastic force of steam


diminishes as it expands, of which Mr. Woolf appears to have been
entirely ignorant, is precisely similar to the same property in air and
other elastic fluids. If steam expands into twice or thrice its volume,
it will lose its elastic force in precisely the same proportion as it
enlarges its bulk; and therefore will have only a half or a third of its
former pressure, supposing that as it expands its temperature is kept
up. Although Mr. Woolf's patent contained the erroneous principle
which we have noticed, yet, so far as his invention suggested the
idea of employing steam at a very high-pressure, and allowing it to
expand in a much greater degree than was contemplated either by
Watt or Hornblower, it became the means of effecting a considerable
saving in fuel; for engines used for pumping on a large scale, the
steam being produced under a pressure of forty or fifty pounds or
more upon the square inch, might be worked first through a small
space with intense force, and the communication with the boiler
being then cut off, it might be allowed, with great advantage, to
expand through a very large space. Some double-cylinder engines
upon this principle have been worked in Cornwall, with considerable
economy. But the form in which the expansive principle, combined
with high pressure, is now applied in the engines used for raising
water from the mines, is that in which it was originally proposed by
Watt. A single cylinder of considerable length is employed; the piston
is driven through a small proportion of this length by steam,
admitted from the boiler at a very intense pressure: the steam being
then cut off, the piston is urged by the expansive force of the steam
which has been admitted, and is by that means brought to the
bottom of the cylinder.

It is evident, under such circumstances, that the pressure of the


steam admitted from the boiler must be much greater than the
resistance opposed to the piston, and that the motion of the piston
must, in the first instance, be accelerated and not uniform. If the
piston moved from the commencement with a uniform motion, the
pressure of the steam urging it must necessarily be exactly equal to
the resistance opposed to it, and then cutting off the supply of
steam from the boiler, the piston could only continue its motion by
inertia, the steam immediately becoming of less pressure than the
resistance; and after advancing through a very small space, the
piston would recoil upon the steam, and come to a state of rest. The
steam, however, at the moment it is cut off being of much greater
pressure than the amount of resistance upon the piston, will
continue to drive the piston forward, until by its expansion its force
is so far diminished as to become equal to the resistance of the
piston. From that point the impelling power of the steam will cease,
and the piston will move forward by its inertia only. The point at
which the steam is cut off should therefore be so regulated that it
shall acquire a pressure equal to the resistance on the piston by its
expansion, just at such a distance from the end of the stroke as the
piston may be able to move through by its inertia. It is evident the
adjustment of this will require great care and nicety of management.

(79.) In 1797 a patent was granted to the Rev. Mr. Cartwright, a


gentleman well known for other mechanical inventions, for some
improvements in the steam-engine. His contrivance is at once so
elegant and simple, that, although it has not been carried into
practice, we cannot here pass it over without notice.

The steam-pipe from the boiler is represented cut off at B (fig.


46.); T is a spindle-valve for admitting steam above the piston, and
R is a spindle-valve in the piston; D is a curved pipe forming a
communication between the cylinder and the condenser, which is of
very peculiar construction. Cartwright proposed effecting a
condensation without a jet, by exposing the steam to contact with a
very large quantity of cold surface. For this purpose, he formed his
condenser by placing two cylinders nearly equal in size one within
the other, allowing the water of the cold cistern in which they were
placed to flow through the inner cylinder, and to surround the outer
one. Thus the thin space between the two cylinders formed the
condenser.

Pl. IX.
Pl. X.
The air-pump is placed immediately under the cylinder, and the
continuation of the piston-rod works its piston, which is solid and
without a valve: F is the pipe from the condenser to the air-pump,
through which the condensed steam is drawn off through the valve
G on the ascent of the piston, and on the descent, this is forced
through a tube into a hot well, H, for the purpose of feeding the
boiler through the feed-pipe I. In the top of the hot well H is a valve
which opens inwards, and is kept closed by a ball floating on the
surface of the liquid. The pressure of the condensed air above the
surface of the liquid in H forces it through I into the boiler. When the
air accumulates in too great a degree in H, the surface of the liquid
is pressed so low that the ball falls and opens the valve, and allows
it to escape. The air in H is that which is pumped from the
condenser with the liquid, and which was disengaged from it.

Let us suppose the piston at the top of the cylinder; it strikes the
tail of the valve T, and raises it, while the stem of the piston-valve R
strikes the top of the cylinder, and is pressed into its seat. A free
communication is at the same time open between the cylinder,
below the piston and the condenser, through the tube D. The
pressure of the steam thus admitted above the piston, acting against
the vacuum below it, will cause its descent. On arriving at the
bottom of the cylinder, the tail of the piston-valve R will strike the
bottom, and it will be lifted from its seat, so that a communication
will be opened through it with the condenser. At the same moment a
projecting spring, K, attached to the piston-rod, strikes the stem of
the steam-valve T, and presses it into its seat. Thus, while the
further admission of steam is cut off, the steam above the piston
flows into the condenser, and the piston being relieved from all
pressure, is drawn up by the momentum of the fly-wheel, which
continues the motion it received from the descending force. On the
arrival of the piston again at the top of the cylinder, the valve T is
opened and R closed, and the piston descends as before, and so the
process is continued.

The mechanism by which motion is communicated from the piston


to the fly-wheel is peculiarly elegant. On the axis of the fly-wheel is
a small wheel with teeth, which work in the teeth of another large
wheel L. This wheel is turned by a crank, which is worked by a
cross-piece attached to the end of the piston-rod. Another equal-
toothed wheel, M, is turned by a crank, which is worked by the other
end of the cross-arm attached to the piston-rod.

One of the peculiarities of this engine is, that the liquid which is
used for the production of steam in the boiler circulates through the
machine without either diminution or admixture with any other fluid,
so that the boiler never wants more feeding than what can be
supplied from the hot-well H. This circumstance forms a most
important feature in the machine, as it allows of ardent spirits being
used in the boiler instead of water, which, since they boil at low
heats, promised a saving of half the fuel. The inventor even
proposed, that the engine should be used as a still, as well as a
mechanical power, in which case the whole of the fuel would be
saved.
In this engine, the ordinary method of rendering the piston steam-
tight, by oil or melted wax or tallow poured upon it, could not be
applied, since the steam above the piston must always have a free
passage through the piston-valve R. The ingenious inventor
therefore contrived a method of making the piston steam-tight in the
cylinder, without oil or stuffing, and his method has since been
adopted with success in other engines.

A ring of metal is ground into the cylinder, so as to fit it perfectly,


and is then cut into four equal segments. The inner surface of this
ring being slightly conical, another ring is ground into it, so as to fit
it perfectly, and this is also cut into four segments, and one is placed
within the other, but in such a manner that the joints or divisions do
not coincide. The arrangement of the two rings is represented in fig.
47. Within the inner ring are placed four springs, which press the
pieces outward against the sides of the cylinder, and are represented
in the diagram. Four pairs of these rings are placed one over
another, so that their joints do not coincide, and the whole is
screwed together by plates placed at top and bottom. A vertical
section of the piston is given in fig. 48.

One of the advantages of this piston is, that the longer it is


worked, the more accurately it fits the cylinder, so that, as the
machine wears it improves.

Metallic pistons have lately come into very general use, and such
contrivances differ very little from the above.
CHAPTER X.
LOCOMOTIVE ENGINES ON RAILWAYS.

High-pressure Engines. — Leupold's Engine. — Trevithick and


Vivian. — Effects of Improvement in Locomotion. — Historical
Account of the Locomotive Engine. — Blenkinsop's Patent. —
Chapman's Improvement. — Walking Engine. — Stephenson's
First Engines. — His Improvements. — Liverpool and
Manchester Railway Company. — Their Preliminary Proceedings.
— The Great Competition of 1829. — The Rocket. — The
Sanspareil. — The Novelty. — Qualities of the Rocket. —
Successive Improvements. — Experiments. — Defects of the
Present Engines. — Inclined Planes. — Methods of surmounting
them. — Circumstances of the Manchester Railway Company. —
Probable Improvements in Locomotives. — Their capabilities
with respect to speed. — Probable Effects of the Projected
Railroads. — Steam Power compared with Horse Power. —
Railroads compared with Canals.

(80.) In the various modifications of the steam engine which we


have hitherto considered, the pressure introduced on one side of the
piston derives its efficacy either wholly or partially from the vacuum
produced by condensation on the other side. This always requires a
condensing apparatus, and a constant and abundant supply of cold
water. An engine of this kind must therefore necessarily have
considerable dimensions and weight, and is inapplicable to uses in
which a small and light machine only is admissible. If the condensing
apparatus be dispensed with, the piston will always be resisted by a
force equal to the atmospheric pressure, and the only part of the
steam pressure which will be available as a moving power, is that
part by which it exceeds the pressure of the atmosphere. Hence, in
engines which do not work by condensation, steam of a much higher
pressure than that of the atmosphere is indispensably necessary,
and such engines are therefore called high-pressure engines.

We are not, however, to understand that every engine, in which


steam is used of a pressure exceeding that of the atmosphere, is
what is meant by a high-pressure engine; for in the ordinary engines
in common use, constructed on Watt's principle, the safety-valve is
loaded with from 3 to 5 lbs. on the square inch; and in Woolf's
engines, the steam is produced under a pressure of 40 lbs. on the
square inch. These would therefore be more properly called
condensing engines than high-pressure engines; a term quite
inapplicable to those of Woolf. In fact, by high-pressure engines is
meant engines in which no vacuum is produced, and, therefore, in
which the piston works against a pressure equal to that of the
atmosphere.

In these engines, the whole of the condensing apparatus, viz. the


cold-water cistern, condenser, air-pump, cold-water pump, &c. are
dispensed with, and nothing is retained except the boiler, cylinder,
piston, and valves. Consequently, such an engine is small, light, and
cheap. It is portable also, and may be moved, if necessary, along
with its load, and is therefore well adapted to locomotive purposes.

(81.) High-pressure engines were one of the earliest modifications


of the steam engine. The contrivance, which is obscurely described
in the article already quoted (27.), from the Century of Inventions, is
a high-pressure engine; for the power there alluded to is the elastic
force of steam working against the atmospheric pressure.
Newcomen, in 1705, applied the working-beam, cylinder, and piston
to the atmospheric engine; and Leupold, about 1720, combined the
working-beam and cylinder with the high-pressure principle, and
produced the earliest high-pressure engine worked by a cylinder and
piston. The following is a description of Leupold's engine:—
A (fig. 49.) is the boiler, with the furnace beneath it; C C´ are two
cylinders with two solid pistons, P P´, connected with the working-
beams B B´, to which are attached the pump-rods, R R´, of two
forcing-pumps, F F´, which communicate with a great force-pipe S;
G is a four-way cock (66.) already described. In the position in which
it stands in the figure, the steam is issuing from below the piston P
into the atmosphere, and the piston is descending by its own
weight; steam from the boiler is at the same time pressing up the
piston P´, with a force equal to the difference between the pressure
of the steam and that of the atmosphere. Thus the piston R of the
forcing-pump is being drawn up, and the piston P´ is forcing the
piston R´ down, and thereby driving water into the force-pipe S. On
the arrival of the piston P at the bottom of the cylinder C, and P´ at
the top of the cylinder C´, the position of the cock is changed as
represented in fig. 50. The steam, which has just pressed up the
piston P´, is allowed to escape into the atmosphere, while the
steam, passing from the boiler below the piston P, presses it up, and
thus P ascends by the steam pressure, and P´ descends by its own
weight. By these means the piston R is forced down, driving before
it the water in the pump cylinder into the force-pipe S, and the
piston R´ is drawn up to allow the other pump-cylinder to be re-
filled; and so the process is continued.

A valve is placed in the bottom of the force-pipes, to prevent the


water which has been driven into it from returning. This valve opens
upwards; and, consequently, the weight of the water pressing upon
it only keeps it more effectually closed. On each descent of the
piston, the pressure transmitted to the valve acting upwards being
greater than the weight of the water resting upon it, forces it open,
and an increased quantity of water is introduced.

(82.) From the date of the improvement of Watt until the


commencement of the present century, high-pressure engines were
altogether neglected in these countries. In the year 1802, Messrs.
Trevithick and Vivian constructed the first high-pressure engine
which was ever brought into extensive practical use in this kingdom.
A section of this machine, made by a vertical plane, is represented in
fig. 51.

The boiler A B is a cylinder with flat circular ends. The fire-place is


constructed in the following manner:—A tube enters the cylindrical
boiler at one end; and, proceeding onwards, near the other
extremity, is turned and recurved, so as to be carried back parallel to
the direction in which it entered. It is thus conducted out of the
boiler, at another part of the same end at which it entered. One of
the ends of this tube communicates with the chimney E, which is
carried upwards, as represented in the figure. The other mouth is
furnished with a door; and in it is placed the grate, which is formed
of horizontal bars, dividing the tube into two parts; the upper part
forming the fire-place, and the lower the ash-pit. The fuel is
maintained in a state of combustion, on the bars, in that part of the
tube represented at C D; and the flame is carried by the draft of the
chimney round the curved flue, and issues at E into the chimney.
The flame is thus conducted through the water, so as to expose the
latter to as much heat as possible.

A section of the cylinder is represented at F, immersed in the


boiler, except a few inches of the upper end, where the four-way
cock G is placed for regulating the admission of the steam. A tube is
represented at H, which leads from this four-way cock into the
chimney; so that the waste steam, after working the piston, is
carried off through this tube, and passes into the chimney. The
upper end of the piston-rod is furnished with a cross-bar, which is
placed in a direction at right angles to the length of the boiler, and
also to the piston-rod. This bar is guided in its motion by sliding on
two iron perpendicular rods fixed to the sides of the boiler, and
parallel to each other. To the ends of this cross-bar are joined two
connecting rods, the lower ends of which work two cranks fixed on
an axis extending across and beneath the boiler, and immediately
under the centre of the cylinder. This axis is sustained in bearings
formed in the legs which support the boiler, and upon its extremity is
fixed the fly-wheel as represented at B. A large-toothed wheel is
placed on this axis; which, being turned with the cranked axle,
communicates motion to other wheels; and, through them, to any
machinery which the engine may be applied to move.

As the four-way cock is represented in the figure, the steam


passes from the boiler through the curved passage G above the
piston, while the steam below the piston is carried off through a
tube which does not appear in the figure, by which it is conducted to
the tube H, and thence to the chimney. The steam, therefore, which
passes above the piston presses it downwards; while the pressure
upwards does not exceed that of the atmosphere. The piston will
therefore descend with a force depending on the excess of the
pressure of the steam produced in the boiler above the atmospheric
pressure. When the piston has arrived at the bottom of the cylinder,
the cock is made to assume the position represented in the figure
52. This effect is produced by the motion of the piston-rod. The
steam now passes from above the piston, through the tube H, into
the chimney, while the steam from the boiler is conducted through
another tube below the piston. The pressure above the piston, in
this case, does not exceed that of the atmosphere; while the
pressure below it will be that of the steam in the boiler. The piston
will therefore ascend with the difference of these pressures. On the
arrival of the piston at the top of the cylinder, the four-way cock is
again turned to the position represented in fig. 51., and the piston
again descends; and in the same manner the process is continued. A
safety-valve is placed on the boiler at V, loaded with a weight W,
proportionate to the strength of the steam with which it is proposed
to work.

Pl. XI.
Engr. by P. Maverick

In the engines now described, this valve was frequently loaded at


the rate of from 60 to 80 lbs. on the square inch. As the boilers of
high-pressure engines were considered more liable to accidents from
bursting than those in which steam of a lower pressure was used,
greater precautions were taken against such effects. A second
safety-valve was provided, which was not left in the power of the
engine-man. By this means he had a power to diminish the pressure
of the steam, but could not increase it beyond the limit determined
by the valve which was removed from his interference. The greatest
cause of danger, however, arose from the water in the boiler being
consumed by evaporation faster than it was supplied; and therefore
falling below the level of the tube containing the furnace. To guard
against accidents arising from this circumstance, a hole was bored in
the boiler, at a certain depth, below which the water should not be
allowed to fall; and in this hole a plug of metal was soldered with
lead, or with some other metal, which would fuse at that
temperature which would expose the boiler to danger. Thus, in the
event of the water being exhausted, so that its level would fall below
the plug, the heat of the furnace would immediately melt the solder,
and the plug would fall out, affording a vent for the steam, without
allowing the boiler to burst. The mercurial steam-gauge, already
described, was also used as an additional security. When the force of
the steam exceeded the length of the column of mercury which the
tube would contain, the mercury would be blown out, and the tube
would give vent to the steam. The water by which the boiler was
replenished was forced into it by a pump worked by the engine. In
order to economise the heat, this water was contained in a tube T,
which surrounded the pipe H. As the waste steam, after working the
piston, passed off through H, it imparted a portion of its heat to the
water contained in the tube T, which was thus warmed to a certain
temperature before it was forced into the boiler by the pump. Thus a
part of the heat, which was originally carried from the boiler in the
form of steam, was returned again to the boiler with the water with
which it was fed.

It is evident that engines constructed in this manner may be


applied to all the purposes to which the condensing engines are
applicable.

(e) To the plates of the English edition has been added one, (plate
A) representing a high-pressure engine as constructed by the West
Point Foundry in the state of New York. The principal parts will be
readily distinguished from their resemblance to the analogous parts
of a condensing engine. The condenser and air-pump of that engine,
it will be observed, are suppressed. At v x and y z are forcing-pumps
by which a supply of water is injected into the boiler at each motion
of the engine. For the four-way cock, used in the English high-
pressure engines, a slide valve at r s, is substituted, and is found to
work to much greater advantage. It is set in motion by an eccentric,
in a manner that will be more obvious from an inspection of the
plate than from any description.—A. E.

(f) A very safe and convenient boiler for a high-pressure engine


has been invented in the United States by Mr. Babcock. The boiler
consists of small tubes, into which water is flashed by a small
forcing-pump at every stroke of the engine. The tubes are kept so
hot in a furnace, as to generate steam of the required temperature,
but not hot enough to cause any risk of the decomposition of the
water. The strength of the apparatus is such, and the quantity of
water exposed to heat at one time so small, as to leave hardly any
risk of danger.—A. E.

(83.) Two years after the date of the patent of this engine, its
inventor constructed a machine of the same kind for the purpose of
moving carriages on railroads; and applied it successfully, in the year
1804, on the railroad at Merthyr Tydvil, in South Wales. It was in
principle the same as that already described. The cylinder however
was in a horizontal position, the piston-rod working in the direction
of the line of road: the extremity of the piston-rod, by means of a
connecting rod, worked cranks placed on the axletree, on which
were fixed two cogged wheels: these worked in others, by which
their motion was communicated finally to cogged wheels fixed on
the axle of the hind wheels of the carriage, by which this axle was
kept in a state of revolution. The hind wheels being fixed on the
axletree, and turning with it, were caused likewise to revolve; and so
long as the weight of the carriage did not exceed that which the
friction of the road was capable of propelling, the carriage would
thus be moved forwards. On this axle was placed a fly-wheel to
continue the rotatory motion at the termination of each stroke. The
fore wheels are described as being capable of turning like the fore
wheels of a carriage, so as to guide the vehicle. The projectors
appear to have contemplated, in the first instance, the use of this
carriage on turnpike roads; but that notion seems to have been
abandoned, and its use was only adopted on the railroad before
mentioned. On the occasion of its first trial, it drew after it as many
carriages as contained 10 tons of iron a distance of nine miles;
which stage it performed without any fresh supply of water, and
travelled at the rate of five miles an hour.

(84.) Capital and skill have of late years been directed with
extraordinary energy to the improvement of inland transport; and
this important instrument of national wealth and civilisation has
received a proportionate impulse. Effects are now witnessed, which,
had they been narrated a few years since, could only have been
admitted into the pages of fiction or volumes of romance. Who could
have credited the possibility of a ponderous engine of iron, loaded
with several hundred passengers, in a train of carriages of
corresponding magnitude, and a large quantity of water and coal,
taking flight from Manchester and arriving at Liverpool, a distance of
about thirty miles, in little more than an hour? And yet this is a
matter of daily and almost hourly occurrence. Neither is the road, on
which this wondrous performance is effected, the most favourable
which could be constructed for such machines. It is subject to
undulations and acclivities, which reduce the rate of speed much
more than similar inequalities affect the velocity on common roads.
The rapidity of transport thus attained is not less wonderful than the
weights transported. Its capabilities in this respect far transcend the
exigencies even of the two greatest commercial marts in Great
Britain. Loads, varying from 50 to 150 tons are transported at the
average rate of 15 miles an hour; but the engines in this case are
loaded below their power; and in one instance we have seen a load
—we should rather say a cargo—of wagons, conveying merchandise
to the amount of 230 tons gross, transported from Liverpool to
Manchester at the average rate of 12 miles an hour.
The astonishment with which such performances must be viewed,
might be qualified, if the art of transport by steam on railways had
been matured, and had attained that full state of perfection which
such an art is always capable of receiving from long experience,
aided by great scientific knowledge, and the unbounded application
of capital. But such is not the present case. The art of constructing
locomotive engines, so far from having attained a state of maturity,
has not even emerged from its infancy. So complete was the
ignorance of its powers which prevailed, even among engineers,
previous to the opening of the Liverpool railway, that the transport of
heavy goods was regarded as the chief object of the undertaking,
and its principal source of revenue. The incredible speed of
transport, effected even in the very first experiments in 1830, burst
upon the public, and on the scientific world, with all the effect of a
new and unlooked-for phenomenon. On the unfortunate occasion
which deprived this country of Mr. Huskisson, the wounded body of
that statesman was transported a distance of about fifteen miles in
twenty-five minutes, being at the rate of thirty-six miles an hour. The
revenue of the road arising from passengers since its opening, has,
contrary to all that was foreseen, been nearly double that which has
been derived from merchandise. So great was the want of
experience in the construction of engines, that the company was at
first ignorant whether they should adopt large steam-engines fixed
at different stations on the line, to pull the carriages from station to
station, or travelling engines to drag the loads the entire distance.
Having decided on the latter, they have, even to the present
moment, laboured under the disadvantage of the want of that
knowledge which experience alone can give. The engines have been
constantly varied in their weight and proportions, in their magnitude
and form, as the experience of each successive month has indicated.
As defects became manifest they were remedied; improvements
suggested were adopted; and each quarter produced engines of
such increased power and efficiency, that their predecessors were
abandoned, not because they were worn out, but because they had
been outstripped in the rapid march of improvement. Add to this,
that only one species of travelling engine has been effectively tried;
the capabilities of others remain still to be developed; and even that
form of engine which has received the advantage of a course of
experiments on so grand a scale to carry it towards perfection, is far
short of this point, and still has defects, many of which, it is obvious,
time and experience will remove. If then travelling steam engines,
with all the imperfections of an incipient invention—with the want of
experience, the great parent of practical improvements—with the
want of the common advantage of the full application of the skill and
capital of the country—subjected to but one great experiment, and
that experiment limited to one form of engine; if, under such
disadvantages, the effects to which we have referred have been
produced, what may we not expect from this extraordinary power,
when the enterprise of the country shall be unfettered, when greater
fields of experience are opened, when time, ingenuity, and capital
have removed the existing imperfections, and have brought to light
new and more powerful principles? This is not mere speculation on
possibilities, but refers to what is in a state of actual progression.
Railways are in progress between the points of greatest intercourse
in the United Kingdom, and travelling steam engines are in
preparation for the common turnpike roads; the practicability and
utility of that application of the steam engine having not only been
established by experiment to the satisfaction of their projectors, but
proved before the legislature in a committee of inquiry on the
subject.

The important commercial and political effects attending such


increased facility and speed in the transport of persons and goods,
are too obvious to require any very extended notice here. A part of
the price (and in many cases a considerable part) of every article of
necessity or luxury, consists of the cost of transporting it from the
producer to the consumer; and consequently every abatement or
saving in this cost must produce a corresponding reduction in the
price of every article transported; that is to say, of everything which
is necessary for the subsistence of the poor, or for the enjoyment of
the rich, of every comfort, and of every luxury of life. The benefit of
this will extend, not to the consumer only, but to the producer: by
lowering the expense of transport of the produce, whether of the
soil or of the loom, a less quantity of that produce will be spent in
bringing the remainder to market, and consequently a greater
surplus will reward the labour of the producer. The benefit of this will
be felt even more by the agriculturist than by the manufacturer;
because the proportional cost of transport of the produce of the soil
is greater than that of manufactures. If 200 quarters of corn be
necessary to raise 400, and 100 more be required to bring the 400
to market, then the net surplus will be 100. But if by the use of
steam carriages the same quantity can be brought to market with an
expenditure of 50 quarters, then the net surplus will be increased
from 100 to 150 quarters; and either the profit of the farmer, or the
rent of the landlord, must be increased by the same amount.

But the agriculturist would not merely be benefited by an


increased return from the soil already under cultivation. Any
reduction in the cost of transporting the produce to market would
call into cultivation tracts of inferior fertility, the returns from which
would not at present repay the cost of cultivation and transport.
Thus land would become productive which is now waste, and an
effect would be produced equivalent to adding so much fertile soil to
the present extent of the country. It is well known, that land of a
given degree of fertility will yield increased produce by the increased
application of capital and labour. By a reduction in the cost of
transport, a saving will be made which may enable the agriculturist
to apply to tracts already under cultivation the capital thus saved,
and thereby increase their actual production. Not only, therefore,
would such an effect be attended with an increased extent of
cultivated land, but also with an increased degree of cultivation in
that which is already productive.

It has been said, that in Great Britain there are above a million of
horses engaged in various ways in the transport of passengers and
goods, and that to support each horse requires as much land as
would, upon an average, support eight men. If this quantity of
animal power were displaced by steam engines, and the means of
transport drawn from the bowels of the earth, instead of being
raised upon its surface, then, supposing the above calculation
correct, as much land would become available for the support of
human beings as would suffice for an additional population of eight
millions; or, what amounts to the same, would increase the means of
support of the present population by about one-third of the present
available means. The land which now supports horses for transport
would then support men, or produce corn for food.

The objection that a quantity of land exists in the country capable


of supporting horses alone, and that such land would be thrown out
of cultivation, scarcely deserves notice here. The existence of any
considerable quantity of such land is extremely doubtful. What is the
soil which will feed a horse and not feed oxen or sheep, or produce
food for man? But even if it be admitted that there exists in the
country a small portion of such land, that portion cannot exceed, nor
indeed equal, what would be sufficient for the number of horses
which must after all continue to be employed for the purposes of
pleasure, and in a variety of cases where steam must necessarily be
inapplicable. It is to be remembered, also, that the displacing of
horses in one extensive occupation, by diminishing their price must
necessarily increase the demand for them in others.

The reduction in the cost of transport of manufactured articles, by


lowering their price in the market, will stimulate their consumption.
This observation applies of course not only to home but to foreign
markets. In the latter we already in many branches of manufacture
command a monopoly. The reduced price which we shall attain by
cheapness and facility of transport will still further extend and
increase our advantages. The necessary consequence will be, an
increased demand for manufacturing population; and this increased
population again reacting on the agricultural interests, will form an
increased market for that species of produce. So interwoven and
complicated are the fibres which form the texture of the highly
civilized and artificial community in which we live, that an effect
produced on any one point is instantly transmitted to the most
remote and apparently unconnected parts of the system.

The two advantages of increased cheapness and speed, besides


extending the amount of existing traffic, call into existence new
objects of commercial intercourse. For the same reason that the
reduced cost of transport, as we have shown, calls new soils into
cultivation, it also calls into existence new markets for manufactured
and agricultural produce. The great speed of transit which has been
proved to be practicable, must open a commerce between distant
points in various articles, the nature of which does not permit them
to be preserved so as to be fit for use beyond a certain time. Such
are, for example, many species of vegetable and animal food, which
at present are confined to markets at a very limited distance from
the grower or feeder. The truth of this observation is manifested by
the effects which have followed the intercourse by steam on the
Irish Channel. The western towns of England have become markets
for a prodigious quantity of Irish produce, which it had been
previously impossible to export. If animal food be transported alive
from the grower to the consumer, the distance of the market is
limited by the power of the animal to travel, and the cost of its
support on the road. It is only particular species of cattle which bear
to be carried to market on common roads and by horse carriages.
But the peculiar nature of a railway, the magnitude and weight of
the loads which may be transported on it, and the prodigious speed
which may be attained, render the transport of cattle, of every
species, to almost any distance, both easy and cheap. In process of
time, when the railway system becomes extended, the metropolis
and populous towns will therefore become markets, not as at
present to districts within limited distances of them, but to the whole
country.

The moral and political consequences of so great a change in the


powers of transition of persons and intelligence from place to place
are not easily calculated. The concentration of mind and exertion
which a great metropolis always exhibits, will be extended in a
considerable degree to the whole realm. The same effect will be
produced as if all distances were lessened in the proportion in which
the speed and cheapness of transit are increased. Towns, at present
removed some stages from the metropolis, will become its suburbs;
others, now a day's journey, will be removed to its immediate
vicinity; business will be carried on with as much ease between them
and the metropolis, as it is now between distant points of the
metropolis itself. Let those who discard speculations like these as
wild and improbable, recur to the state of public opinion, at no very
remote period, on the subject of steam navigation. Within the
memory of persons who have not yet passed the meridian of life,
the possibility of traversing by the steam engine the channels and
seas that surround and intersect these islands, was regarded as the
dream of enthusiasts. Nautical men and men of science rejected
such speculations with equal incredulity, and with little less than
scorn for the understanding of those who could for a moment
entertain them. Yet we have witnessed steam engines traversing not
these channels and seas alone, but sweeping the face of the waters
round every coast in Europe. The seas which interpose between our
Asiatic dominions and Egypt, and those which separate our own
shores from our West Indian possessions, have offered an equally
ineffectual barrier to its powers. Nor have the terrors of the Pacific
prevented the "Enterprise" from doubling the Cape, and reaching the
shores of India. If steam be not used as the only means of
connecting the most distant points of our planet, it is not because it
is inadequate to the accomplishment of that end, but because the
supply of the material from which at the present moment it derives
its powers, is restricted by local and accidental circumstances.[24]

We propose in the present chapter to lay before our readers some


account of the means whereby the effects above referred to have
been produced; of the manner and degree in which the public have
availed themselves of these means; and of the improvements of
which they seem to us to be susceptible.
(85.) It is a singular fact, that in the history of this invention
considerable time and great ingenuity were vainly expended in
attempting to overcome a difficulty, which in the end turned out to
be purely imaginary. To comprehend distinctly the manner in which a
wheel carriage is propelled by steam, suppose that a pin or handle is
attached to the spoke of the wheel at some distance from its centre,
and that a force is applied to this pin in such a manner as to make
the wheel revolve. If the face of the wheel and the surface of the
road were absolutely smooth and free from friction, so that the face
of the wheel would slide without resistance upon the road, then the
effect of the force thus applied would be merely to cause the wheel
to turn round, the carriage being stationary, the surface of the wheel
would slip or slide upon the road as the wheel is made to revolve.
But if, on the other hand, the pressure of the face of the wheel upon
the road is such as to produce between them such a degree of
adhesion as will render it impossible for the wheel to slide or slip
upon the road by the force which is applied to it, the consequence
will be, that the wheel can only turn round in obedience to the force
which moves it by causing the carriage to advance, so that the
wheel will roll upon the road, and the carriage will be moved
forward, through a distance equal to the circumference of the wheel,
each time it performs a complete revolution.

It is obvious that both of these effects may be partially produced;


the adhesion of the wheel to the road may be insufficient to prevent
slipping altogether, and yet it may be sufficient to prevent the wheel
from slipping as fast as it revolves. Under such circumstances the
carriage would advance and the wheel would slip. The progressive
motion of the carriage during one complete revolution of the wheel
would be equal to the difference between the complete
circumference of the wheel and the portion through which in one
revolution it has slipped.

When the construction of travelling steam engines first engaged


the attention of engineers, and for a considerable period afterwards,
a notion was impressed upon their minds that the adhesion between
the face of the wheel and the surface of the road must necessarily
be of very small amount, and that in every practical case the wheels
thus driven would either slip altogether, and produce no advance of
the carriage, or that a considerable portion of the impelling power
would be lost by the partial slipping or sliding of the wheels. It is
singular that it should never have occurred to the many ingenious
persons who for several years were engaged in such experiments
and speculations, to ascertain by experiment the actual amount of
adhesion in any particular case between the wheels and the road.
Had they done so, we should probably now have found locomotive
engines in a more advanced state than that to which they have
attained.

To remedy this imaginary difficulty, Messrs. Trevithick and Vivian


proposed to make the external rims of the wheels rough and
uneven, by surrounding them with projecting heads of nails or bolts,
or by cutting transverse grooves on them. They proposed, in cases
where considerable elevations were to be ascended, to cause claws
or nails to project from the surface during the ascent, so as to take
hold of the road.

In seven years after the construction of the first locomotive engine


by these engineers, another locomotive engine was constructed by
Mr. Blinkensop, of Middleton Colliery, near Leeds. He obtained a
patent, in 1811, for the application of a rack-rail. The railroad thus,
instead of being composed of smooth bars of iron, presented a line
of projecting teeth, like those of a cog-wheel, which stretched along
the entire distance to be travelled. The wheels on which the engine
rolled were furnished with corresponding teeth, which worked in the
teeth of the railroad; and, in this way, produced a progressive
motion in the carriage.

The next contrivance for overcoming this fictitious difficulty, was


that of Messrs. Chapman, who, in the year 1812, obtained a patent
for working a locomotive engine by a chain extending along the
middle of the line of railroad, from the one end to the other. This
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookmasss.com

You might also like