Functional Programming in JavaScript How to
improve your JavaScript programs using
functional techniques 1st Edition Luis Atencio
install download
https://ebookmeta.com/product/functional-programming-in-
javascript-how-to-improve-your-javascript-programs-using-
functional-techniques-1st-edition-luis-atencio/
Download more ebook from https://ebookmeta.com
We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!
Functional Programming in JavaScript How to improve
your JavaScript programs using functional techniques
1st Edition Luis Atencio
https://ebookmeta.com/product/functional-programming-in-
javascript-how-to-improve-your-javascript-programs-using-
functional-techniques-1st-edition-luis-atencio/
Mastering JavaScript Functional Programming 1st Edition
Federico Kereki
https://ebookmeta.com/product/mastering-javascript-functional-
programming-1st-edition-federico-kereki/
Functional JavaScript 1st Edition Michael Fogus
https://ebookmeta.com/product/functional-javascript-1st-edition-
michael-fogus/
Neuroscience for Learning and Development: How to Apply
Neuroscience and Psychology for Improved Learning and
Training 3rd Edition Stella Collins
https://ebookmeta.com/product/neuroscience-for-learning-and-
development-how-to-apply-neuroscience-and-psychology-for-
improved-learning-and-training-3rd-edition-stella-collins/
ALU 101 TEXTBOOK BASIC LIFE INSURANCE UNDERWRITING
Academy Of Life Underwriting
https://ebookmeta.com/product/alu-101-textbook-basic-life-
insurance-underwriting-academy-of-life-underwriting/
The Oxford Handbook of Nigerian Politics A. Carl Levan
https://ebookmeta.com/product/the-oxford-handbook-of-nigerian-
politics-a-carl-levan/
Bedside Manner- A Small-Town, Older Man/Younger Woman
Instalove Medical Romance: May December Romance Series
1st Edition Violet Rae
https://ebookmeta.com/product/bedside-manner-a-small-town-older-
man-younger-woman-instalove-medical-romance-may-december-romance-
series-1st-edition-violet-rae/
These Vile Secrets Enclave 1 1st Edition Ce Ricci Ricci
Ce
https://ebookmeta.com/product/these-vile-secrets-enclave-1-1st-
edition-ce-ricci-ricci-ce/
The Princeton Field Guide to Dinosaurs Second Edition
Gregory S. Paul
https://ebookmeta.com/product/the-princeton-field-guide-to-
dinosaurs-second-edition-gregory-s-paul/
Mr. Park Lane (Mister #4) 1st Edition Louise Bay
https://ebookmeta.com/product/mr-park-lane-mister-4-1st-edition-
louise-bay/
www.ebook3000.com
Functional Programming in JavaScript
www.ebook3000.com
www.ebook3000.com
Functional
Programming
in JavaScript
LUIS ATENCIO
MANNING
SHELTER ISLAND
www.ebook3000.com
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: [email protected]
©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: Marina Michaels
20 Baldwin Road
Technical development editor: Dean Iverson
PO Box 761
Review editor: Aleksandar Dragosavljevic
Shelter Island, NY 11964
Project editor: Tiffany Taylor
Copy editor: Tiffany Taylor
Proofreader: Katie Tennant
Technical proofreader: Daniel Lamb
Typesetter: Dennis Dalinnik
Cover designer: Leslie Haimes
ISBN: 9781617292828
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – EBM – 21 20 19 18 17 16
www.ebook3000.com
To my wonderful wife, Ana.
Thank you for your unconditional support
and for being the source of passion and inspiration in my life.
www.ebook3000.com
www.ebook3000.com
brief contents
PART 1
THINK FUNCTIONALLY ..................................................1
Becoming functional
3
Higher-order JavaScript
23
PART 2
GET FUNCTIONAL........................................................55
Few data structures, many operations
57
Toward modular, reusable code
84
Design patterns against complexity
117
PART 3
ENHANCING YOUR FUNCTIONAL SKILLS...................... 151
Bulletproofing your code
153
Functional optimizations
180
Managing asynchronous events and data
205
vii
www.ebook3000.com
www.ebook3000.com
contents
preface
xv
acknowledgments
xvii
about this book
xix
PART 1 THINK FUNCTIONALLY .......................................1
1 Becoming functional 3
1.1
Can functional programming help?
1.2
What is functional programming?
Functional programming is declarative
7 ■ Pure functions and
the problem with side effects
9 ■ Referential transparency and
substitutability
13 ■ Preserving immutable data
15
1.3
Benefits of functional programming
16
Encouraging the decomposition of complex tasks
16
Processing data using fluent chains
18 ■ Reacting to the
complexity of asynchronous applications
19
1.4
Summary
22
ix
www.ebook3000.com
CONTENTS
2 Higher-order JavaScript 23
2.1
Why JavaScript?
24
2.2
Functional vs. object-oriented programming
24
Managing the state of JavaScript objects
31 ■ Treating objects
as values
32 ■ Deep-freezing moving parts
34 ■ Navigating
and modifying object graphs with lenses
37
2.3
Functions
38
Functions as first-class citizens
39 ■ Higher-order functions
40
Types of function invocation
43 ■ Function methods
44
2.4
Closures and scopes
45
Problems with the global scope
47 ■ JavaScript’s function
scope
48 ■ A pseudo-block scope
49 ■ Practical applications
of closures
50
2.5
Summary
53
PART 2 GET FUNCTIONAL ............................................55
3 Few data structures, many operations 57
3.1
Understanding your application’s control flow
58
3.2
Method chaining
59
3.3
Function chaining
60
Understanding lambda expressions
61 ■ Transforming data
with _.map
62 ■ Gathering results with _.reduce
65
Removing unwanted elements with _.filter
68
3.4
Reasoning about your code
70
Declarative and lazy function chains
71 ■ SQL-like data:
functions as data
75
3.5
Learning to think recursively
77
What is recursion?
77 ■ Learning to think recursively
77
Recursively defined data structures
79
3.6
Summary
83
4 Toward modular, reusable code 84
4.1
Method chains vs. function pipelines
85
Chaining methods together
86 ■ Arranging functions
in a pipeline
87
CONTENTS
xi
4.2
Requirements for compatible functions
88
Type-compatible functions
88 ■ Functions and arity:
the case for tuples
89
4.3
Curried function evaluation
92
Emulating function factories
95 ■ Implementing reusable
function templates
97
4.4
Partial application and parameter binding
98
Extending the core language
100 ■ Binding into
delayed functions
101
4.5
Composing function pipelines
102
Understanding composition with HTML widgets
102
Functional composition: separating description from
evaluation
104 ■ Composition with functional libraries
107
Coping with pure and impure code
109 ■ Introducing point-free
programming
111
4.6
Managing control flow with functional combinators
112
Identity (I-combinator)
112 ■ Tap (K-combinator)
113
Alternation (OR-combinator)
113 ■ Sequence (S-combinator)
114
Fork (join) combinator
115
4.7
Summary
116
5 Design patterns against complexity 117
5.1
Shortfalls of imperative error handling
118
Error handling with try-catch
118 ■ Reasons not to throw
exceptions in functional programs
119 ■ Problems with
null-checking
121
5.2
Building a better solution: functors
121
Wrapping unsafe values
122 ■ Functors explained
124
5.3
Functional error handling using monads
127
Monads: from control flow to data flow
128 ■ Error handling with
Maybe and Either monads
132 ■ Interacting with external
resources using the IO monad
141
5.4
Monadic chains and compositions
144
5.5
Summary
150
CONTENTS
xii
PART 3 ENHANCING YOUR FUNCTIONAL SKILLS ..........151
6 Bulletproofing your code 153
6.1
Functional programming’s influence on unit tests
154
6.2
Challenges of testing imperative programs
155
Difficulty identifying and decomposing tasks
155
Dependency on shared resources leads to inconsistent results
157
Predefined order of execution
158
6.3
Testing functional code
159
Treating a function as a black box
159 ■ Focusing on business
logic instead of control flow
160 ■ Separating the pure from
the impure with monadic isolation
161 ■ Mocking external
dependencies
164
6.4
Capturing specifications with property-based testing
166
6.5
Measuring effectiveness through code coverage
172
Measuring the effectiveness of testing functional code
173
Measuring the complexity of functional code
177
6.6
Summary
179
7 Functional optimizations 180
7.1
Under the hood of function execution
181
Currying and the function context stack
183 ■ Challenges of
recursive code
186
7.2
Deferring execution using lazy evaluation
188
Avoiding computations with the alternation functional
combinator
189 ■ Taking advantage of shortcut fusion
190
7.3
Implementing a call-when-needed strategy
191
Understanding memoization
192 ■ Memoizing computationally
intensive functions
192 ■ Taking advantage of currying and
memoization
196 ■ Decomposing to maximize memoization
196
Applying memoization to recursive calls
197
7.4
Recursion and tail-call optimization (TCO)
199
Converting non-tail calls to tail calls
201
7.5
Summary
203
CONTENTS
xiii
8 Managing asynchronous events and data 205
8.1
Challenges of asynchronous code
206
Creating temporal dependencies among functions
207
Falling into a callback pyramid
208 ■ Using continuation-
passing style
210
8.2
First-class asynchronous behavior with promises
214
Future method chains
216 ■ Composing synchronous and
asynchronous behavior
221
8.3
Lazy data generation
224
Generators and recursion
226 ■ The Iterator protocol
228
8.4
Functional and reactive programming with RxJS
229
Data as observable sequences
229 ■ Functional and reactive
programming
230 ■ RxJS and promises
233
8.5
Summary
234
appendix JavaScript libraries used in this book
235
index
239
preface
When I was in college and graduate school, my class schedule was
focused on object-oriented design as the sole methodology for
planning and architecting software systems. And, like many
developers, I began my career writing object-oriented code and
building entire systems based on this paradigm.
Throughout my development career, I’ve learned and followed
programming languages closely, not only because I want to learn
something cool, but also because I’m intrigued by the design
decisions and philosophy that each language fosters. Just as a new
language provides a different perspective on how to approach
software problems, a new paradigm can achieve the same effect.
Although the object-oriented approach continues to be the modus
operandi of software design, learning about functional programming
will open your eyes to new techniques that you can use on their own
or in parallel with any other design paradigm that fits your
application.
Functional programming has been around for years, but to me it was
only a minor distraction. I had heard and read about the benefits of
Haskell, Lisp, Scheme, and, more recently, Scala, Clojure, and F# in
terms of expressiveness and being highly productive platforms; even
Java, which has traditionally been known as a verbose language, has
functional artifacts that make code more succinct. Eventually, the
minor distraction became impossible to avoid. And guess what?
JavaScript, that object-oriented language everyone uses, can be
turned around 180 degrees and used functionally. It turns out that
this is the most powerful and effective way to use JavaScript. It took
me a long time to discover this, and in this book I want to make you
aware of it so you don’t have go on wondering why your JavaScript
code is becoming so complex.
xv
PREFACE
xvi
Throughout my journey as a developer, I’ve learned how to use
functional programming principles to create code that is modular,
expressive, robust, easy to reason about, and simple to test. Without
a doubt, this has changed me as a software engineer, so I wanted to
capture and jot down my experiences somehow—perhaps in a book.
Naturally, I approached Manning, with the idea of writing a functional
programming book using the Dart programming language. I was
playing around with Dart at the time and thought that combining it
with my functional background would be a fun, unexplored,
uncharted territory. I wrote a proposal, and a week later I had an
interview. During the interview, I learned that Manning was seeking a
person to write a book about functional programming in JavaScript.
Because JavaScript is a language I’m very much obsessed with, to
say the least, I was thrilled to jump into this opportunity. By writing
this book, I hope to help you develop the same skills and take your
development in a new direction.
acknowledgments
Writing a book is not a trivial undertaking, and the tireless
collaboration of many people with a variety of talents brought to life
the manuscript you’re holding (or reading onscreen).
The staff at Manning were incredible and instrumental in obtaining
the level of quality we all hoped for, and I thank all of them from the
bottom of my heart. Without them, this book would not have been
possible. Special thanks to Marjan Bace and Mike Stephens for
believing in the idea of this book and in me as an author; to Marina
Michaels, for giving me a map and a flashlight to navigate this maze
of book-writing challenges; to Susan Conant, for bringing me up to
speed and teaching me my first lessons about what it means to write
a technical book; to Bert Bates, for giving me my initial sparks of
creativity and for his amazing insights on how to teach programming;
and to everyone on the editorial and production teams, including
Mary Piergies, Janet Vail, Kevin Sullivan, Tiffany Taylor, Katie Tennant,
Dennis Dalinnik, and many others who worked behind the scenes.
I can’t thank enough the amazing group of technical peer reviewers
led by Aleksandar Dragosavljevic—Amy Teng, Andrew Meredith,
Becky Huett, Daniel Lamb, David Barkol, Ed Griebel, Efran Cobisi,
Ezra Simeloff, John Shea, Ken Fukuyama, Peter Edwards, Subhasis
Ghosh, Tanner Slayton, Thorsten Szutzkus, Wilfredo Manrique,
William E. Wheeler, and Yiling Lu—and the talented forum
contributors. Their contributions included catching technical mistakes,
errors in terminology, and typos, and making topic suggestions. Each
pass through the review process and each piece of feedback
implemented through the forum topics shaped and molded the
manuscript.
xvii
ACKNOWLEDGMENTS
xviii
On the technical side, special thanks to Dean Iverson, who served as
the book’s technical editor; Daniel Lamb, who served as the book’s
technical proofreader; and Brian Hanafee, for his thorough and in-
depth evaluation of the entire book. They are the best technical
editors I could have hoped for.
Last but not least, I thank my wife for always supporting me, and my
family for pushing me to become better every day and not asking
why I didn’t call as often to check in while I was writing this book.
Also, thanks go to my colleagues at work for purchasing early
releases of the chapters. I am grateful to have the pleasure of
working alongside such wonderful people.
about this book
Complexity is a huge beast to tame, and we’ll never get rid of it
entirely; it will always be an aspect of software development. I’ve
spent countless hours and immeasurable brainpower trying to
understand what a particular piece of code does. The secret is to
control the complexity so it doesn’t grow in proportion to the size of
your code base—
and functional programming can help. We’re writing more JavaScript
than ever before.
We’ve gone from building small client-side event-handling routines, to
heavy client-side architectures, to complete isomorphic (server +
client) JavaScript applications.
Functional programming isn’t a tool—it’s a way of thinking that can
apply equally to any of these environments.
This book is designed to teach you how to apply functional
programming techniques to your code using ECMAScript 6 JavaScript.
The material is presented at a gradual, steady pace and covers both
theoretical and practical aspects of functional programming. I provide
additional information for advanced readers, to help you get deeper
into some of the harder concepts.
Roadmap
This book has eight chapters and is divided into three parts that
guide you from fundamental building blocks to more-advanced and
practical applications of functional programming.
xix
www.ebook3000.com
ABOUT THIS BOOK
xx
Part 1, “Think functionally,” paints a high-level landscape of functional
JavaScript.
It also discusses core aspects of using JavaScript functionally and
thinking like a functional programmer:
Chapter 1 introduces some of the core functional concepts that are
explained in later chapters and prepares you to make the functional
leap. It introduces the main pillars of functional programming,
including pure functions, side effects, and declarative programming.
Chapter 2 establishes a level playing field for beginning and
intermediate JavaScript developers and acts as a refresher for more-
advanced readers. In addition, it’s sprinkled with basic functional
programming concepts to prepare you for the techniques discussed in
part 2.
Part 2, “Get functional,” focuses on core functional programming
techniques, including function chains, currying, composition, monads,
and more:
Chapter 3 introduces function chains and explores writing programs
as combinations of recursion and high-order functions like map, filter,
and reduce. It teaches these concepts using the Lodash.js
framework.
Chapter 4 covers the popular techniques of currying and composition,
which increase the modularity of your code. Using a functional
framework such as Ramda.js, composition is the glue that
orchestrates your entire JavaScript solution.
Chapter 5 provides a deep dive into more-theoretical areas of
functional programming, with a comprehensive and gradual
discussion of functors and monads in the context of error handling.
Part 3, “Enhancing your functional skills,” discusses the practical
benefits of using functional programming to tackle real-world
challenges:
Chapter 6 reveals the inherent ease with which functional programs
can be unit tested. In addition, it introduces a rigorous, automated
testing mode called property-based testing.
■
Chapter 7 takes a look at JavaScript’s memory model, which is used
to support the evaluation of functions. This chapter also discusses
techniques that help optimize the execution time of functional
JavaScript applications.
Chapter 8 introduces some of the main challenges JavaScript
developers face on a day-to-day basis when dealing with event-driven
and asynchronous behavior. It discusses how functional programming
can provide elegant solutions to reduce the complexity of existing
imperative solutions with a related paradigm known as reactive
programming, implemented using RxJS.
Who should read this book
Functional Programming in JavaScript is written for JavaScript
developers with at least a basic understanding of object-oriented
software and a general awareness of the challenges of modern web
applications. Because JavaScript is such a ubiquitous language,
ABOUT THIS BOOK
xxi
if you want an introduction to functional programming and prefer a
familiar syntax, you can take full advantage of this book instead of
learning Haskell. (If you want to ease your way into Haskell, this
book isn’t the best resource, because each language has its own
idiosyncrasies that are best understood by learning it directly.) The
book will help beginning and intermediate programmers heighten
their JavaScript skills with higher-order functions, closures, function
currying, composition, as well as new JavaScript ES6 features like
lambda expressions, iterators, generators, and promises. Advanced
developers will enjoy the comprehensive coverage of monads and
reactive programming as well, which can help you implement
innovative ways of tackling the arduous task of dealing with event-
driven and asynchronous code, taking full advantage of the
JavaScript platform.
How to use this book
If you’re a beginner or intermediate JavaScript developer and
functional programming is new to you, begin with chapter 1. If you’re
a strong JavaScript programmer, you can skim through chapter 2 and
move quickly into chapter 3, which begins with function chains and
overall functional design.
More-advanced users of functional JavaScript typically understand
pure functions, currying, and composition, so you may skim chapter 4
and move into functors and monads in chapter 5.
Examples and source code
The code examples in this book use ECMAScript 6 JavaScript, which
can run equally well on either the server (Node.js) or the client.
Some examples show I/O and browser DOM APIs, but without regard
for browser incompatibilities. I assume you have experience
interacting at a basic level with HTML pages and the console. No
specific browser-based JavaScript is used.
The book makes heavy use of functional JavaScript libraries like
Lodash.js, Ramda.js, and others. You can find documentation and
installation information in the appendix.
This book contains extensive code listings that showcase functional
techniques and, where appropriate, compare imperative versus
functional designs. You can find all the code samples at the
publisher’s website, https://www.manning.com/books/
functional-programming-in-javascript, and on GitHub at
https://github.com/luijar/
functional-programming-js.
Typographical conventions
The following conventions are used throughout the book:
Italic typeface is used to reference important terms.
Courier typeface is used to denote code listings, as well as elements
and attributes, methods names, classes, functions, and other
programming artifacts.
Code annotations accompany some of the source code listings,
highlighting important concepts.
ABOUT THIS BOOK
xxii
About the author
Luis Atencio (@luijar) is a staff software engineer for Citrix Systems
in Ft. Lauderdale, Florida. He has a B.S. and an M.S. in Computer
Science and now works full-time developing and architecting
applications using JavaScript, Java, and PHP platforms.
Luis is very involved in the community and has presented frequently
at local meetups and conferences. He blogs about software
engineering at luisatencio.net, writes articles for magazines and
DZone, and is also the coauthor of RxJS in Action (forthcoming from
Manning in 2017).
Author Online
Purchase of Functional Programming in 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 the
forum and subscribe to it, point your web browser to
https://www.manning
.com/books/functional-programming-in-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 conduct 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 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
Think functionally
It’s highly probable that most of your experience building professional
applications has been with an object-oriented language. You may
have heard or read about functional programming in other books,
blogs, forums, and magazine articles, but you’ve probably never
written any functional code. Don’t worry; this is to be expected. I’ve
done most of my development in an object-oriented environment as
well. Writing functional code isn’t difficult, but learning to think
functionally and letting go of old habits is. The primary goal of part 1
of this book is to lay the foundation for and prepare your mind to
embrace the functional techniques discussed in parts 2 and 3.
Chapter 1 discusses what functional programming is and the mindset
you need to embrace it; it also introduces some of the most
important techniques based on pure functions, immutability, side
effects, and referential transparency.
These form the backbone of all functional code and will help you
transition into functional more easily. Also, these will be the guiding
principles that set the stage for many of the design decisions we
make in the following chapters.
Chapter 2 provides a first view of JavaScript as a functional language.
Because it’s so ubiquitous and mainstream, it’s an ideal language with
which to teach functional programming. If you aren’t a strong
JavaScript developer, this chapter will bring you up to speed with
everything you need to know to understand functional JavaScript,
such as higher-order functions, closures, and scoping rules.
Becoming functional
This chapter covers
■ Thinking in functional terms
■ Learning the what and why of functional
programming
■ Understanding the principles of immutability
and pure functions
■ Functional programming techniques and their
impact on overall design
OO makes code understandable by encapsulating moving parts.
FP makes code understandable by minimizing moving parts.
—Michael Feathers (Twitter)
If you’re reading this book, chances are you’re a JavaScript developer
with a working knowledge of object-oriented or structured design,
and you’re curious about functional programming. Perhaps you’ve
tried to learn it before and haven’t been able to apply it successfully
at work or on your personal projects. In either case, your main goal
is to advance your development skills and improve the quality of your
code. This book can help you accomplish that.
CHAPTER 1
Becoming functional
The rapid pace of web platforms, the evolution of browsers, and—
most important—the demands of end users have all had a profound
effect on the way we design web applications today. Users demand
that web applications feel more like a native desktop or a mobile app
with rich and responsive widgets. Naturally, these demands force
JavaScript developers to think more broadly about the solution space
and to adopt adequate programming paradigms and best practices
that provide the best possible solutions.
As developers, we gravitate toward frameworks that help us create
extensible and clean application architectures. Yet the complexity of
our codebase still gets out of control, and we’re challenged to
reexamine the basic design principles of our code.
Also, the web of today is radically different than it was years ago for
JavaScript developers, because we can do many things now that
weren’t technically feasible before. We can choose to write large
server-side applications with Node.js or push the bulk of the business
logic onto the client, leaving a thin server behind. In either case, we
need to interact with storage technology, spawn asynchronous
processes, handle events, and much more.
Object-oriented design helps solve part of the problem; but because
JavaScript is such a dynamic language with lots of shared state, it
isn’t long before we accumulate enough complexity to make our code
unwieldy and hard to maintain. Object-oriented design certainly
moves the needle in the right direction, but we need more. Perhaps
you’ve heard the term reactive programming in recent years. This
programming paradigm facilitates working with data flows and
propagation of change. In JavaScript, this is extremely important
when dealing with asynchronous or event-based code. Overall, what
we need is a programming paradigm that encourages us to think
carefully about our data and the functions that interact with it. When
thinking about an application’s design, ask yourself the following
questions in terms of these design principles:
Extensibility—Do I constantly refactor my code to support additional
functionality?
Easy to modularize—If I change one file, is another file affected?
Reusability—Is there a lot of duplication?
■
Testability—Do I struggle to unit test my functions?
Easy to reason about—Is my code unstructured and hard to follow?
If you answer “Yes” or “I don’t know” to any of these questions, then
you’ve picked up the right book as a guide on the path to
productivity. Functional programming (FP) is the programming
paradigm you need. Although it’s based on simple concepts, FP
requires a shift in the way you think about problems. FP isn’t a new
tool or an API, but a different approach to problem solving that will
become intuitive once you understand the basic principles.
In this chapter, I define what functional programming is and tell you
how and why it’s useful and important. I introduce the core principles
of immutability and pure functions and talk about FP techniques and
how those techniques affect your approach to designing programs.
These techniques allow you to easily pick up reactive programming
What is functional programming?
and use it to solve complex JavaScript tasks. But before we can get
into all this, you need to learn why thinking functionally is important
and how it can help you tackle the complexities of JavaScript
programs.
1.1
Can functional programming help?
Learning functional programming has never been as important as it is
today. The development community and major software companies
are starting to realize the benefits of using FP techniques to power
their business applications. Nowadays, most major programming
languages (Scala, Java 8, F#, Python, JavaScript, and many more)
provide either native or API-based functional support. Hence, FP skills
are in high demand now and will continue to be in the years to come.
In the context of JavaScript, an FP mindset can be used to shape the
incredibly expressive nature of the language and help you write code
that is clean, modular, testable, and succinct so that you can be more
productive at work. For many years, we’ve neglected the fact that
JavaScript can be written more effectively in a functional style.
This neglect is partly due to an overall misunderstanding of the
JavaScript language, and also due to JavaScript’s lack of native
constructs to properly manage state; it’s a dynamic platform that
places the burden of managing this state on us (the ones responsible
for introducing bugs into our applications). This may work well for
small scripts, but it becomes harder to control as your code base
grows. In a way, I think FP
protects you from JavaScript itself. I discuss this further in chapter 2.
Writing functional JavaScript code addresses most of these concerns.
Using a set of proven techniques and practices based on pure
functions, you can write code that is easy to reason about in the face
of increasing complexity. Writing JavaScript functionally is a two-for-
one deal, because you not only improve the quality of your entire
application, but also gain more proficiency in and a better
understanding of the JavaScript language.
Because functional programming isn’t a framework or a tool, but a
way of writing code, thinking functionally is radically different from
thinking in object-oriented terms. But how do you become functional?
How do you begin to think functionally?
Functional programming is intuitive once you’ve grasped its essence.
Unlearning old habits is the hardest part and can be a huge paradigm
shift for most people who come from an object-oriented background.
Before you can learn to think functionally, first you must learn what
FP is.
1.2
What is functional programming?
In simple terms, functional programming is a software development
style that places a major emphasis on the use of functions. You might
say, “Well, I already use functions on a day-to-day basis at work;
what’s the difference?” As I mentioned earlier, FP
requires you to think a bit differently about how to approach the
tasks you’re facing.
It’s not a matter of just applying functions to come up with a result;
the goal, rather, is to abstract control flows and operations on data
with functions in order to avoid side effects
CHAPTER 1
Becoming functional
and reduce mutation of state in your application. I know this sounds
like a mouthful, but I’ll visit each of these terms further and build on
them throughout the book.
Normally, FP books start with computing Fibonacci numbers, but I’d
rather start with a simple JavaScript program that displays text on an
HTML page. What better text to print than the good ol’ “Hello World”:
document.querySelector('#msg').innerHTML = '<h1>Hello
World</h1>'; NOTE
I mentioned earlier that because functional programming isn’t a
specific tool, but a way of writing code, you can apply it to write
client-side (browser-based) as well as server-side applications
(Node.js). Opening the browser and typing in some code is probably
the easiest way to get JavaScript up and running, and that’s all you’ll
need for this book.
This program is simple, but because everything is hardcoded, you
can’t use it to display messages dynamically. Say you wanted to
change the formatting, the content, or perhaps the target element;
you’d need to rewrite this entire expression. Maybe you decide to
wrap this code with a function and make the change points
parameters, so you can write it once and use it with any
configuration:
function printMessage(elementId, format, message) {
document.querySelector(`#${elementId}`).innerHTML =
`<${format}>${message}</${format}>`;
printMessage('msg', 'h1','Hello World');
An improvement, indeed, but still not a completely reusable piece of
code. Suppose you want to write to a file instead of an HTML page.
You need to take the simple thought process of creating
parameterized functions to a different level, where parameters aren’t
just scalar values but can also be functions themselves that provide
additional functionality. Functional programming is a bit like using
functions on steroids, because your sole objective is to evaluate and
combine lots of functions with others to achieve greater behavior. I’ll
fast-forward a bit and show you a sneak peek at this same program
using a functional approach.
Listing 1.1
Functional printMessage
var printMessage = run(addToDom('msg'), h1, echo);
printMessage('Hello World');
Without a doubt, this looks radically different than the original. For
starters, h1 isn’t a scalar anymore; it’s a function just like addToDom
and echo. Visually, it feels as though you’re creating a function from
smaller functions.
There’s a reason for this madness. Listing 1.1 captures the process of
decomposing a program into smaller pieces that are more reusable,
more reliable, and easier to
What is functional programming?
understand, and then combining them to form an entire program that
is easier to reason about as a whole. Every functional program
follows this fundamental principle.
For the time being, you’ll use a magical function, run,1 to invoke a
series of functions sequentially, such as addToDom, h1, and echo. I’ll
explain run in detail later. Behind the scenes, it basically links each
function in a chain-like manner by passing the return value of one as
input to the next. In this case, the string “Hello World” returned from
echo is passed into h1, and the result is finally passed into
addToDom.
Why does the functional solution look this way? I like to think of it as
basically parameterizing your code so that you can easily change it in
a noninvasive manner—
like adjusting an algorithm’s initial conditions. With this foundation
laid, you can now easily augment printMessage to repeat the
message twice, use an h2 header, and write to the console instead of
the DOM, all without having to rewrite any of the internal logic.
Listing 1.2
Extending printMessage
var printMessage = run(console.log, repeat(3), h2, echo);
printMessage('Get Functional');
This visually distinct approach isn’t accidental. When comparing the
functional to the nonfunctional solution, you may have noticed that
there’s a radical difference in style.
Both print the same output, yet they look very different. This is due
to FP’s inherent declarative mode of development. In order to fully
understand functional programming, first you must learn the
fundamental concepts on which it’s based:
Declarative programming
Pure functions
Referential transparency
Immutability
1.2.1
Functional programming is declarative
Functional programming falls under the umbrella of declarative
programming paradigms: it’s a paradigm that expresses a set of
operations without revealing how they’re implemented or how data
flows through them. The more popular models used today, though,
are imperative or procedural, and are supported in most structured
and object-oriented languages like Java, C#, C++, and others.
Imperative programming treats a computer program as merely a
sequence of top-to-bottom statements that changes the state of the
system in order to compute a result.
For more details on this provisional run function, visit
http://mng.bz/nmax.
CHAPTER 1
Becoming functional
Let’s look at a simple imperative example. Suppose you need to
square all the numbers in an array. An imperative program follows
these steps: var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for(let i = 0; i < array.length; i++) {
array[i] = Math.pow(array[i], 2);
array; //-> [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Imperative programming tells the computer, in great detail, how to
perform a certain task (looping through and applying the square
formula to each number, in this case).
This is the most common way of writing this code and will most likely
be your first approach to tackling this problem.
Declarative programming, on the other hand, separates program
description from evaluation. It focuses on the use of expressions to
describe what the logic of a program is without necessarily specifying
its control flow or state changes. An example of declarative
programming is found in SQL statements. SQL queries are composed
of statements that describe what the outcome of a query should look
like, abstracting the internal mechanism for data retrieval. In chapter
3, I show an example of using a SQL-like overlay over your functional
code to give meaning to both your application and the data that runs
through it.
Shifting to a functional approach to tackle this same task, you only
need to be concerned with applying the right behavior at each
element and cede control of looping to other parts of the system. You
can let Array.map() do most of the heavy lifting:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(
function(num) {
Map takes a function
return Math.pow(num, 2);
that computes the
});
square of each number
//-> [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Compared with the previous example, you see that this code frees
you from the responsibility of properly managing a loop counter and
array index access; put simply, the more code you have, the more
places there are for bugs to occur. Also, standard loops aren’t
reusable artifacts unless they’re abstracted with functions. And that’s
precisely what we’ll do. In chapter 3, I demonstrate how to remove
manual loops completely from your code in favor of first-class,
higher-order functions like map, reduce, and filter, which accept
functions as parameters so that your code is more reusable,
extensible, and declarative.
This is what I did with the magical run function in listings 1.1 and
1.2.
Abstracting loops with functions lets you take advantage of lambda
expressions or arrow functions, introduced in ES6 JavaScript. Lambda
expressions provide a succinct alternative to anonymous functions
that can be passed in as a function argument, in the spirit of writing
less:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(num => Math.pow(num, 2));
//-> [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
What is functional programming?
Translating lambda notation to regular function notation
Lambda expressions provide an enormous syntactical advantage over
regular function notations because they reduce the structure of a
function call down to the most important pieces. This ES6 lambda
expression
num => Math.pow(num, 2)
is equivalent to the following function:
function(num) {
return Math.pow(num, 2);
}
Why remove loops from your code? A loop is an imperative control
structure that’s hard to reuse and difficult to plug in to other
operations. In addition, it implies code that’s constantly changing or
mutating in response to new iterations. You’ll learn that functional
programs aim for statelessness and immutability as much as possible.
Stateless code has zero chance of changing or breaking global state.
To achieve this, you’ll use functions that avoid side effects and
changes of state, known as pure functions.
1.2.2
Pure functions and the problem with side effects
Functional programming is based on the premise that you build
immutable programs based on the building blocks of pure functions.
A pure function has the following qualities:
It depends only on the input provided and not on any hidden or
external state that may change during its evaluation or between calls.
It doesn’t inflict changes beyond their scope, such as modifying a
global object or a parameter passed by reference.
Intuitively, any function that doesn’t meet these requirements is
“impure.” Programming with immutability can feel strange at first.
After all, the whole point of imperative design, which is what we’re
accustomed to, is to declare that variables are to mutate from one
statement to the next (they’re “variable,” after all). This is a natural
thing for us to do. Consider the following function:
var counter = 0;
function increment() {
Other documents randomly have
different content
Saucy girl! her mind seems only filled with lovers. But she would
have her way, and the whole day passed in this occupation. She
boldly untied each package, and resolutely determined I should tell
her the little history appended to each in my memory. The one I held
in my hand when she entered, was first taken up; and we both shed
tears over the sad story it recalled of friendship, love, and a broken-
heart. It is too sad a tale for me to relate to you now, dear reader,
for I am not in the tearful mood. Some gloomy, “gray” day, as Kate
says, I will again recall it, and see if you will sympathize with the
past as did dear Kate Wilson. I have digressed so much already, that
I will take up one of the smallest packages now, and relate to you
the history of my school-girl friend, Lolah Lalande, as she was called
then. Her name is now more famous; but I will keep that a secret
until I arrive at the end of my story. It was a small packet,
containing only a few French letters, a tress of long, glossy black
hair, and a crayon sketch of a childish figure in Spanish costume, and
in one of the attitudes of a Spanish national dance. It had a
beautiful, girlish face, clear, dark eyes—long, sweeping hair—arched,
delicately formed brows—and rich, full lips. That face has turned the
head of a monarch, it is said—but I will not anticipate.
“Tell me this, dear Miss Enna,” said Kate, as she looked at the
contents of the package. “It could not have been a friendship of long
standing—so little remains of it; therefore you will only have a tiny,
little story for me, and I will not teaze you again until—to-morrow, or
the next gray, rainy day.”
Kate listened with affectionate interest; and I’ll never forgive you,
reader, if you are not as indulgent as Kate. But I will seek your favor
in the words of Spenser:
“Goe, little worke! thyself present,
As child whose parent is unkent,
To him that is the President
Of Noblenesse and Chivalrie;
And when thou art past jeopardie,
Come tell me what was said of mee,
And I will send more after thee.”
Surely, now, if I say to you such delicate words as these, which
Spenser gave to that “noble and virtuous gentleman, most worthy of
all titles, both of learning and chivalry, Master Philip Sidney,” you
cannot but listen complacently.
When about twelve or thirteen years of age, I was placed at the
fashionable establishment of Madame Lalande, to perfect my French
pronunciation. Being a shy child, I drew away from the different
cliques of the school, during my play hours, and gave myself up to
sad recollections of home and my darling little brothers and sisters.
The girls laughed at me, and called me “a mope,” which served only
to increase my shyness. The Madame was exceedingly kind to me;
but I only saw her in the evening, when we all assembled in the
large drawing-rooms to dance, promenade, and converse sociably
together under her superintendence. A few evenings after my
arrival, while I was studiously endeavoring to make my petite figure
still smaller, by hiding behind a harp-case which stood in a corner of
the back drawing-room, to my exquisite terror, I saw the Madame
approach me, holding by the hand a beautiful child, apparently
about my own age.
“Mademoiselle Duval,” she said, “you must join in the dancing.
You and my niece, Lolah, are about the same size; you will make
good partners for each other. Lola, ma chère, I depend upon you to
entertain our new pupil.”
The little girl approached me kindly, and taking my trembling
hand, said,
“Will you not dance with me?”
I did not dare to refuse, but accompanied her to a quadrille,
(cotillions, we called them in those days,) just forming near us,
feeling as awkward and shy as a home-girl might be expected to
feel, thrown, for the first time, in a crowd of nearly a hundred girls.
The first figures of the quadrille I danced awkwardly enough, giving
my little partner good reason to think I did not know my right hand
from my left; but I soon forgot my mauvaise honte, in the pleasant
chatting of the little Lolah, who told me of all the little enjoyments
she had. Her “chère tante,” as she called Madame Lalande, had
taken her the night before to an Opera, for the first time in her life;
and, of course, her little head was filled with recollections of it. She
described, with French volubility, and in a most graphic manner, the
story of the Opera, the different scènas, and the dresses. I was so
new to all such things, that I suppose she could not have found a
more agreeable listener in the whole school; and we were mutually
pleased with each other. We danced every quadrille together; and
she most patronizingly waltzed with me in a corner of the drawing-
room, until I could summon sufficient courage to venture in the large
circle in the centre of the rooms. At ten o’clock we bade good night
to each other, she promising, as her cherry lips kissed affectionately
my mouth and cheeks, that she would persuade chère tante to take
me some night with them to the Opera—a promise which she kept.
From that night I no longer felt lonely in the school—Lolah was
my companion. Though a year or so my junior, she was quite as far
advanced in mind; and we were thrown a great deal together in our
studies, and with the easy confidence of childhood, we became
bosom friends. Lolah was a great favorite in the school. The elder
girls courted her for her influence with the Madame and the
governesses, and the younger ones gathered around her because
she was always merry, kind, and generous. She was a darling little
creature—exceedingly pretty. She had full, large, dark eyes, an oval
face, with a rich brunette complexion, and glossy hair, black as
night. Her figure was slight, but perfectly formed; and she was the
most graceful child I ever saw. The little queen of the Viennoise
corps, darling little Fanny Prager, always reminds me of Lolah. She is
not so pretty, but her graceful movements, her evident superiority
over the rest of the troupe, her commanding little step, her apparent
freedom from vanity, and her cleverness in forming the different
tableaux and groups, bring Lolah to my mind; and while looking at
her, I find myself loving the child as I used to love Lolah Lalande in
my school days.
With the dancing-master Lolah was an especial favorite. She
early gave evidence of a decided partiality for dancing; and Madame
Lalande availed herself of every opportunity that offered to improve
the child in her favorite accomplishment. Polkas, Redowas, and
Mazurkas, were not known in those days; but the dancing-master, in
those times, grew eloquent over Gavottes, Shawl Dances, and the
expressive and graceful Spanish Waltzes. With delighted earnestness
would Lolah go through her different dances; and Monsieur Neillet
would almost expire with ecstacy. The Monsieur had been educated
in the Parisian school, a pupil of La Conservatoire, and had even
danced in a ballet before the august Emperor and Empress. With
eager eloquence he would dilate upon Lolah’s wonderful gift to the
Madame, and with great concern and grief, lament that she could
not become a professional danseuse. Then he would give most
tempting accounts of the immense sums of money made by the
great danseuses of Europe.
“I trust, Monsieur,” the Madame would always reply, “I trust that
my dear Lolah will never be forced to support herself by such a
dangerous and exposed profession. While I live, she will be always
sure of a home; and I earnestly pray I may have strength to collect
for her before I die, a competency sufficient to place her above
want.”
Lolah was called the niece of Madame Lalande, and went by her
name. She loved the Madame passionately, who treated her with the
greatest indulgence—indulgence that was never abused by Lolah,
however, for she was an excellent, obedient child. Soon after my
arrival, I noticed mysterious allusions made by some of the elder
girls, when speaking of Lolah, which led me to question the
relationship which Lolah bore to Madame Lalande. The curiosity
excited in me was at last gratified by Lolah herself, who, after I had
been some months at the school, told me that Madame Lalande had
owned to her that she was not in truth her niece; that she was an
orphan, whose parents had come from Ireland, before her birth, to
settle in America; they had been in very humble circumstances. The
mother of Lolah had been employed by Madame Lalande as a
seamstress, and the Madame became very much interested in her.
When Lolah was an infant, both parents were seized with an
epidemic, and died within a few hours of each other. Madame
Lalande promised them on their deathbeds she would adopt the
infant Lolah, and take care of her so long as she lived. The Madame
intended at first to bring up the child in a plain manner, and when
old enough, have her taught some trade, by which she might
support herself, and be independent; but Lolah proved so intelligent
and beautiful, that she resolved to educate her well, and do her best
by her, looking upon her as her own child.
“How can I ever repay ma chère tante for her kindness!” would
the warm-hearted girl exclaim over and again, her fine, dark eyes
dilating with emotion, and filling with tears, when with girlish
frankness she would allude to the story of her birth.
When I had been about two years with Madame Lalande, she
resolved, very much against the wishes of her friends, to remove to
Paris. She had always pined for her home during the ten or twelve
years she had resided in America. She had been fortunate, and laid
up some little money, with which she fancied she could establish a
large school at “home,” and realize larger profits. Her health was but
indifferent. She was, in fact, suffering from maladie du pays; and
she gave up the fine school she had been so lucky in establishing in
America, to grasp at an uncertainty in her own beloved Paris. Her
friends reasoned, but in vain; she said the letters she received from
her friends in Paris, assured her that her circumstances would be
infinitely improved by a removal there. Lolah and I parted with many
tears and promises for the future. The long tress of her beautiful
hair, and the crayon sketch which had been made of her by her
drawing-master, were her little gifts to me—gifts which I have
treasured carefully. After their arrival in Paris, she wrote to me, and
a few letters passed between us; but only a few. I never received
but two or three from Lolah, and then the correspondence on her
side ceased. I continued writing for a year or more, but at last gave
it up; and year after year passed without bringing any information to
me of her. I remember well what sad tears I shed over that little
packet, when I first put it away in my desk; for a year or more I
could not bear to open it, so miserable did the little drawing and lock
of hair make me feel. Some clever German writer says, “Children live
in a world of imagination and feeling;” thus I at last soothed my
aching heart by imaginings of the future, and dreaming happy day-
visions of a reunion with my darling Lolah.
A year or two since, my father’s health grew delicate, and his
physicians thought a sea voyage would prove beneficial. A visit to
Europe was recommended, and I, of course, accompanied him. We
spent some time abroad, traveling over those parts of the Continent
most interesting to him, from early intellectual pursuits and
associations. While we were at Munich, the Bavarian capital, we
heard that the famous dancer, Lola Montes, was there, creating a
great excitement. The strange stories we had heard of this
remarkable woman, made us feel desirous to see her; and,
accordingly, one evening we went to the theatre to gratify our
curiosity. I could scarcely refrain from a loud exclamation when this
danseuse appeared upon the stage. She was dressed in Spanish
costume, as she was about to execute a favorite Spanish dance. A
rich costly veil floated around her head, and her long, glossy hair
hung in heavy, dark braids, looped, and bound with glittering gems.
It was Lolah Lalande. Love could not be deceived; and tears sprung
to my eyes as I recalled our girlish friendship. Had she been in any
other dress, I might have failed to trace the resemblance so quickly;
but I had so often seen her in that Spanish costume—it was similar
to the crayon sketch—it was the dress she most affected at the
dancing parties at school, because the Spanish waltzes were her
favorite dances when a child; and she always danced them dressed
in the beautiful, becoming national costume. How anxiously I noted
every movement, traced every feature—it was Lolah herself I felt
convinced, although changed. A fierté cold expression overspread
her face, and her brilliant eyes flashed a little disdainfully at times,
as she seemed to command and exact applause as a right. There
was no glittering, set, stage-smile upon her face, but a cold, haughty
recognition was all that she gave to any mark of approbation from
the audience. Her style of dancing was different from any I had ever
seen on the stage. I had admired the childish beauty of Carlotta
Grisi’s dancing; the voluptuous Cerito’s; the fascinating, refined
Ellsler’s, and the dignified, intellectual Taglioni’s; but Montes’—no,
Lolah Lalande’s—seemed to me—it might have been from childish
association—more entrancing than any other, although those who
were with me, and who were, undoubtedly, good judges, better than
I, condemned her style; but when woman’s heart begins to act,
good-by to her judgment. Lolah had grown tall; and though still
exquisitely graceful, as in childhood, she seemed remarkably strong
and commanding. Other dancers, I thought, might be compared to a
Hebe or a Venus, but Lolah seemed a Juno and Pallas united; and I
quoted to my clever critic friends the lines with which I have headed
this sketch, —
“She can show art rules to astonish her.
And what the muses would with study find,
She teaches in her dancing.”
I only saw her that night. The next day we left Munich, and I
never saw her again. From a gentleman I met afterward in Paris,
and who had known Montes from the time of her first appearance in
public, I learned that extreme poverty had driven her to the stage.
She had not been educated for it as a profession; and the touching
account he gave me of her trials, united with my own knowledge of
Lolah Lalande’s history, convinced me that Lolah Lalande and Lolah
Montes were, as I had imagined, one and the same person.
Soon after their arrival in Paris, Madame Lalande discovered that
her move had been an injudicious one. Success did not attend her as
she expected; the château d’Espagne she had created was never
realized; and she found herself, although in her “home,” the
residence of her childhood, among strangers; old associates were
dead, or had formed new connections. Day by day passed, and the
little capital she had collected in America, and which was to establish
the grand school in Paris for les jeunes demoiselles of the nobility,
gradually melted away; and she at last resolved to bid an eternal
farewell to Paris, and return, though with mortified feelings, to the
school in America she had with such blind willfulness given up. But
just as she had come to this conclusion, and Lolah was gladly
making preparations for their return, sickness, caused by extreme
chagrin and disappointment, attacked chère tante. This sickness was
lingering, and at last, bitter, actual poverty stared them in the face.
“What am I to do?” exclaimed poor Lolah, one day, as she turned
from the apothecary’s door, to whom she had just paid her last coin
for medicine for chère tante. Gay equipages dashed past her; and
the busy, bustling crowd moved by, unheeding the misery of that
pale, friendless girl. “God help me,” she murmured, in a thick, hoarse
voice. Sorrow and want had dried up her tears—the real poor
seldom weep. She turned to seek her wretched home, which,
miserable as it was, she knew not how long it might remain to them.
Faint and exhausted with hunger and anxiety, she could scarcely
drag her little feet along the pavé. Regardless of her movements,
she stumbled over a stone; a kind person passing, caught her as she
fell, and upon lifting her eyes to thank him, she recognized Monsieur
Neillet.
“Ah, Mademoiselle Lolah! can this be you?” he exclaimed. “I have
been seeking in vain for Madame Lalande’s residence ever since I
reached Paris;” and then followed a host of questions and
explanations.
The Monsieur had come over to Paris for new dances. A rival had
appeared in the city, where he had so long been the favorite
teacher; and the Americans were raving for new figures. His
gavottes and shawl dances were voted obsolete, and out of date;
and he had been dethroned by the children of his former pupils, to
make way for the new teacher, who came over fresh from Paris with
gallopes and figures of the newest fashion. He could scarcely realize
it until he found his hours unoccupied, his school-list, that had
formerly been filled to overflowing, without a single name; then,
with laudable courage and energy, he resolved to take the little
independence he had collected, return to chère Paris—but not as a
sober Englishman or Scotchman would have done, live quietly on it
for the rest of his days—oh, no! he pined for revenge. What was life
to a Frenchman without a triumph? “Inglorious ease” he scorned.
No! he, too, would learn new dances; he would return to the scene
of his former power, but late discomfiture, and hurl the
presumptuous usurper from his throne. He, too, would flourish in
gallopes and new figures.
The sight of Lolah suffering from poverty and trouble, touched
his warm heart, but gave a new impulse to his thoughts. Monsieur
Neillet was kind and generous; but, like all Frenchmen, ambitious
and enthusiastic. He aided the poor Madame, relieved their
distresses, and asked but one return—to bring his pet pupil out upon
the stage. She consented. Poverty and necessity had humbled
Madame Lalande’s pride—and Lolah became a public danseuse.
Success attended her; and Monsieur Neillet had the satisfaction
of seeing his little Mademoiselle Lolah ride in the grand carriage, and
receive the intoxicating plaudits he had wished for her, when in
Madame Lalande’s school, in America, she had executed à ravir his
favorite gavottes and Spanish waltzes.
I never saw Lolah again. I struggled with my feelings in
exercising this self-denial; but I knew we had both altered, and I felt
that I had rather retain the recollection of our girlish, loving
intercourse undimmed. She was a public danseuse, rich, courted,
and, the world said, free in her morals—I, a plain, unknown woman,
with tastes, associations, and opinions widely differing from hers.
Better to retain the bright recollection of the past, and the uncertain
knowledge of the present, than to risk coldness, or even a realization
of what I feared—that Lolah Montes, the woman, was not the
innocent, pure, guileless Lolah Lalande of school memory. Many may
censure, and call this the cold reasoning of a woman bound down by
conventional prejudices; but how else is a woman to be governed, if
she wishes to secure, not her own happiness, but the happiness of
those around her; and living in a conventional world, she be not
directed and ruled by this same reasoning, which is called cold and
cramping? The gentle graces of charity and indulgence to the
frailties of others, are beautiful, and should be peculiar qualities of
the feminine character; but they may be extended too far, and
instead of giving a helping hand to suffering, oppressed virtue,
encourage evil.
“After all,” said my father, one moonlight evening, as we sat on
the deck of the vessel, “Homeward Bound,” watching the silver flood
of light streaming down upon the billows, and discussing this same
subject, “after all, Enna, she may not be Lolah Lalande, it may only
be a woman’s fancy and imaginings.”
I did not reply; but the recollection of that lovely form, rich, dark,
soul-subduing eyes, and flowing hair, with the delicate brow, and
full, red, laughing lips, came before me strangely blended with the
cold, fierté expression of the tall, beautiful danseuse I looked at in
Munich with tearful eyes. . . .
“I’d have seen her,” said Kate, when I concluded; “I would at
least have satisfied myself.”
“So would I, dear Kate,” I replied, “at your age; but when you are
older, you will argue differently. A recollection of pleasure is better
than a reality of pain.”
Painted by Sir Joshua Reynolds Engraved by H. S. Wagner
THE FIRST LOSS.
Engraved Expressly for Graham’s Magazine
THE FIRST LOSS.
WITH AN ENGRAVING.
’Tis her first loss, and tear-drops fall
Upon her cherished friend,
Whose voice once echoed to her call—
Whose wants she loved to tend.
’Tis her first grief. Alas! that life
Full many a care will bring,
With keener pang and sharper strife,
That gentle heart to wring.
REVIEW OF NEW BOOKS.
History of the Conquest of Peru. With a Preliminary View of
the Civilization of the Incas. By William H. Prescott. New
York: Harper & Brothers. 2 vols. 8vo.
It would be impossible in the narrow limits of our magazine to do
justice to a work of such labor and ability as this. Mr. Prescott has
displayed the same qualities of mind, and the same energy of
character, in his History of Peru as of Mexico. Nothing relating to the
subject in a printed or manuscript form seems to have escaped his
diligent researches, and the facts of his narrative are thus placed on
a foundation of authorities which cannot be disputed. Men who
investigate with such minute care as Mr. Prescott are not generally
those who can compose readable histories. They are commonly but
compilers of materials for the use of abler writers. But our
countryman is an artist as well as antiquary. He spares no labor, it is
true, in collecting his materials, and might claim, if he chose, the
highest rank among the disciples of Dr. Dryasdust; but such would
be but a small object for his ambition. His glory as a historian comes
from his power to collect truth from a mass of perhaps conflicting
testimony; to perceive character so accurately as to see just that
point in the mind of a contemporary chronicler, where his individual
bias casts ominous conjecture on his testimony; to imbue his mind
with the very spirit of the age he has chosen for his subject; to look
at events from the same position occupied by the actors in them,
and thus enable the reader to pass beyond actions to motives; and,
above all, to represent the period of time he has selected for his
theme in the clearest light, giving to persons and events their
natural prominence, and avoiding all interference with their just
relations.
The reader of Mr. Prescott’s histories is almost made for the time
a contemporary of Ferdinand, Cortez and Pizarro; a contemporary
who sees clearly the passions and bigotries which warp their moral
judgments, and while uninfluenced himself by the prejudices which
blind them, blends charity with justice in deciding upon their actions.
There is a healthiness in Mr. Prescott’s intellect which places all
objects in “daylight.” They are not discolored in passing through his
mind.
His style of composition, a style so flexible as to yield readily to
all the changes of his narrative, a style which ever fascinates and
never wearies, has drawn forth numberless panegyrics. We think the
style of his present book even more pleasant than that of his others.
There is hardly a passage, hardly a sentence, of fine writing—of
writing, not for the sake of the thought but of the rhetoric—in the
whole work. This wise abstinence in one who has such a wide
command of the resources of language, and who could, if he
pleased, pile up pages of rhetorical sublimities to catch the untrained
eye, is a great merit, and is so felt by the reader, when at the end of
the book he notices its unity of effect upon his mind.
The subject of Mr. Prescott’s present history may not seem, at
first, so good as that of the Conquest of Mexico. It would be difficult
to say which work was filled with the most wonderful events. Both
are laden with examples of courage, constancy, and endurance,
which appear beyond the powers of humanity. Both represent men
undaunted not merely in battle with vastly superior forces, but
bearing up against the yet fiercer assaults of fatigue, pestilence and
famine. In all the hardier qualities of mind and body the Spaniards
who conquered Peru do not yield to the followers of Cortez, and in
avarice, treachery, and cruelty, in all those qualities which
characterize freebooters and pirates, they fairly exceed all other
men. Mr. Prescott has done them ample justice, and brought out in
bold relief their characters and exploits. His delineations of Pizarro
and his brothers are masterly, and his whole view of the country
before and after the conquest is marked by uncommon
comprehension, and the most extensive erudition. The preliminary
essay, on the civilization of the Incas, is of very great value. In
clearness of exposition it is almost unmatched. Altogether, the book
must add even to Mr. Prescott’s reputation, in all those qualities of
mind and style for which he is distinguished.
Modern Painters. By a Graduate of Oxford. First American
from the Third London Edition. Revised by the Author.
New York: Wiley & Putnam. 1 vol. 12mo.
It is rare that we see so eloquent and vigorous a production as
this, announcing high principles of art with such unhesitating
confidence, and supporting them with so much splendor of style and
fertility of illustration. The freshness and animation of the author’s
mind are displayed on every page, lending life to the discussion of
the most abstract questions of taste, and prompting continually the
heartiest bursts of eloquence. The work has caused a sensation
among the artists and amateurs of England, and has been made the
subject of much discussion in the reviews and magazines. Its
general tone is manly and independent, sliding, often, it must be
allowed, into a kind of dictatorial dogmatism, but still giving
evidence of a firm grasp of the subject, and of a capacity to support
all its positions by argument and illustration. Apart from the leading
object of the book, there are many sentences which bring out
important truths in a strong light, and numerous passages of beauty
and power to stir and elevate the reader’s mind. Here is a great
truth finely expressed: “We must be cautious not to lose sight of the
real use of what has been left us by antiquity, nor to take that as a
model for perfection which is, in many cases, only a guide to it. The
picture which is looked to for an interpretation of nature is
invaluable, but the picture which is taken as a substitute for nature,
had better be burned; and the young artist, while he should shrink
with horror from the iconoclast who would tear from him every
landmark and light which has been bequeathed him by the ancients,
and leave him in a liberated childhood, may be equally certain of
being betrayed by those who would give him the power and
knowledge of past time, and then fetter his strength from all
advance, and bend his eyes backward on a beaten path—who would
thrust canvas between him and the sky, and tradition between him
and God.”
We cordially advise our readers to peruse this book. They may
find much in it to which they cannot assent, but it will be sure to
rouse and refresh their minds.
Conversations in Rome. Between an Artist, a Catholic, and a
Critic. By William Ellery Channing. Boston: Crosby &
Nichols. 1 vol. 12mo.
Mr. Channing is a gentleman engaged in the occupation of acting
out himself. The present elegant little volume is a record of himself
as influenced by Italy. Though cast in the form of conversations, one
mind is discernible in all that is said. The author gives his personal
impressions of all he sees, and judges every thing from the manner
it affects him. From his positive manner of utterance, one would
conclude he saw no distinction between his impressions of things
and the truth of things: a distinction which his readers will often be
compelled to make. Painting, sculpture, poetry, manners, religion,
government, all are disposed of in short-hand judgments. It is really
edifying to find knots which centuries of philosophers have been
unable to untie, so unceremoniously cut by Mr. Channing. This
decisive way of settling debated questions lends much raciness to
the volume, and many of the observations are acute and well put:
others are sheer presumption and impertinence. Mr. Channing is
really a man possessing genius, and it is often provoking to see his
seeming anxiety to pass with others as a coxcomb. Both in the
present volume and in his poems there is often displayed a fineness
of faculty, which, under careful training, would give him a prominent
rank among American writers. At present he is only “recognized” by
a clique. Within that magic circle he passes for little less than a
prophet; out of it he is simply a transcendental target for
descendental jests. If he ever works his way out of his present
environment of egoism, and discerns the path which leads to other
minds, his real merit will be acknowledged. Our readers will find
much in his present volume which will well repay its perusal.
Life and Religious Opinions and Experiences of Madame de
la Mothe Guyon, together with some Account of the
Personal History and Religious Opinions of Fenelon. By
Thomas C. Upham. New York: Harper & Brothers. 2
vols. 12mo.
Professor Upham has performed a service to literature as well as
theology by his present work. It is an account of a remarkable
woman, carefully following the statements contained in her own
autobiography, and written in a style of sweet serenity, in which the
very spirit of Madame Guyon seems mirrored. No one can read the
book without having his knowledge of the higher and subtler
phenomena of the mind extended. It exhibits a human soul in that
state of religious exaltation, where every thing is viewed in its
relation to God, and all the evils of life taken as proofs of God’s love.
The delineation is not ideal but actual. Every step in the upward
progress of her soul is minutely marked, and the whole phenomena
of her consciousness laid open to inspection. The value of the book
is enhanced by the clear revelation of an order of feelings and
thoughts, which are too commonly overlooked in treatises on
metaphysics and theology. Goethe must have studied the character
of Madame Guyon very attentively, before he ventured upon the
delineation of the devotee in Wilhelm Meister.
The Autobiography of Goethe. Edited by Parke Godwin.
Parts III. and IV. New York: Wiley & Putnam.
The present volume completes this most valuable work, now for
the first time “done” into good English. No better period for the
successful publication of the book could have been selected. The
character and writings of Goethe are now continually made the
subjects of eager praise or fierce invective, even among classes of
readers whose curiosity rarely extends beyond the last novel. Much
both of the praise and blame squandered upon the great German is
directed against a mere man of straw, bearing little resemblance to
the real object. Few of the vehement writers and talkers about
Goethe have taken upon themselves the task of reading and
investigation. His autobiography presents the man and his mind as
they appeared to his own consciousness, and certainly constitutes
one of the most remarkable biographies in literature. It is Goethe’s
portrait drawn by himself, and done with matchless skill. It is worthy
of the most profound study. We should pity the person who could
carefully meditate it without having his knowledge of human nature
increased. That vast mind here discourses of itself with the simplicity
of a child.
Morceaux Choisis des Auteurs Modernes. By F. M. Rowon.
Revised, Corrected and Enlarged by J. L. Jewett. New
York: D. Appleton & Co. 1 vol. 12mo.
Such a volume as this has long been needed in our schools and
academies. Most of the selections from French authors studied by
new beginners, are made from writers of the old school. But within
the last twenty or thirty years there has occurred a kind of idiomatic
revolution in the language, of which the pieces in the present work
are an exemplification. The volume contains selections from Balzac,
Dumas, Victor Hugo, Jules Janin, Lamartine, Sue, Guizot, Michelet,
Thiers, Thierry, Sismondi, Tocqueville, Villemain, and other
celebrated French prose writers of the present day, with translations
of difficult phrases at the bottom of each page. It will be found a
most valuable and interesting French reader.
1776, or the War of Independence.
A beautiful volume bearing this title has been laid upon our table
by the publisher, Mr. Walker, of New York. The work was prepared by
Mr. Benson J. Lossing, and dedicated by him to the youth of our
country, “upon whom will soon devolve the faithful guardianship of
our goodly heritage.” A cursory glance at its contents impresses us
very favorably, as it appears to contain a compendious and well
written account of the original history of the American colonies, the
causes which induced their determination to separate themselves
from a connection with the British government, and the difficulties
and dangers through which this design was carried into effect, and a
free republic established.
The publisher says he “always believed that a book in one
volume, well written, and embracing a faithful chronicle of events
which accomplished the laying of the foundation stone of this great
republic, would be invaluable to the present and all future
generations.” The belief was a just one, and the work before us
seems well calculated to suit the purpose for which it was designed.
Its typographical execution is excellent, and its pages are graced by
seventy-eight beautiful illustrations.
Philosophy in Sport Made Science in Earnest. From the
Sixth London Edition. Philadelphia: Lea & Blanchard. 1
vol. 12mo.
This is a little work which greatly pleases us. It is, as the author
terms it, an attempt to illustrate the first principles of natural
philosophy by the aid of the popular toys and sports of youth, and
he has succeeded admirably in his design. The book may be
commended, with great propriety, to the attention of those who
have the training and culture of the minds of youth, as it conveys a
vast fund of highly important and useful information in a very
attractive and interesting form.
Transcriber’s Notes:
Table of Contents has been added for reader convenience. Archaic
spellings and hyphenation have been retained. Obvious typesetting
and punctuation errors have been corrected without note. Other
errors have been corrected as noted below. For illustrations, some
caption text may be missing or incomplete due to condition of the
originals available for preparation of the eBook.
page 117, ladies; but too poor men ==> ladies; but two poor men
page 119, elité, the young, the ==> élite, the young, the
page 134, with the sail lose, ==> with the sail loose,
page 141, to help to soup. ==> to help himself to soup.
page 151, banished my music-stand, ==> banished from my music-
stand,
page 154, executed a ràvir his favorite ==> executed à ravir his
favorite
[End of Graham’s Magazine, Vol. XXXI, No. 3, September 1847]
*** END OF THE PROJECT GUTENBERG EBOOK GRAHAM'S
MAGAZINE, VOL. XXXI, NO. 3, SEPTEMBER 1847 ***
Updated editions will replace the previous one—the old editions
will be renamed.
Creating the works from print editions not protected by U.S.
copyright law means that no one owns a United States
copyright in these works, so the Foundation (and you!) can copy
and distribute it in the United States without permission and
without paying copyright royalties. Special rules, set forth in the
General Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.
START: FULL LICENSE
THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK
To protect the Project Gutenberg™ mission of promoting the
free distribution of electronic works, by using or distributing this
work (or any other work associated in any way with the phrase
“Project Gutenberg”), you agree to comply with all the terms of
the Full Project Gutenberg™ License available with this file or
online at www.gutenberg.org/license.
Section 1. General Terms of Use and
Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand,
agree to and accept all the terms of this license and intellectual
property (trademark/copyright) agreement. If you do not agree
to abide by all the terms of this agreement, you must cease
using and return or destroy all copies of Project Gutenberg™
electronic works in your possession. If you paid a fee for
obtaining a copy of or access to a Project Gutenberg™
electronic work and you do not agree to be bound by the terms
of this agreement, you may obtain a refund from the person or
entity to whom you paid the fee as set forth in paragraph 1.E.8.
1.B. “Project Gutenberg” is a registered trademark. It may only
be used on or associated in any way with an electronic work by
people who agree to be bound by the terms of this agreement.
There are a few things that you can do with most Project
Gutenberg™ electronic works even without complying with the
full terms of this agreement. See paragraph 1.C below. There
are a lot of things you can do with Project Gutenberg™
electronic works if you follow the terms of this agreement and
help preserve free future access to Project Gutenberg™
electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright
law in the United States and you are located in the United
States, we do not claim a right to prevent you from copying,
distributing, performing, displaying or creating derivative works
based on the work as long as all references to Project
Gutenberg are removed. Of course, we hope that you will
support the Project Gutenberg™ mission of promoting free
access to electronic works by freely sharing Project Gutenberg™
works in compliance with the terms of this agreement for
keeping the Project Gutenberg™ name associated with the
work. You can easily comply with the terms of this agreement
by keeping this work in the same format with its attached full
Project Gutenberg™ License when you share it without charge
with others.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.
1.E. Unless you have removed all references to Project
Gutenberg:
1.E.1. The following sentence, with active links to, or other
immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project
Gutenberg™ work (any work on which the phrase “Project
Gutenberg” appears, or with which the phrase “Project
Gutenberg” is associated) is accessed, displayed, performed,
viewed, copied or distributed:
This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and
with almost no restrictions whatsoever. You may copy it,
give it away or re-use it under the terms of the Project
Gutenberg License included with this eBook or online at
www.gutenberg.org. If you are not located in the United
States, you will have to check the laws of the country
where you are located before using this eBook.
1.E.2. If an individual Project Gutenberg™ electronic work is
derived from texts not protected by U.S. copyright law (does not
contain a notice indicating that it is posted with permission of
the copyright holder), the work can be copied and distributed to
anyone in the United States without paying any fees or charges.
If you are redistributing or providing access to a work with the
phrase “Project Gutenberg” associated with or appearing on the
work, you must comply either with the requirements of
paragraphs 1.E.1 through 1.E.7 or obtain permission for the use
of the work and the Project Gutenberg™ trademark as set forth
in paragraphs 1.E.8 or 1.E.9.
1.E.3. If an individual Project Gutenberg™ electronic work is
posted with the permission of the copyright holder, your use and
distribution must comply with both paragraphs 1.E.1 through
1.E.7 and any additional terms imposed by the copyright holder.
Additional terms will be linked to the Project Gutenberg™
License for all works posted with the permission of the copyright
holder found at the beginning of this work.
1.E.4. Do not unlink or detach or remove the full Project
Gutenberg™ License terms from this work, or any files