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

PDF Get Programming with JavaScript 1st Edition John R Larsen download

The document provides information about the book 'Get Programming with JavaScript' by John R. Larsen, which includes a structured approach to learning JavaScript through the development of a text-based adventure game called The Crypt. It outlines various programming concepts such as variables, objects, functions, and arrays, along with their applications in the game. Additionally, it includes links to other related ebooks available for download on ebookmeta.com.

Uploaded by

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

PDF Get Programming with JavaScript 1st Edition John R Larsen download

The document provides information about the book 'Get Programming with JavaScript' by John R. Larsen, which includes a structured approach to learning JavaScript through the development of a text-based adventure game called The Crypt. It outlines various programming concepts such as variables, objects, functions, and arrays, along with their applications in the game. Additionally, it includes links to other related ebooks available for download on ebookmeta.com.

Uploaded by

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

Download Full Version ebook - Visit ebookmeta.

com

Get Programming with JavaScript 1st Edition John R


Larsen

https://ebookmeta.com/product/get-programming-with-
javascript-1st-edition-john-r-larsen-3/

OR CLICK HERE

DOWLOAD NOW

Discover More Ebook - Explore Now at ebookmeta.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

Get Programming with JavaScript 1st Edition John R Larsen

https://ebookmeta.com/product/get-programming-with-javascript-1st-
edition-john-r-larsen-3/

ebookmeta.com

Get Programming with JavaScript 1st Edition John R Larsen

https://ebookmeta.com/product/get-programming-with-javascript-1st-
edition-john-r-larsen/

ebookmeta.com

Reactive Programming with JavaScript 1st Edition Jonathan


Hayward

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

ebookmeta.com

Astronomy magazine - vol. 51 ■ 5 [May 2023] Astronomy


Magazine

https://ebookmeta.com/product/astronomy-magazine-
vol-51-%e2%84%96-5-may-2023-astronomy-magazine/

ebookmeta.com
Data-Enabled Analytics: DEA for Big Data Joe Zhu

https://ebookmeta.com/product/data-enabled-analytics-dea-for-big-data-
joe-zhu/

ebookmeta.com

Land of Lisp Learn to Program in Lisp One Game at a Time


1st Edition Conrad Barski

https://ebookmeta.com/product/land-of-lisp-learn-to-program-in-lisp-
one-game-at-a-time-1st-edition-conrad-barski/

ebookmeta.com

From Hell Master Edition Alan Moore

https://ebookmeta.com/product/from-hell-master-edition-alan-moore/

ebookmeta.com

Rainwater Harvesting for Drylands and Beyond Volume 2 2nd


Edition Water Harvesting Earthworks Brad Lancaster

https://ebookmeta.com/product/rainwater-harvesting-for-drylands-and-
beyond-volume-2-2nd-edition-water-harvesting-earthworks-brad-
lancaster/
ebookmeta.com

Four-Color Communism. Comic Books and Contested Power in


the German Democratic Republic 1st Edition Sean Eedy

https://ebookmeta.com/product/four-color-communism-comic-books-and-
contested-power-in-the-german-democratic-republic-1st-edition-sean-
eedy/
ebookmeta.com
Entrepreneurship with Microorganisms 1st Edition Amritesh
C. Shukla

https://ebookmeta.com/product/entrepreneurship-with-
microorganisms-1st-edition-amritesh-c-shukla/

ebookmeta.com
The Crypt: a running example

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

Game element Task JavaScript Chapter

Players Deciding what information you need to Variables 2


know about each player

Collecting player information in one place Objects 3

Displaying information about players on Functions 4–7


the console

Creating a list of items collected by each Arrays 8


player

Organizing player-creation code Constructors 9

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


a similar structure

Joining places with exits Square bracket notation 10

Game Adding simple functions for movement, Square bracket notation 10


collecting items, and displaying informa-
tion

Maps Joining places with exits Square bracket notation 10


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

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

©2016 by Manning Publications Co. All rights reserved.

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


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

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

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

Manning Publications Co. Development editor: Helen Stergius


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

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

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


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

v
vi BRIEF CONTENTS

15 ■ Views: displaying data 264


16 ■ Controllers: linking models and views 280

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


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

22 ■ Node: running JavaScript outside the browser online


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

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

1 Programming, JavaScript, and JS Bin 3


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

Logging to the console 8 Code comments 9 Further


■ ■

Adventures 9 Error messages 9 Line numbers 10


■ ■

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

vii
viii CONTENTS

2 Variables: storing data in your program 16


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

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

its own assignment 21


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

variables 23 camelCase 23 Use descriptive


■ ■

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

3 Objects: grouping your data 27


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

weather like? 36 The testing effect 37 Create your own


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

4 Functions: code on demand 40


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

function declarations 45 Using functions 46


Functions step by step 47


4.3 Reducing repetition 48
A function for displaying object properties as text 48
Functions for adding tax and displaying a summary 50
CONTENTS ix

4.4 Making code easier to read and update 52


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

5 Arguments: passing data to functions 57


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

Displaying players’ locations 67 Putting it all together—


displaying players’ information 68


5.4 Summary 69

6 Return values: getting data from functions 70


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

keyword 72 Using arguments to determine the return value



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

7 Object arguments: functions working with objects 83


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

7.3 Methods—setting functions as properties of objects 91


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

for your namespace 96 Deep namespace exploration 98


7.4 The Crypt–player objects as arguments 101


7.5 Summary 102

8 Arrays: putting data into lists 104


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

arrays 111 Visiting each element with forEach 113


8.3 The Crypt—a player items array 118


8.4 Summary 120

9 Constructors: building objects with functions 122


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

into methods 143 Assigning places to players 144


Using null as a placeholder for objects 144


9.6 Summary 145

10 Bracket notation: flexible property names 147


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

10.2 The Crypt—enhancing exit excitement 155


Using an object to hold the exits 156 Creating functions to

add and display exits 158 Giving each place object its own

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

constructor 161 Testing the Place constructor 163


10.3 The Crypt—let the games begin! 164


Updating the display—render 165 Exploring the

map—go 166 Collecting all the things—get 166


Designing a bigger adventure—Jahver’s ship 167


10.4 What’s next? 167
10.5 Summary 167

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

11 Scope: hiding information 171


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

relying on an implementation 174 Naming collisions 176


Crazy bugs 177


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

independent counters with getCount 181 Creating multiple


independent counters with a constructor function 182


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

12 Conditions: choosing code to run 198


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

200
The else clause 200 Hide the secret number inside a

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

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

answer 214 Returning the interface object 214


12.5 The Crypt—checking user input 214


Step by step through the go method 215 Never trust ■

user input 216 Safe exploration—using the if statement


to avoid problems 217


12.6 Summary 219

13 Modules: breaking a program into pieces 221


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

of the filename 225 ■


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

13.6 Immediately invoked function expressions (IIFE) 238


Recognizing function expressions 240 Invoking functions 240

Immediately invoking function expressions 241 Returning ■

information from an IIFE 241


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

14 Models: working with data


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

249

data as a JavaScript object 251 Converting the data into


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

14.2 The Crypt—separating map data from the game 253


Map data 255 Adding challenges to the map data 256

Updating the Place constructor to include challenges 258


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

the pieces together to run the game 262


14.3 Summary 263

15 Views: displaying data 264


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

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

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

16 Controllers: linking models and views 280


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

controller 282 Putting the pieces together for a working


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

16.2 The Crypt—adding a game controller 284


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

16.3 The Crypt—the structure of the controller code 287


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

Updating the display—functions that use the view modules 289


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

of a challenge 291 Moving with game.go 292


Licking the leopard with game.use 294


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

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

17 HTML: building web pages 301


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

Marking up a list 306 Some common HTML elements 307


17.3 Adding content to a web page with JavaScript 309


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

the listings 317 Using JavaScript’s strict mode 318


Loading modules and adding placeholders in the HTML 318


Adding a touch of CSS 319 Playing the game 320

Preparing the message view 320


17.6 Summary 321

18 Controls: getting user input 323


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

greeting 325 Listening for clicks 325



CONTENTS xv

18.2 Using a select element to choose an option 327


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

list to display the comments 332 Getting references to the


new elements 332 Updating the rateMovie function 332


Styling the examples with CSS 334


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

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


and shift 336 Deciding between options with switch 338


Making it so—listening for button clicks 339


Enter The Crypt 340
18.5 Summary 341

19 Templates: filling placeholders with data 343


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

the HTML by string concatenation 345 Designing with HTML


templates 346 Using script tags for templates 346


19.2 Replacing one string with another 347


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

loop 351 Replacing a string while it can be found 352


Replacing strings with regular expressions 353


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

of items using a template 355


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

views to use the new templates 362 Enter The Crypt 365

19.7 Summary 365


xvi CONTENTS

20 XHR: loading data 367


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

368

Loading the user data—the XMLHttpRequest constructor 370


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

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


20.2 JSON—a simple data format 377


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

each place only once 380 Replacing the Map Data and Map

Builder modules with Map Manager 380 Updating the game■

controller to use the Map Manager 383 Building the game


page 384 Enter The Crypt 386


20.4 Summary 386

21 Conclusion: get programming with JavaScript 387


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

in a browser 390 ■ Concatenating and minifying files 390


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

22 Node: running JavaScript outside the browser


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

23 Express: building an API


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

24 Polling: repeating requests with XHR


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

25 Socket.IO: real-time messaging


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

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

xvii
xviii FOREWORD

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

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

xix
xx PREFACE

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

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

Who should read this book


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

xxii
ABOUT THIS BOOK xxiii

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

Having covered some key, core concepts in part 1, you learn how to better organize
your code in part 2:
■ Chapter 11 discusses the dangers of global variables, variables that can be seen
throughout a program, and the benefits of local variables, variables defined
inside functions. Along the way, you consider who might use your code and the
difference between an interface and an implementation.
■ If you want to find out about conditions, then chapter 12 is the place to go. Only
executing code if a condition is met adds flexibility to your programs and lets
you check input from users before using it.
■ As your programs grow, it usually makes sense to organize the pieces that make
them up into modules, separate files that can be combined and swapped to
improve versatility, focus, portability, and maintainability. Chapter 13 considers
ways of modularizing your code, including namespaces and the snappily titled
immediately invoked function expressions.
■ Having learned techniques for creating modules, in chapters 14, 15, and 16 you
see three different roles that modules might play. Models help you work with
data (calendar events, blog posts, or movie reviews, for example); views present
that data to the user (as text, HTML, or a graph, for example); and controllers
work with the models and views, responding to user actions and updating the
models before passing them to the views for display.
Part 3 covers using JavaScript to update web pages and respond to user input via but-
tons, drop-down lists, and text boxes. It also introduces templates for displaying repet-
itive, dynamic data, and techniques for loading that data into an existing page:
■ Chapter 17 has a brief introduction to HyperText Markup Language (HTML), a
way of specifying the structure of your content in a web page (headings, para-
graphs, or list items, for example) and of loading further resources like images,
videos, scripts, and style sheets. It then shows how you can use JavaScript to
access and update a page’s content.
■ In order to capture user input, you need to use HTML controls, like buttons,
drop-down lists, and text boxes. Chapter 18 demonstrates how to set up code
that can work with user input and that the program executes when a user clicks
a button.
■ Templates offer a way to design the presentation of data by using placeholders. In
chapter 19 you learn how to include HTML templates in a page and replace
their placeholders with data. You avoid the confusing mess of JavaScript, HTML,
and data all mixed together and create a neat, clear way of populating a web
page with nicely formatted information.
■ Chapter 20 explains how to load further data into a web page by using
XMLHttpRequest objects. Commonly referred to as Ajax, the techniques let you
update parts of a page with fresh data in response to user actions, leading to
more responsive applications.
ABOUT THIS BOOK xxv

■ Chapter 21 wraps up everything in the printed book, discussing text editors and
integrated development environments and how to organize your own files when
creating projects away from JS Bin. It also suggests sources of further learning
about JavaScript and wishes you well on your programming adventures.
Chapters 22–25 are available online only, at www.manning.com/books/get-programming-
with-javascript. They’re more advanced and cover programming on the server with
Node.js and Express.js, polling the server with XHR, and real-time communication with
Socket.IO.

About the code


This book contains many examples of source code both in numbered listings and in
line with normal text. In both cases, source code is formatted in a fixed-width font
like this to separate it from ordinary text. Sometimes code is also in bold to high-
light code that has changed from previous steps in the chapter, such as when a new
feature adds to an existing line of code.
In many cases, the original source code has been reformatted; we’ve added line
breaks and reworked indentation to accommodate the available page space in the
book. In rare cases, even this was not enough, and listings include line-continuation
markers (➥). Additionally, comments in the source code have often been removed
from the listings when the code is described in the text. Code annotations accompany
many of the listings, highlighting important concepts.
Most of the code listings in the book include a link to the same code on the JS Bin
website, where you can run the code and experiment with it. The code is also available
on GitHub at https://github.com/jrlarsen/getprogramming and on the book’s Man-
ning.com page at www.manning.com/books/get-programming-with-javascript.

Other online resources


The book’s website at www.room51.co.uk/books/getprogramming/index.html includes
answers to many of the book’s exercises as well as video tutorials, further articles and
guides for learning JavaScript, and links to other resources on the Internet.

About the author


John Larsen is a mathematics and computing teacher with an interest in educational
research. He has an MA in mathematics and an MSc in information technology. He
started programming in 1982, writing simple programs for teaching mathematics in
1993, building websites in 2001, and developing data-driven web-based applications
for education in 2006.

Author Online
Purchase of Get Programming with JavaScript includes free access to a private web forum
run by Manning Publications where you can make comments about the book, ask
technical questions, and receive help from the author and from other users. To access
xxvi ABOUT THIS BOOK

the forum and subscribe to it, point your web browser to www.manning.com/books/
get-programming-with-javascript. This page provides information on how to get on
the forum once you are registered, what kind of help is available, and the rules of con-
duct on the forum.
Manning’s commitment to our readers is to provide a venue where a meaningful
dialog between individual readers and between readers and the author can take place.
It is not a commitment to any specific amount of participation on the part of the
author, whose contribution to the Author Online remains voluntary (and unpaid). We
suggest you try asking the author some challenging questions lest his interest stray!
The Author Online forum and the archives of previous discussions will be accessible
from the publisher’s website as long as the book is in print.
Part 1

Core concepts
on the console

G et Programming with JavaScript starts by introducing the key concepts you


use in every program. The ideas presented form the foundation for all the subse-
quent code you write. The discussion starts gently and takes its time, with plenty
of examples. There is an overarching theme of organization, which runs through-
out the book; you see how to store and retrieve values with variables, group val-
ues with objects and arrays, and group instructions with functions.
By the end of part 1, you’ll have built a working version of an adventure game
called The Crypt. Players will be able to explore a map of locations and move from
room to room and tomb to tomb, collecting treasure. Chapter 1 sets the scene,
introducing programming, JavaScript, and JS Bin, the online code environment in
which your adventures take place. Let the games begin!
Random documents with unrelated
content Scribd suggests to you:
been wont to wander through space, and from aloft in the upper air
to look down with contempt upon human affairs. Hence it is that
Plato declares that the wise man’s mind is entirely given up to death,
longs for it, contemplates it, and through his eagerness for it is
always striving after things which lie beyond this life. Why, Marcia,
when you saw him while yet young displaying the wisdom of age,
with a mind that could rise superior to all sensual enjoyments,
faultless and without a blemish, able to win riches without
greediness, public office without ambition, pleasure without
extravagance, did you suppose it would long be your lot to keep him
safe by your side? Whatever has arrived at perfection, is ripe for
dissolution. Consummate virtue flees away and betakes itself out of
our sight, and those things which come to maturity in the first stage
of their being do not wait for the last. The brighter a fire glows, the
sooner it goes out: it lasts longer when it is made up with bad and
slowly burning fuel, and shows a dull light through a cloud of smoke:
its being poorly fed makes it linger all the longer. So also the more
brilliant men’s minds, the shorter lived they are: for when there is no
room for further growth, the end is near. Fabianus tells us, what our
parents themselves have seen, that there was at Rome a boy of
gigantic stature, exceeding that of a man: but he soon died, and
every sensible person always said that he would soon die, for he
could not live to reach the age which he had assumed before it was
due. So it is: too complete maturity is a proof that destruction is
near, and the end approaches when growth is over.

XXIV. Begin to reckon his age, not by years, but by virtues: he lived
long enough. He was left as a ward in the care of guardians up to
his fourteenth year, and never passed out of that of his mother:
when he had a household of his own he was loth to leave yours, and
continued to dwell under his mother’s roof, though few sons can
endure to live under their father’s. Though a youth whose height,
beauty, and vigour of body destined him for the army, yet he refused
to serve, that he might not be separated from you. Consider, Marcia,
how seldom mothers who live in separate houses see their children:
consider how they lose and pass in anxiety all those years during
which they have sons in the army, and you will see that this time,
none of which you lost, was of considerable extent: he never went
out of your sight: it was under your eyes that he applied himself to
the cultivation of an admirable intellect and one which would have
rivalled that of his grandfather, had it not been hindered by shyness,
which has concealed many men’s accomplishments: though a youth
of unusual beauty, and living among such throngs of women who
made it their business to seduce men, he gratified the wishes of
none of them, and when the effrontery of some led them so far as
actually to tempt him, he blushed as deeply at having found favour
in their eyes as though he had been guilty. By this holiness of life he
caused himself, while yet quite a boy, to be thought worthy of the
priesthood, which no doubt he owed to his mother’s influence; but
even his mother’s influence would have had no weight if the
candidate for whom it was exerted had been unfit for the post. Dwell
upon these virtues, and nurse your son as it were in your lap: now
he is more at leisure to respond to your caresses, he has nothing to
call him away from you, he will never be an anxiety or a sorrow to
you. You have grieved at the only grief so good a son could cause
you: all else is beyond the power of fortune to harm, and is full of
pleasure, if only you know how to make use of your son, if you do
but know what his most precious quality was. It is merely the
outward semblance of your son that has perished, his likeness, and
that not a very good one; he himself is immortal, and is now in a far
better state, set free from the burden of all that was not his own,
and left simply by himself: all this apparatus which you see about us
of bones and sinews, this covering of skin, this face, these our
servants the hands, and all the rest of our environment, are but
chains and darkness to the soul: they overwhelm it, choke it, corrupt
it, fill it with false ideas, and keep it at a distance from its own true
sphere: it has to struggle continually against this burden of the flesh,
lest it be dragged down and sunk by it. It ever strives to rise up
again to the place from whence it was sent down on earth: there
eternal rest awaits it, there it will behold what is pure and clear, in
place of what is foul and turbid.
XXV. You need not, therefore, hasten to the burial-place of your son:
that which lies there is but the worst part of him and that which
gave him most trouble, only bones and ashes, which are no more
parts of him than clothes or other coverings of his body. He is
complete, and without leaving any part of himself behind on earth
has taken wing and gone away altogether: he has tarried a brief
space above us while his soul was being cleansed and purified from
the vices and rust which all mortal lives must contract, and from
thence he will rise to the high heavens and join the souls of the
blessed: a saintly company will welcome him thither,—Scipios and
Catos; and among the rest of those who have held life cheap and set
themselves free, thanks to death, albeit all there are alike akin, your
father, Marcia, will embrace his grandson as he rejoices in the
unwonted light, will teach him the motion of the stars which are so
near to them, and introduce him with joy into all the secrets of
nature, not by guesswork but by real knowledge. Even as a stranger
is grateful to one who shows him the way about an unknown city, so
is a searcher after the causes of what he sees in the heavens to one
of his own family who can explain them to him. He will delight in
gazing deep down upon the earth, for it is a delight to look from
aloft at what one has left below. Bear yourself, therefore, Marcia, as
though you were placed before the eyes of your father and your son,
yet not such as you knew them, but far loftier beings, placed in a
higher sphere. Blush, then, to do any mean or common action, or to
weep for those your relatives who have been changed for the better.
Free to roam through the open, boundless realms of the everliving
universe, they are not hindered in their course by intervening seas,
lofty mountains, impassable valleys, or the treacherous fiats of the
Syrtes: they find a level path everywhere, are swift and ready of
motion, and are permeated in their turn by the stars and dwell
together with them.

XXVI. Imagine then, Marcia, that your father, whose influence over
you was as great as yours over your son, no longer in that frame of
mind in which he deplored the civil wars, or in which he for ever
proscribed those who would have proscribed him, but in a mood as
much more joyful as his abode now is higher than of old, is saying,
as he looks down from the height of heaven, “My daughter, why
does this sorrow possess you for so long? why do you live in such
ignorance of the truth, as to think that your son has been unfairly
dealt with because he has returned to his ancestors in his prime,
without decay of body or mind, leaving his family flourishing? Do you
not know with what storms Fortune unsettles everything? how she
proves kind and compliant to none save to those who have the
fewest possible dealings with her? Need I remind you of kings who
would have been the happiest of mortals had death sooner
withdrawn them from the ruin which was approaching them? or of
Roman generals, whose greatness, had but a few years been taken
from their lives, would have wanted nothing to render it complete?
or of men of the highest distinction and noblest birth who have
calmly offered their necks to the stroke of a soldier’s sword? Look at
your father and your grandfather: the former fell into the hands of a
foreign murderer: I allowed no man to take any liberties with me,
and by abstinence from food showed that my spirit was as great as
my writings had represented it. Why, then, should that member of
our household who died most happily of all be mourned in it the
longest? We have all assembled together, and, not being plunged in
utter darkness, we see that with you on earth there is nothing to be
wished for, nothing grand or magnificent, but all is mean, sad,
anxious, and hardly receives a fractional part of the clear light in
which we dwell. I need not say that here are no frantic charges of
rival armies, no fleets shattering one another, no parricides, actual or
meditated, no courts where men babble over lawsuits for days
together, here is nothing underhand, all hearts and minds are open
and unveiled, our life is public and known to all, and that we
command a view of all time and of things to come. I used to take
pleasure in compiling the history of what took place in one century
among a few people in the most out-of-the-way corner of the world:
here I enjoy the spectacle of all the centuries, the whole chain of
events from age to age as long as years have been. I may view
kingdoms when they rise and when they fall, and behold the ruin of
cities and the new channels made by the sea. If it will be any
consolation to you in your bereavement to know that it is the
common lot of all, be assured that nothing will continue to stand in
the place in which it now stands, but that time will lay everything
low and bear it away with itself: it will sport, not only with men—for
how small a part are they of the dominion of Fortune? —but with
districts, provinces, quarters of the world: it will efface entire
mountains, and in other places will pile new rocks on high: it will dry
up seas, change the course of rivers, destroy the intercourse of
nation with nation, and break up the communion and fellowship of
the human race: in other regions it will swallow up cities by opening
vast chasms in the earth, will shake them with earthquakes, will
breathe forth pestilence from the nether world, cover all habitable
ground with inundations and destroy every creature in the flooded
world, or burn up all mortals by a huge conflagration. When the time
shall arrive for the world to be brought to an end, that it may begin
its life anew, all the forces of nature will perish in conflict with one
another, the stars will be dashed together, and all the lights which
now gleam in regular order in various parts of the sky will then blaze
in one fire with all their fuel burning at once. Then we also, the souls
of the blest and the heirs of eternal life, whenever God thinks fit to
reconstruct the universe, when all things are settling down again, we
also, being a small accessory to the universal wreck,[13] shall be
changed into our old elements. Happy is your son, Marcia, in that he
already knows this.”

[1] See Merivale’s “History of the Romans under the Empire,” ch. xlv.

[2] If it is a pain to dwell upon the thought of lost friends, of course you do not
continually refresh the memory of them by speaking of them.

[3] See my note on invidiam facere alicui in Juv. 15.—J. E. B. Mayor.

[4] Koch declares that this cannot be the true reading, and suggests deminutio,
‘degradation.’

[5] This seems to have been part of the ceremony of dedication. Pulvillus was
dedicating the Temple of Jupiter in the Capitol. See Livy, ii. 8; Cic. Pro Domo,
paragraph cxxi.

[6] Lucius Aemilius Paullus conquered Perses, the last King of Macedonia, B.C.
168.

[7] “For he had four sons, two, as has been already related, adopted into other
families, Scipio and Fabius; and two others, who were still children, by his second
wife, who lived in his own house. Of these, one died five days before Aemilius’s
triumph, at the age of fourteen, and the other, twelve years old, died three days
after it: so that there was no Roman that did not grieve for him,” &c.—Plutarch,
“Life of Aemilius,” ch. xxxv.

[8] A. U. C. 695, B.C 59.

[9] Virg. Ae. III. 418.

[10] See Mayor’s note on Juv. i., and above, c. 16, § 4.

[11] Lipsius points out that this idea is borrowed from the comic poet Antiphanes.
See Meineke’s “Comic Fragments,” p. 3.

[12] This I believe to be the meaning of the text, but Koch reasonably conjectures
that the true reading is “editur subscriptio,” “an indictment was made out against
him.” See “On Benefits,” iii. 26.

[13] Ruinae; Koch’s urinae is a misprint.


THE SEVENTH BOOK OF THE DIALOGUES
OF L. ANNAEUS SENECA,
ADDRESSED TO GALLIO.
OF A HAPPY LIFE.

I. All men, brother Gallio, wish to live happily, but are dull at
perceiving exactly what it is that makes life happy: and so far is it
from being easy to attain to happiness that the more eagerly a man
struggles to reach it the further he departs from it, if he takes the
wrong road; for, since this leads in the opposite direction, his very
swiftness carries him all the further away. We must therefore first
define clearly what it is at which we aim: next we must consider by
what path we may most speedily reach it, for on our journey itself,
provided it be made in the right direction, we shall learn how much
progress we have made each day, and how much nearer we are to
the goal towards which our natural desires urge us. But as long as
we wander at random, not following any guide except the shouts
and discordant clamours of those who invite us to proceed in
different directions, our short life will be wasted in useless roamings,
even if we labour both day and night to get a good understanding.
Let us not therefore decide whither we must tend, and by what
path, without the advice of some experienced person who has
explored the region which we are about to enter, because this
journey is not subject to the same conditions as others; for in them
some distinctly understood track and inquiries made of the natives
make it impossible for us to go wrong, but here the most beaten and
frequented tracks are those which lead us most astray. Nothing,
therefore, is more important than that we should not, like sheep,
follow the flock that has gone before us, and thus proceed not
whither we ought, but whither the rest are going. Now nothing gets
us into greater troubles than our subservience to common rumour,
and our habit of thinking that those things are best which are most
generally received as such, of taking many counterfeits for truly
good things, and of living not by reason but by imitation of others.
This is the cause of those great heaps into which men rush till they
are piled one upon another. In a great crush of people, when the
crowd presses upon itself, no one can fall without drawing some one
else down upon him, and those who go before cause the destruction
of those who follow them. You may observe the same thing in
human life: no one can merely go wrong by himself, but he must
become both the cause and adviser of another’s wrongdoing. It is
harmful to follow the march of those who go before us, and since
every one had rather believe another than form his own opinion, we
never pass a deliberate judgment upon life, but some traditional
error always entangles us and brings us to ruin, and we perish
because we follow other men’s examples: we should be cured of this
if we were to disengage ourselves from the herd; but as it is, the
mob is ready to fight against reason in defence of its own mistake.
Consequently the same thing happens as at elections, where, when
the fickle breeze of popular favour has veered round, those who
have been chosen consuls and praetors are viewed with admiration
by the very men who made them so. That we should all approve and
disapprove of the same things is the end of every decision which is
given according to the voice of the majority.

II. When we are considering a happy life, you cannot answer me as


though after a division of the House, “This view has most
supporters;” because for that very reason it is the worse of the two:
matters do not stand so well with mankind that the majority should
prefer the better course: the more people do a thing the worse it is
likely to be. Let us therefore inquire, not what is most commonly
done, but what is best for us to do, and what will establish us in the
possession of undying happiness, not what is approved of by the
vulgar, the worst possible exponents of truth. By “the vulgar” I mean
both those who wear woollen cloaks and those who wear crowns;[1]
for I do not regard the colour of the clothes with which they are
covered: I do not trust my eyes to tell me what a man is: I have a
better and more trustworthy light by which I can distinguish what is
true from what is false: let the mind find out what is good for the
mind. If a man ever allows his mind some breathing space and has
leisure for communing with himself, what truths he will confess to
himself, after having been put to the torture by his own self! He will
say, “Whatever I have hitherto done I wish were undone: when I
think over what I have said, I envy dumb people: whatever I have
longed for seems to have been what my enemies would pray might
befall me: good heaven, how far more endurable what I have feared
seems to be than what I have lusted after. I have been at enmity
with many men, and have changed my dislike of them into
friendship, if friendship can exist between bad men: yet I have not
yet become reconciled to myself. I have striven with all my strength
to raise myself above the common herd, and to make myself
remarkable for some talent: what have I effected save to make
myself a mark for the arrows of my enemies, and show those who
hate me where to wound me? Do you see those who praise your
eloquence, who covet your wealth, who court your favour, or who
vaunt your power? All these either are, or, which comes to the same
thing, may be your enemies: the number of those who envy you is
as great as that of those who admire you; why do I not rather seek
for some good thing which I can use and feel, not one which I can
show? these good things which men gaze at in wonder, which they
crowd to see, which one points out to another with speechless
admiration, are outwardly brilliant, but within are miseries to those
who possess them.”

III. Let us seek for some blessing, which does not merely look fine,
but is sound and good throughout alike, and most beautiful in the
parts which are least seen: let us unearth this. It is not far distant
from us; it can be discovered: all that is necessary is to know
whither to stretch out your hand: but, as it is, we behave as though
we were in the dark, and reach out beyond what is nearest to us,
striking as we do so against the very things that we want. However,
that I may not draw you into digressions, I will pass over the
opinions of other philosophers, because it would take a long time to
state and confute them all: take ours. When, however, I say “ours,” I
do not bind myself to any one of the chiefs of the Stoic school, for I
too have a right to form my own opinion. I shall, therefore, follow
the authority of some of them, but shall ask some others to
discriminate their meaning:[2] perhaps, when after having reported
all their opinions, I am asked for my own, I shall impugn none of my
predecessors’ decisions, and shall say, “I will also add somewhat to
them.” Meanwhile I follow nature, which is a point upon which every
one of the Stoic philosophers are agreed: true wisdom consists in
not departing from nature and in moulding our conduct according to
her laws and model. A happy life, therefore, is one which is in
accordance with its own nature, and cannot be brought about unless
in the first place the mind be sound and remain so without
interruption, and next, be bold and vigorous, enduring all things with
most admirable courage, suited to the times in which it lives, careful
of the body and its appurtenances, yet not troublesomely careful. It
must also set due value upon all the things which adorn our lives,
without over-estimating any one of them, and must be able to enjoy
the bounty of Fortune without becoming her slave. You understand
without my mentioning it that an unbroken calm and freedom ensue,
when we have driven away all those things which either excite us or
alarm us: for in the place of sensual pleasures and those slight
perishable matters which are connected with the basest crimes, we
thus gain an immense, unchangeable, equable joy, together with
peace, calmness and greatness of mind, and kindliness: for all
savageness is a sign of weakness.

IV. Our highest good may also be defined otherwise, that is to say,
the same idea may be expressed in different language. Just as the
same army may at one time be extended more widely, at another
contracted into a smaller compass, and may either be curved
towards the wings by a depression in the line of the centre, or drawn
up in a straight line, while, in whatever figure it be arrayed, its
strength and loyalty remain unchanged; so also our definition of the
highest good may in some cases be expressed diffusely and at great
length, while in others it is put into a short and concise form. Thus,
it will come to the same thing, if I say “The highest good is a mind
which despises the accidents of fortune, and takes pleasure in
virtue”: or, “It is an unconquerable strength of mind, knowing the
world well, gentle in its dealings, showing great courtesy and
consideration for those with whom it is brought into contact.” Or we
may choose to define it by calling that man happy who knows good
and bad only in the form of good or bad minds: who worships
honour, and is satisfied with his own virtue, who is neither puffed up
by good fortune nor cast down by evil fortune, who knows no other
good than that which he is able to bestow upon himself, whose real
pleasure lies in despising pleasures. If you choose to pursue this
digression further, you can put this same idea into many other
forms, without impairing or weakening its meaning: for what
prevents our saying that a happy life consists in a mind which is
free, upright, undaunted, and steadfast, beyond the influence of fear
or desire, which thinks nothing good except honour, and nothing bad
except shame, and regards everything else as a mass of mean
details which can neither add anything to nor take anything away
from the happiness of life, but which come and go without either
increasing or diminishing the highest good? A man of these
principles, whether he will or no, must be accompanied by a
continual cheerfulness, a high happiness, which comes indeed from
on high because he delights in what he has, and desires no greater
pleasures than those which his home affords. Is he not right in
allowing these to turn the scale against petty, ridiculous, and
shortlived movements of his wretched body? on the day on which he
becomes proof against pleasure he also becomes proof against pain.
See, on the other hand, how evil and guilty a slavery the man is
forced to serve who is dominated in turn by pleasures and pains,
those most untrustworthy and passionate of masters. We must,
therefore, escape from them into freedom. This nothing will bestow
upon us save contempt of Fortune: but if we attain to this, then
there will dawn upon us those invaluable blessings, the repose of a
mind that is at rest in a safe haven, its lofty imaginings, its great and
steady delight at casting out errors and learning to know the truth,
its courtesy, and its cheerfulness, in all of which we shall take
delight, not regarding them as good things, but as proceeding from
the proper good of man.

V. Since I have begun to make my definitions without a too strict


adherence to the letter, a man may be called “happy” who, thanks to
reason, has ceased either to hope or to fear: but rocks also feel
neither fear nor sadness, nor do cattle, yet no one would call those
things happy which cannot comprehend what happiness is. With
them you may class men whose dull nature and want of self-
knowledge reduces them to the level of cattle, mere animals: there
is no difference between the one and the other, because the latter
have no reason, while the former have only a corrupted form of it,
crooked and cunning to their own hurt. For no one can be styled
happy who is beyond the influence of truth: and consequently a
happy life is unchangeable, and is founded upon a true and
trustworthy discernment; for the mind is uncontaminated and freed
from all evils only when it is able to escape not merely from wounds
but also from scratches, when it will always be able to maintain the
position which it has taken up, and defend it even against the angry
assaults of Fortune: for with regard to sensual pleasures, though
they were to surround one on every side, and use every means of
assault, trying to win over the mind by caresses and making trial of
every conceivable stratagem to attract either our entire selves or our
separate parts, yet what mortal that retains any traces of human
origin would wish to be tickled day and night, and, neglecting his
mind, to devote himself to bodily enjoyments?

VI. “But,” says our adversary, “the mind also will have pleasures of
its own.” Let it have them, then, and let it sit in judgment over
luxury and pleasures; let it indulge itself to the full in all those
matters which give sensual delights: then let it look back upon what
it enjoyed before, and with all those faded sensualities fresh in its
memory let it rejoice and look eagerly forward to those other
pleasures which it experienced long ago, and intends to experience
again, and while the body lies in helpless repletion in the present, let
it send its thoughts onward towards the future, and take stock of its
hopes: all this will make it appear, in my opinion, yet more wretched,
because it is insanity to choose evil instead of good: now no insane
person can be happy, and no one can be sane if he regards what is
injurious as the highest good and strives to obtain it. The happy
man, therefore, is he who can make a right judgment in all things:
he is happy who in his present circumstances, whatever they may
be, is satisfied and on friendly terms with the conditions of his life.
That man is happy, whose reason recommends to him the whole
posture of his affairs.

VII. Even those very people who declare the highest good to be in
the belly, see what a dishonourable position they have assigned to it:
and therefore they say that pleasure cannot be parted from virtue,
and that no one can either live honourably without living cheerfully,
nor yet live cheerfully without living honourably. I do not see how
these very different matters can have any connexion with one
another. What is there, I pray you, to prevent virtue existing apart
from pleasure? of course the reason is that all good things derive
their origin from virtue, and therefore even those things which you
cherish and seek for come originally from its roots. Yet, if they were
entirely inseparable, we should not see some things to be pleasant,
but not honourable, and others most honourable indeed, but hard
and only to be attained by suffering. Add to this, that pleasure visits
the basest lives, but virtue cannot co-exist with an evil life; yet some
unhappy people are not without pleasure, nay, it is owing to
pleasure itself that they are unhappy; and this could not take place if
pleasure had any connexion with virtue, whereas virtue is often
without pleasure, and never stands in need of it. Why do you put
together two things which are unlike and even incompatible one with
another? virtue is a lofty quality, sublime, royal, unconquerable,
untiring: pleasure is low, slavish, weakly, perishable; its haunts and
homes are the brothel and the tavern. You will meet virtue in the
temple, the market-place, the senate house, manning the walls,
covered with dust, sunburnt, horny-handed: you will find pleasure
skulking out of sight, seeking for shady nooks at the public baths,
hot chambers, and places which dread the visits of the aedile, soft,
effeminate, reeking of wine and perfumes, pale or perhaps painted
and made up with cosmetics. The highest good is immortal: it knows
no ending, and does not admit of either satiety or regret: for a right-
thinking mind never alters or becomes hateful to itself, nor do the
best things ever undergo any change: but pleasure dies at the very
moment when it charms us most: it has no great scope, and
therefore it soon cloys and wearies us, and fades away as soon as its
first impulse is over: indeed, we cannot depend upon anything
whose nature is to change. Consequently it is not even possible that
there should be any solid substance in that which comes and goes
so swiftly, and which perishes by the very exercise of its own
functions, for it arrives at a point at which it ceases to be, and even
while it is beginning always keeps its end in view.

VIII. What answer are we to make to the reflexion that pleasure


belongs to good and bad men alike, and that bad men take as much
delight in their shame as good men in noble things? This was why
the ancients bade us lead the highest, not the most pleasant life, in
order that pleasure might not be the guide but the companion of a
right-thinking and honourable mind; for it is Nature whom we ought
to make our guide: let our reason watch her, and be advised by her.
To live happily, then, is the same thing as to live according to
Nature: what this may be, I will explain. If we guard the
endowments of the body and the advantages of nature with care
and fearlessness, as things soon to depart and given to us only for a
day; if we do not fall under their dominion, nor allow ourselves to
become the slaves of what is no part of our own being; if we assign
to all bodily pleasures and external delights the same position which
is held by auxiliaries and light-armed troops in a camp; if we make
them our servants, not our masters—then and then only are they of
value to our minds. A man should be unbiassed and not to be
conquered by external things: he ought to admire himself alone, to
feel confidence in his own spirit, and so to order his life as to be
ready alike for good or for bad fortune. Let not his confidence be
without knowledge, nor his knowledge without steadfastness: let
him always abide by what he has once determined, and let there be
no erasure in his doctrines. It will be understood, even though I
append it not, that such a man will be tranquil and composed in his
demeanour, high-minded and courteous in his actions. Let reason be
encouraged by the senses to seek for the truth, and draw its first
principles from thence: indeed it has no other base of operations or
place from which to start in pursuit of truth: it must fall back upon
itself. Even the all-embracing universe and God who is its guide
extends himself forth into outward things, and yet altogether returns
from all sides back to himself. Let our mind do the same thing:
when, following its bodily senses it has by means of them sent itself
forth into the things of the outward world, let it remain still their
master and its own. By this means we shall obtain a strength and an
ability which are united and allied together, and shall derive from it
that reason which never halts between two opinions, nor is dull in
forming its perceptions, beliefs, or convictions. Such a mind, when it
has ranged itself in order, made its various parts agree together,
and, if I may so express myself, harmonized them, has attained to
the highest good: for it has nothing evil or hazardous remaining,
nothing to shake it or make it stumble: it will do everything under
the guidance of its own will, and nothing unexpected will befal it, but
whatever may be done by it will turn out well, and that, too, readily
and easily, without the doer having recourse to any underhand
devices: for slow and hesitating action are the signs of discord and
want of settled purpose. You may, then, boldly declare that the
highest good is singleness of mind: for where agreement and unity
are, there must the virtues be: it is the vices that are at war one
with another.

IX. “But,” says our adversary, “you yourself only practise virtue
because you hope to obtain some pleasure from it.” In the first
place, even though virtue may afford us pleasure, still we do not
seek after her on that account: for she does not bestow this, but
bestows this to boot, nor is this the end for which she labours, but
her labour wins this also, although it be directed to another end. As
in a tilled-field, when ploughed for corn, some flowers are found
amongst it, and yet, though these posies may charm the eye, all this
labour was not spent in order to produce them—the man who sowed
the field had another object in view, he gained this over and above it
—so pleasure is not the reward or the cause of virtue, but comes in
addition to it; nor do we choose virtue because she gives us
pleasure, but she gives us pleasure also if we choose her. The
highest good lies in the act of choosing her, and in the attitude of
the noblest minds, which when once it has fulfilled its function and
established itself within its own limits has attained to the highest
good, and needs nothing more: for there is nothing outside of the
whole, any more than there is anything beyond the end. You are
mistaken, therefore, when you ask me what it is on account of which
I seek after virtue: for you are seeking for something above the
highest. Do you ask what I seek from virtue? I answer. Herself: for
she has nothing better; she is her own reward. Does this not appear
great enough, when I tell you that the highest good is an unyielding
strength of mind, wisdom, magnanimity, sound judgment, freedom,
harmony, beauty? Do you still ask me for something greater, of
which these may be regarded as the attributes? Why do you talk of
pleasures to me? I am seeking to find what is good for man, not for
his belly; why, cattle and whales have larger ones than he.

X. “You purposely misunderstand what I say,” says he, “for I too say
that no one can live pleasantly unless he lives honorably also, and
this cannot be the case with dumb animals who measure the extent
of their happiness by that of their food. I loudly and publicly
proclaim that what I call a pleasant life cannot exist without the
addition of virtue.” Yet who does not know that the greatest fools
drink the deepest of those pleasures of yours? or that vice is full of
enjoyments, and that the mind itself suggests to itself many
perverted, vicious forms of pleasure?—in the first place arrogance,
excessive self-esteem, swaggering precedence over other men, a
shortsighted, nay, a blind devotion to his own interests, dissolute
luxury, excessive delight springing from the most trifling and childish
causes, and also talkativeness, pride that takes a pleasure in
insulting others, sloth, and the decay of a dull mind which goes to
sleep over itself. All these are dissipated by virtue, which plucks a
man by the ear, and measures the value of pleasures before she
permits them to be used; nor does she set much store by those
which she allows to pass current, for she merely allows their use,
and her cheerfulness is not due to her use of them, but to her
moderation in using them. “Yet when moderation lessens pleasure, it
impairs the highest good.” You devote yourself to pleasures, I check
them; you indulge in pleasure, I use it; you think that it is the
highest good, I do not even think it to be good: for the sake of
pleasure I do nothing, you do everything.

XI. When I say that I do nothing for the sake of pleasure, I allude to
that wise man, whom alone you admit to be capable of pleasure:
now I do not call a man wise who is overcome by anything, let alone
by pleasure: yet, if engrossed by pleasure, how will he resist toil,
danger, want, and all the ills which surround and threaten the life of
man? How will he bear the sight of death or of pain? How will he
endure the tumult of the world, and make head against so many
most active foes, if he be conquered by so effeminate an antagonist?
He will do whatever pleasure advises him: well, do you not see how
many things it will advise him to do? “It will not,” says our adversary,
“be able to give him any bad advice, because it is combined with
virtue?” Again, do you not see what a poor kind of highest good that
must be which requires a guardian to ensure its being good at all?
and how is virtue to rule pleasure if she follows it, seeing that to
follow is the duty of a subordinate, to rule that of a commander? do
you put that which commands in the background? According to your
school, virtue has the dignified office of preliminary taster of
pleasures. We shall, however, see whether virtue still remains virtue
among those who treat her with such contempt, for if she leaves her
proper station she can no longer keep her proper name: in the
meanwhile, to keep to the point, I will show you many men beset by
pleasures, men upon whom Fortune has showered all her gifts,
whom you must needs admit to be bad men. Look at Nomentanus
and Apicius, who digest all the good things, as they call them, of the
sea and land, and review upon their tables the whole animal
kingdom. Look at them as they lie on beds of roses gloating over
their banquet, delighting their ears with music, their eyes with
exhibitions, their palates with flavours: their whole bodies are
titillated with soft and soothing applications, and lest even their
nostrils should be idle, the very place in which, they solemnize[3] the
rites of luxury is scented with various perfumes. You will say that
these men live in the midst of pleasures. Yet they are ill at ease,
because they take pleasure in what is not good.

XII. “They are ill at ease,” replies he, “because many things arise
which distract their thoughts, and their minds are disquieted by
conflicting opinions.” I admit that this is true: still these very men,
foolish, inconsistent, and certain to feel remorse as they are, do
nevertheless receive great pleasure, and we must allow that in so
doing they are as far from feeling any trouble as they are from
forming a right judgment, and that, as is the case with many people,
they are possessed by a merry madness, and laugh while they rave.
The pleasures of wise men, on the other hand, are mild, decorous,
verging on dulness, kept under restraint and scarcely noticeable, and
are neither invited to come nor received with honour when they
come of their own accord, nor are they welcomed with any delight
by those whom they visit, who mix them up with their lives and fill
up empty spaces with them, like an amusing farce in the intervals of
serious business. Let them no longer, then, join incongruous matters
together, or connect pleasure with virtue, a mistake whereby they
court the worst of men. The reckless profligate, always in liquor and
belching out the fumes of wine, believes that he lives with virtue,
because he knows that he lives with pleasure, for he hears it said
that pleasure cannot exist apart from virtue; consequently he dubs
his vices with the title of wisdom and parades all that he ought to
conceal. So, men are not encouraged by Epicurus to run riot, but the
vicious hide their excesses in the lap of philosophy, and flock to the
schools in which they hear the praises of pleasure. They do not
consider how sober and temperate—for so, by Hercules, I believe it
to be—that “pleasure” of Epicurus is, but they rush at his mere
name, seeking to obtain some protection and cloak for their vices.
They lose, therefore, the one virtue which their evil life possessed,
that of being ashamed of doing wrong: for they praise what they
used to blush at, and boast of their vices. Thus modesty can never
reassert itself, when shameful idleness is dignified with an
honourable name. The reason why that praise which your school
lavishes upon pleasure is so hurtful, is because the honourable part
of its teaching passes unnoticed, but the degrading part is seen by
all.

XIII. I myself believe, though my Stoic comrades would be unwilling


to hear me say so, that the teaching of Epicurus was upright and
holy, and even, if you examine it narrowly, stern: for this much
talked of pleasure is reduced to a very narrow compass, and he bids
pleasure submit to the same law which we bid virtue do—I mean, to
obey nature. Luxury, however, is not satisfied with what is enough
for nature. What is the consequence? Whoever thinks that happiness
consists in lazy sloth, and alternations of gluttony and profligacy,
requires a good patron for a bad action, and when he has become
an Epicurean, having been led to do so by the attractive name of
that school, he follows, not the pleasure which he there hears
spoken of, but that which he brought thither with him, and, haying
learned to think that his vices coincide with the maxims of that
philosophy, he indulges in them no longer timidly and in dark
corners, but boldly in the face of day. I will not, therefore, like most
of our school, say that the sect of Epicurus is the teacher of crime,
but what I say is: it is ill spoken of, it has a bad reputation, and yet it
does not deserve it. “Who can know this without having been
admitted to its inner mysteries?” Its very outside gives opportunity
for scandal, and encourages men’s baser desires: it is like a brave
man dressed in a woman’s gown: your chastity is assured, your
manhood is safe, your body is submitted to nothing disgraceful, but
your hand holds a drum (like a priest of Cybele). Choose, then, some
honourable superscription for your school, some writing which shall
in itself arouse the mind: that which at present stands over your
door has been invented by the vices. He who ranges himself on the
side of virtue gives thereby a proof of a noble disposition: he who
follows pleasure appears to be weakly, worn out, degrading his
manhood, likely to fall into infamous vices unless someone
discriminates his pleasures for him, so that he may know which
remain within the bounds of natural desire, which are frantic and
boundless, and become all the more insatiable the more they are
satisfied. But come! let virtue lead the way: then every step will be
safe. Too much pleasure is hurtful: but with virtue we need fear no
excess of any kind, because moderation is contained in virtue
herself. That which is injured by its own extent cannot be a good
thing: besides, what better guide can there be than reason for
beings endowed with a reasoning nature? so if this combination
pleases you, if you are willing to proceed to a happy life thus
accompanied, let virtue lead the way, let pleasure follow and hang
about the body like a shadow: it is the part of a mind incapable of
great things to hand over virtue, the highest of all qualities, as a
handmaid to pleasure.

XIV. Let virtue lead the way and bear the standard: we shall have
pleasure for all that, but we shall be her masters and controllers; she
may win some concessions from us, but will not force us to do
anything. On the contrary, those who have permitted pleasure to
lead the van, have neither one nor the other: for they lose virtue
altogether, and yet they do not possess pleasure, but are possessed
by it, and are either tortured by its absence or choked by its excess,
being wretched if deserted by it, and yet more wretched if
overwhelmed by it, like those who are caught in the shoals of the
Syrtes and at one time are left on dry ground and at another tossed
on the flowing waves. This arises from an exaggerated want of self-
control, and a hidden love of evil: for it is dangerous for one who
seeks after evil instead of good to attain his object. As we hunt wild
beasts with toil and peril, and even when they are caught find them
an anxious possession, for they often tear their keepers to pieces,
even so are great pleasures: they turn out to be great evils and take
their owners prisoner. The more numerous and the greater they are,
the more inferior and the slave of more masters does that man
become whom the vulgar call a happy man. I may even press this
analogy further: as the man who tracks wild animals to their lairs,
and who sets great store on—

“Seeking with snares the wandering brutes to noose,”

and

“Making their hounds the spacious glade surround,”

that he may follow their tracks, neglects far more desirable things,
and leaves many duties unfulfilled, so he who pursues pleasure
postpones everything to it, disregards that first essential, liberty, and
sacrifices it to his belly; nor does he buy pleasure for himself, but
sells himself to pleasure.

XV. “But what,” asks our adversary, “is there to hinder virtue and
pleasure being combined together, and a highest good being thus
formed, so that honour and pleasure may be the same thing?”
Because nothing except what is honourable can form a part of
honour, and the highest good would lose its purity if it were to see
within itself anything unlike its own better part. Even the joy which
arises from virtue, although it be a good thing, yet is not a part of
absolute good, any more than cheerfulness or peace of mind, which
are indeed good things, but which merely follow the highest good,
and do not contribute to its perfection, although they are generated
by the noblest causes. Whoever on the other hand forms an alliance,
and that, too, a one-sided one, between virtue and pleasure, clogs
whatever strength the one may possess by the weakness of the
other, and sends liberty under the yoke, for liberty can only remain
unconquered as long as she knows nothing more valuable than
herself: for he begins to need the help of Fortune, which is the most
utter slavery: his life becomes anxious, full of suspicion, timorous,
fearful of accidents, waiting in agony for critical moments of time.
You do not afford virtue a solid immoveable base if you bid it stand
on what is unsteady: and what can be so unsteady as dependence
on mere chance, and the vicissitudes of the body and of those things
which act on the body? How can such a man obey God and receive
everything which comes to pass in a cheerful spirit, never
complaining of fate, and putting a good construction upon
everything that befalls him, if he be agitated by the petty pin-pricks
of pleasures and pains? A man cannot be a good protector of his
country, a good avenger of her wrongs, or a good defender of his
friends, if he be inclined to pleasures. Let the highest good, then,
rise to that height from whence no force can dislodge it, whither
neither pain can ascend, nor hope, nor fear, nor anything else that
can impair the authority of the “highest good.” Thither virtue alone
can make her way: by her aid that hill must be climbed: she will
bravely stand her ground and endure whatever may befal her not
only resignedly, but even willingly: she will know that all hard times
come in obedience to natural laws, and like a good soldier she will
bear wounds, count scars, and when transfixed and dying will yet
adore the general for whom she falls: she will bear in mind the old
maxim “Follow God.” On the other hand, he who grumbles and
complains and bemoans himself is nevertheless forcibly obliged to
obey orders, and is dragged away, however much against his will, to
carry them out: yet what madness is it to be dragged rather than to
follow? as great, by Hercules, as it is folly and ignorance of one’s
true position to grieve because one has not got something or
because something has caused us rough treatment, or to be
surprised or indignant at those ills which befall good men as well as
bad ones, I mean diseases, deaths, illnesses, and the other cross
accidents of human life. Let us bear with magnanimity whatever the
system of the universe makes it needful for us to bear: we are all
bound by this oath: “To bear the ills of mortal life, and to submit
with a good grace to what we cannot avoid.” We have been born
into a monarchy: our liberty is to obey God.

XVI. True happiness, therefore, consists in virtue: and what will this
virtue bid you do? Not to think anything bad or good which is
connected neither with virtue nor with wickedness: and in the next
place, both to endure unmoved the assaults of evil, and, as far as is
right, to form a god out of what is good. What reward does she
promise you for this campaign? an enormous one, and one that
raises you to the level of the gods: you shall be subject to no
restraint and to no want; you shall be free, safe, unhurt; you shall
fail in nothing that you attempt; you shall be debarred from nothing;
everything shall turn out according to your wish; no misfortune shall
befal you; nothing shall happen to you except what you expect and
hope for. “What! does virtue alone suffice to make you happy?” why,
of course, consummate and god-like virtue such as this not only
suffices, but more than suffices: for when a man is placed beyond
the reach of any desire, what can he possibly lack? if all that he
needs is concentred in himself, how can he require anything from
without? He, however, who is only on the road to virtue, although he
may have made great progress along it, nevertheless needs some
favour from fortune while he is still struggling among mere human
interests, while he is untying that knot, and all the bonds which bind
him to mortality. What, then, is the difference between them? it is
that some are tied more or less tightly by these bonds, and some
have even tied themselves with them as well; whereas he who has
made progress towards the upper regions and raised himself
upwards drags a looser chain, and though not yet free, is yet as
good as free.

XVII. If, therefore, any one of those dogs who yelp at philosophy
were to say, as they are wont to do, “Why, then, do you talk so
much more bravely than you live? why do you check your words in
the presence of your superiors, and consider money to be a
necessary implement? why are you disturbed when you sustain
losses, and weep on hearing of the death of your wife or your
friend? why do you pay regard to common rumour, and feel annoyed
by calumnious gossip? why is your estate more elaborately kept than
its natural use requires? why do you not dine according to your own
maxims? why is your furniture smarter than it need be? why do you
drink wine that is older than yourself? why are your grounds laid
out? why do you plant trees which afford nothing except shade? why
does your wife wear in her ears the price of a rich man’s house? why
are your children at school dressed in costly clothes? why is it a
science to wait upon you at table? why is your silver plate not set
down anyhow or at random, but skilfully disposed in regular order,
with a superintendent to preside over the carving of the viands?”
Add to this, if you like, the questions “Why do you own property
beyond the seas? why do you own more than you know of? it is a
shame to you not to know your slaves by sight: for you must be very
neglectful of them if you only own a few, or very extravagant if you
have too many for your memory to retain.” I will add some
reproaches afterwards, and will bring more accusations against
myself than you think of: for the present I will make you the
following answer. “I am not a wise man, and I will not be one in
order to feed your spite: so do not require me to be on a level with
the best of men, but merely to be better than the worst: I am
satisfied, if every day I take away something from my vices and
correct my faults. I have not arrived at perfect soundness of mind,
indeed, I never shall arrive at it: I compound palliatives rather than
remedies for my gout, and am satisfied if it comes at rarer intervals
and does not shoot so painfully. Compared with your feet, which are
lame, I am a racer.” I make this speech, not on my own behalf, for I
am steeped in vices of every kind, but on behalf of one who has
made some progress in virtue.

XVIII. “You talk one way,” objects our adversary, “and live another.”
You most spiteful of creatures, you who always show the bitterest
hatred to the best of men, this reproach was flung at Plato, at
Epicurus, at Zeno: for all these declared how they ought to live, not
how they did live. I speak of virtue, not of myself, and when I blame
vices, I blame my own first of all: when I have the power, I shall live
as I ought to do: spite, however deeply steeped in venom, shall not
keep me back from what is best: that poison itself with which you
bespatter others, with which you choke yourselves, shall not hinder
me from continuing to praise that life which I do not, indeed, lead,
but which I know I ought to lead, from loving virtue and from
following after her, albeit a long way behind her and with halting
gait. Am I to expect that evil speaking will respect anything, seeing
that it respected neither Rutilius nor Cato? Will any one care about
being thought too rich by men for whom Diogenes the Cynic was not
poor enough? That most energetic philosopher fought against all the
desires of the body, and was poorer even than the other Cynics, in
that besides haying given up possessing anything he had also given
up asking for anything: yet they reproached him for not being
sufficiently in want: as though forsooth it were poverty, not virtue, of
which he professed knowledge.

XIX. They say that Diodorus, the Epicurean philosopher, who within
these last few days put an end to his life with his own hand, did not
act according to the precepts of Epicurus, in cutting his throat: some
choose to regard this act as the result of madness, others of
recklessness; he, meanwhile, happy and filled with the
consciousness of his own goodness, has borne testimony to himself
by his manner of departing from life, has commended the repose of
a life spent at anchor in a safe harbour, and has said what you do
not like to hear, because you too ought to do it:

“I’ve lived, I’ve run the race which Fortune set me.”

You argue about the life and death of another, and yelp at the name
of men whom some peculiarly noble quality has rendered great, just
as tiny curs do at the approach of strangers: for it is to your interest
that no one should appear to be good, as if virtue in another were a
reproach to all your crimes. You enviously compare the glories of
others with your own dirty actions, and do not understand how
greatly to your disadvantage it is to venture to do so: for if they who
follow after virtue be greedy, lustful, and fond of power, what must
you be, who hate the very name of virtue? You say that no one acts
up to his professions, or lives according to the standard which he
sets up in his discourses: what wonder, seeing that the words which
they speak are brave, gigantic, and able to weather all the storms
which wreck mankind, whereas they themselves are struggling to
tear themselves away from crosses into which each one of you is
driving his own nail. Yet men who are crucified hang from one single
pole, but these who punish themselves are divided between as many
crosses as they have lusts, but yet are given to evil speaking, and
are so magnificent in their contempt of the vices of others that I
should suppose that they had none of their own, were it not that
some criminals when on the gibbet spit upon the spectators.

XX. “Philosophers do not carry into effect all that they teach.” No;
but they effect much good by their teaching, by the noble thoughts
which they conceive in their minds: would, indeed, that they could
act up to their talk: what could be happier than they would be? but
in the meanwhile you have no right to despise good sayings and
hearts full of good thoughts. Men deserve praise for engaging in
profitable studies, even though they stop short of producing any
results. Why need we wonder if those who begin to climb a steep
path do not succeed in ascending it very high? yet, if you be a man,
look with respect on those who attempt great things, even though
they fall. It is the act of a generous spirit to proportion its efforts not
to its own strength but to that of human nature, to entertain lofty
aims, and to conceive plans which are too vast to be carried into
execution even by those who are endowed with gigantic intellects,
who appoint for themselves the following rules: I will look upon
death or upon a comedy with the same expression of countenance: I
will submit to labours, however great they may be, supporting the
strength of my body by that of my mind: I will despise riches when I
have them as much as when I have them not; if they be elsewhere I
will not be more gloomy, if they sparkle around me I will not be
more lively than I should otherwise be: whether Fortune comes or
goes I will take no notice of her: I will view all lands as though they
belong to me, and my own as though they belonged to all mankind:
I will so live as to remember that I was born for others, and will
thank Nature on this account: for in what fashion could she have
done better for me? she has given me alone to all, and all to me
alone. Whatever I may possess, I will neither hoard it greedily nor
squander it recklessly. I will think that I have no possessions so real
as those which I have given away to deserving people: I will not
reckon benefits by their magnitude or number, or by anything except
the value set upon them by the receiver: I never will consider a gift
to be a large one if it be bestowed upon a worthy object. I will do
nothing because of public opinion, but everything because of
conscience: whenever I do anything alone by myself I will believe
that the eyes of the Roman people are upon me while I do it. In
eating and drinking my object shall be to quench the desires of
Nature, not to fill and empty my belly. I will be agreeable with my
friends, gentle and mild to my foes: I will grant pardon before I am
asked for it, and will meet the wishes of honourable men half way: I
will bear in mind that the world is my native city, that its governors
are the gods, and that they stand above and around me, criticizing
whatever I do or say. Whenever either Nature demands my breath
again, or reason bids me dismiss it, I will quit this life, calling all to
witness that I have loved a good conscience, and good pursuits; that
no one’s freedom, my own least of all, has been impaired through
me.” He who sets up these as the rules of his life will soar aloft and
strive to make his way to the gods: of a truth, even though he fails,
yet he

“Fails in a high emprise.”[4]

But you, who hate both virtue and those who practise it, do nothing
at which we need be surprised, for sickly lights cannot bear the sun,
nocturnal creatures avoid the brightness of day, and at its first
dawning become bewildered and all betake themselves to their dens
together: creatures that fear the light hide themselves in crevices.
So croak away, and exercise your miserable tongues in reproaching
good men: open wide your jaws, bite hard: you will break many
teeth before you make any impression.

XXI. “But how is it that this man studies philosophy and nevertheless
lives the life of a rich man? Why does he say that wealth ought to be
despised and yet possess it? that life should be despised, and yet
live? that health should be despised, and yet guard it with the
utmost care, and wish it to be as good as possible? Does he consider
banishment to be an empty name, and say, “What evil is there in
changing one country for another?” and yet, if permitted, does he
not grow old in his native land? does he declare that there is no
difference between a longer and a shorter time, and yet, if he be not
prevented, lengthen out his life and flourish in a green old age?” His
answer is, that these things ought to be despised, not that he should
not possess them, but that he should not possess them with fear
and trembling: he does not drive them away from him, but when
they leave him he follows after them unconcernedly. Where, indeed,
can fortune invest riches more securely than in a place from whence
they can always be recovered without any squabble with their
trustee? Marcus Cato, when he was praising Curius and Coruncanius
and that century in which the possession of a few small silver coins
were an offence which was punished by the Censor, himself owned
four million sesterces; a less fortune no doubt, than that of Crassus,
but larger than of Cato the Censor. If the amounts be compared, he
had outstripped his great-grandfather further than he himself was
outdone by Crassus, and if still greater riches had fallen to his lot, he
would not have spurned them: for the wise man does not think
himself unworthy of any chance presents: he does not love riches,
but he prefers to have them; he does not receive them into his
spirit, but only into his house: nor does he cast away from him what
he already possesses, but keeps them, and is willing that his virtue
should receive a larger subject-matter for its exercise.

XXII. Who can doubt, however, that the wise man, if he is rich, has a
wider field for the development of his powers than if he is poor,
seeing that in the latter case the only virtue which he can display is
that of neither being perverted nor crushed by his poverty, whereas
if he has riches, he will have a wide field for the exhibition of
temperance, generosity, laboriousness, methodical arrangement, and
grandeur. The wise man will not despise himself, however short of
stature he may be, but nevertheless he will wish to be tall: even
though he be feeble and one-eyed he may be in good health, yet he
would prefer to have bodily strength, and that too, while he knows
all the while that he has something which is even more powerful: he
will endure illness, and will hope for good health: for some things,
though they may be trifles compared with the sum total, and though
they may be taken away without destroying the chief good, yet add
somewhat to that constant cheerfulness which arises from virtue.
Riches encourage and brighten up such a man just as a sailor is
delighted at a favourable wind that bears him on his way, or as
people feel pleasure at a fine day or at a sunny spot in the cold
weather. What wise man, I mean of our school, whose only good is
virtue, can deny that even these matters which we call neither good
nor bad have in themselves a certain value, and that some of them
are preferable to others? to some of them we show a certain amount
of respect, and to some a great deal. Do not, then, make any
mistake: riches belong to the class of desirable things. “Why then,”
say you, “do you laugh at me, since you place them in the same
position that I do?” Do you wish to know how different the position
is in which we place them? If my riches leave me, they will carry
away with them nothing except themselves: you will be bewildered
and will seem to be left without yourself if they should pass away
from you: with me riches occupy a certain place, but with you they
occupy the highest place of all. In fine, my riches belong to me, you
belong to your riches.

XXIII. Cease, then, forbidding philosophers to possess money: no


one has condemned wisdom to poverty. The philosopher may own
ample wealth, but will not own wealth that which has been torn
from another, or which is stained with another’s blood: his must be
obtained without wronging any man, and without its being won by
base means; it must be alike honourably come by and honourably
spent, and must be such as spite alone could shake its head at.
Raise it to whatever figure you please, it will still be an honourable
possession, if, while it includes much which every man would like to
call his own, there be nothing which any one can say is his own.
Such a man will not forfeit his right to the favour of Fortune, and will
neither boast of his inheritance nor blush for it if it was honourably
acquired: yet he will have something to boast of, if he throw his
house open, let all his countrymen come among his property, and
say, “If any one recognizes here anything belonging to him, let him
take it.” What a great man, how excellently rich will he be, if after
this speech he possesses as much as he had before! I say, then, that
if he can safely and confidently submit his accounts to the scrutiny
of the people, and no one can find in them any item upon which he
can lay hands, such a man may boldly and unconcealedly enjoy his
riches. The wise man will not allow a single ill-won penny to cross
his threshold: yet he will not refuse or close his door against great
riches, if they are the gift of fortune and the product of virtue: what
reason has he for grudging them good quarters: let them come and
be his guests: he will neither brag of them nor hide them away: the
one is the part of a silly, the other of a cowardly and paltry spirit,
which, as it were, muffles up a good thing in its lap. Neither will he,
as I said before, turn them out of his house: for what will he say?
will he say, “You are useless,” or “I do not know how to use riches?”
As he is capable of performing a journey upon his own feet, but yet
would prefer to mount a carriage, just so he will be capable of being
poor, yet will wish to be rich; he will own wealth, but will view it as
an uncertain possession which will some day fly away from him. He
will not allow it to be a burden either to himself or to any one else:
he will give it—why do you prick up your ears? why do you open
your pockets?—he will give it either to good men or to those whom
it may make into good men. He will give it after having taken the
utmost pains to choose those who are fittest to receive it, as
becomes one who bears in mind that he ought to give an account of
what he spends as well as of what he receives. He will give for good
and commendable reasons, for a gift ill bestowed counts as a
shameful loss: he will have an easily opened pocket, but not one
with a hole in it, so that much may be taken out of it, yet nothing
may fall out of it.

XXIV. He who believes giving to be an easy matter, is mistaken: it


offers very great difficulties, if we bestow our bounty rationally, and
do not scatter it impulsively and at random. I do this man a service,
I requite a good turn done me by that one: I help this other,
because I pity him: this man, again, I teach to be no fit object for
poverty to hold down or degrade. I shall not give some men
anything, although they are in want, because, even if I do give to

You might also like