Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (2 votes)
18 views

Functional Light JavaScript Balanced Pragmatic FP in JavaScript 1st Edition Kyle Simpson 2024 scribd download

The document provides information about the book 'Functional-Light JavaScript: Balanced Pragmatic FP in JavaScript' by Kyle Simpson, including download links and suggested related ebooks. It details the book's content, publication information, and acknowledgments. The book aims to present functional programming concepts in JavaScript in an accessible manner.

Uploaded by

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

Functional Light JavaScript Balanced Pragmatic FP in JavaScript 1st Edition Kyle Simpson 2024 scribd download

The document provides information about the book 'Functional-Light JavaScript: Balanced Pragmatic FP in JavaScript' by Kyle Simpson, including download links and suggested related ebooks. It details the book's content, publication information, and acknowledgments. The book aims to present functional programming concepts in JavaScript in an accessible manner.

Uploaded by

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

Visit https://ebookfinal.

com to download the full version and


explore more ebooks

Functional Light JavaScript Balanced Pragmatic


FP in JavaScript 1st Edition Kyle Simpson

_____ Click the link below to download _____


https://ebookfinal.com/download/functional-light-
javascript-balanced-pragmatic-fp-in-javascript-1st-
edition-kyle-simpson/

Explore and download more ebooks at ebookfinal.com


Here are some suggested products you might be interested in.
Click the link to download

JavaScript Unlocked 1st Edition Sheiko

https://ebookfinal.com/download/javascript-unlocked-1st-edition-
sheiko/

JavaScript bible Danny Goodman

https://ebookfinal.com/download/javascript-bible-danny-goodman/

JavaScript Creativity 1st edition Edition Hudson

https://ebookfinal.com/download/javascript-creativity-1st-edition-
edition-hudson/

You Don t Know JS ES6 Beyond Kyle Simpson

https://ebookfinal.com/download/you-don-t-know-js-es6-beyond-kyle-
simpson/
Learning JavaScript 2nd Edition Shelley Powers

https://ebookfinal.com/download/learning-javascript-2nd-edition-
shelley-powers/

Jasmine JavaScript Testing 2nd Edition Test your


JavaScript applications efficiently using Jasmine and
React js Paulo Ragonha
https://ebookfinal.com/download/jasmine-javascript-testing-2nd-
edition-test-your-javascript-applications-efficiently-using-jasmine-
and-react-js-paulo-ragonha/

Test Driven JavaScript Development 1st Edition Christian


Johansen

https://ebookfinal.com/download/test-driven-javascript-
development-1st-edition-christian-johansen/

Pro JavaScript Design Patterns 1st Edition Ross Harmes

https://ebookfinal.com/download/pro-javascript-design-patterns-1st-
edition-ross-harmes/

JavaScript Essentials for Dummies 1st Edition Paul


Mcfedries

https://ebookfinal.com/download/javascript-essentials-for-dummies-1st-
edition-paul-mcfedries/
Functional Light JavaScript Balanced Pragmatic FP in
JavaScript 1st Edition Kyle Simpson Digital Instant
Download
Author(s): Kyle Simpson, Brian MacDonald (editor)
ISBN(s): 9781981672349, 1981672346
Edition: 1
File Details: PDF, 3.00 MB
Year: 2018
Language: english
Functional-Light JavaScript
Balanced, Pragmatic FP in JavaScript

Kyle Simpson
This version was published on 2018-02-09

ISBN 9781617296512

Published by GetiPub (http://getipub.com), a division of Getify Solutions, Inc.


While the publisher and the author have used good faith efforts to ensure that the
information and instructions contained in this work are accurate, the publisher and
the author disclaim all responsibility for errors or omissions, including without
limitation responsibility for damages resulting from the use of or reliance on this
work. Use of the information and instructions contained in this work is at your own
risk. If any code samples or other technology this work contains or describes is
subject to open source licenses or the intellectual property rights of others, it is your
responsibility to ensure that your use thereof complies with such licenses and/or
rights.

DISTRIBUTED BY MANNING

This book was created solely by its Author and is being distributed by Manning
Publications “as is,” with no guarantee of completeness, accuracy, timeliness, or
other fitness for use. Neither Manning nor the Author make any warranty
regarding the results obtained from the use of the contents herein and accept no
liability for any decision or action taken in reliance on the information in this book
nor for any damages resulting from this work or its application.

© 2016 - 2018 Getify Solutions, Inc.


Tweet This Book!
Please help Kyle Simpson by spreading the word about this book on Twitter!
The suggested tweet for this book is:
#FP #JS #FLJSBook Monads, and monoids, and functors, oh my!! I just discovered
”Functional-Light JavaScript”, a pragmatic take on FP in JS without all the crazy
terminology and math.
The suggested hashtag for this book is #FLJSBook.
Find out what other people are saying about the book by clicking on this link to
search for this hashtag on Twitter:
#FLJSBook
I owe gratitude to dozens of folks in the JS and FP communities whose work has helped
me on my multiple-year journey to try to learn what FP is all about. I’m also grateful
to all 738 backers of my crowd-funding campaign (listed at the very end of the book),
who helped make this happen.
But I especially want to give a deep and profound thank you to Brian Lonsdorf for
allowing me to pester him endlessly with FP questions, and for being so patient and
attentive in his assistance. He even tech-edited this book, and wrote the Foreword.
You’re my FP hero, man!
Published by GetiPub (http://getipub.com), a division of Getify Solutions, Inc.
Editors: Brian MacDonald and Brian Lonsdorf
Copyeditor: Jasmine Kwityn
November 2017: First Edition
Revision History for the First Edition
2017-11-27: First Release
2017-12-05, 2017-12-14, 2018-01-29: Reformat For Print, Errata Updates
CONTENTS

Contents

Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iii
Mission . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iv

Chapter 1: Why Functional Programming? . . . . . . . . . . . . . . . . . . 1


At a Glance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Confidence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Readability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
How to Find Balance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

Chapter 2: The Nature Of Functions . . . . . . . . . . . . . . . . . . . . . . 14


What Is a Function? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Function Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Named Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Function Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Functions of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
What’s This? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

Chapter 3: Managing Function Inputs . . . . . . . . . . . . . . . . . . . . . 52


All for One . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

Functional-Light JavaScript
CONTENTS

Adapting Arguments to Parameters . . . . . . . . . . . . . . . . . . . . 57


Some Now, Some Later . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
One at a Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Order Matters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
No Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

Chapter 4: Composing Functions . . . . . . . . . . . . . . . . . . . . . . . 92


Output to Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
General Composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Reordered Composition . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Abstraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Revisiting Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

Chapter 5: Reducing Side Effects . . . . . . . . . . . . . . . . . . . . . . . . 122


Effects on the Side, Please . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Once Is Enough, Thanks . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
Pure Bliss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
There or Not . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
Purifying . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159

Chapter 6: Value Immutability . . . . . . . . . . . . . . . . . . . . . . . . . 160


Primitive Immutability . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
Value to Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Reassignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
Treatment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177

Chapter 7: Closure vs. Object . . . . . . . . . . . . . . . . . . . . . . . . . 178


The Same Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
Look Alike . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Two Roads Diverged in a Wood… . . . . . . . . . . . . . . . . . . . . . . 191
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202

Functional-Light JavaScript
CONTENTS

Chapter 8: Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204


Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
Declarative Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Rearranging Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230

Chapter 9: List Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . 232


Non-FP List Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
Filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
Reduce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
Advanced List Operations . . . . . . . . . . . . . . . . . . . . . . . . . . 252
Method vs. Standalone . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
Looking for Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
Fusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
Beyond Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283

Chapter 10: Functional Async . . . . . . . . . . . . . . . . . . . . . . . . . 284


Time as State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
Eager vs. Lazy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
Reactive FP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296

Chapter 11: Putting It All Together . . . . . . . . . . . . . . . . . . . . . . 298


Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
Stock Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
Stock Ticker UI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315

Appendix A: Transducing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317


Why, First . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
How, Next . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
What, Finally . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337

Functional-Light JavaScript
CONTENTS

Appendix B: The Humble Monad . . . . . . . . . . . . . . . . . . . . . . . 338


Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
Loose Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
Just a Monad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
Maybe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
Humble . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352

Appendix C: FP Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353


Stuff to Investigate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
Ramda (0.23.0) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
Lodash/fp (4.17.4) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
Mori (0.3.2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
Bonus: FPO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
Bonus #2: fasy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363

Functional-Light JavaScript
Foreword i

Foreword
It’s no secret that I am a Functional Programming nut. I evangelize functional ideas
and languages wherever I can, try to read the latest academic papers, study abstract
algebra in my spare time…the works. Even in JavaScript, I refuse to write an impure
statement, which is what led to writing Professor Frisby’s Mostly Adequate Guide to
Functional Programming. Yep, full on, dogmatic zealot.
I was not always this way… I was once obsessed with objects. I loved modeling the
“real world”. I was the inventor of synthetic automatons, tinkering through the night
with masterful precision. The creator of sentient puppets, fingers dancing on the
keyboard to give them life – a real 1337 h4x0r Geppetto. Yet, after 5 solid years of
writing object-oriented code, I was never quite satisfied with the outcome. It just
never worked out well for me. I felt like a lousy programmer. I even lost faith that a
simple, flexible codebase of decent scale was possible.
I figured I’d try something different: Functional Programming. I began to dabble
with functional ideas in my everyday codebase, and much to my coworkers’ dismay,
hadn’t the slightest clue what I was doing. The code I wrote in those days was awful.
Atrocious. Digital sewage. The reason was a lack of clear vision or goal on what I
was even trying to accomplish. My Jiminy-Coding-Cricket, if you like, was not there
to guide me. It took a long time and a lot of garbage programs to figure out how to
FP.
Now, after all that messy exploration, I feel that pure Functional Programming has
delivered on its promise. Readable programs do exist! Reuse does exist! I no longer
invent, but rather discover my model. I’ve become a rogue detective uncovering
a vast conspiracy, cork board pinned full of mathematical evidence. A digital-age
Cousteau logging the characteristics of this bizarre land in the name of science! It’s
not perfect and I still have a lot to learn, but I’ve never been more satisfied in my
work and pleased with the outcome.
Had this book existed when I was starting out, my transition into the world of
Functional Programming would have been much easier and less destructive. This

Functional-Light JavaScript
Foreword ii

book is two-fold (right and left): it will not only teach you how to use various
constructs from FP effectively in your daily code, but more importantly, provide
you with an aim; guiding principles that will keep you on track.
You will learn Functional-Light: A paradigm that Kyle has pioneered to enable
declarative, Functional Programming while providing balance and interop with the
rest of the JavaScript world. You will understand the foundation which pure FP is
built upon without having to subscribe to the paradigm in its entirety. You will gain
the skills to practice and explore FP without having to rewrite existing code for it
to work well together. You can take a step forward in your software career without
backtracking and wandering aimlessly as I did years ago. Coworkers and colleagues
rejoice!
Kyle is a great teacher known for his relentless pursuit of the whole picture, leaving
no nook or cranny unexplored, yet he maintains an empathy for the learner’s plight.
His style has resonated with the industry, leveling us all up as a whole. His work
has a solid place in JavaScript’s history and most people’s bookmarks bar. You are in
good hands.
Functional Programming has many different definitions. A Lisp programmer’s
definition is vastly different from a Haskell perspective. OCaml’s FP bears little
resemblance to the paradigm seen in Erlang. You will even find several competing
definitions in JavaScript. Yet there is a tie that binds – some blurry know-it-when-
I-see-it definition, much like obscenity (indeed, some do find FP obscene!) and this
book certainly captures it. The end result might not be considered idiomatic in certain
circles, but the knowledge acquired here directly applies to any flavor of FP.
This book is a terrific place to begin your FP journey. Take it away, Kyle…
-Brian Lonsdorf (@drboolean)

Functional-Light JavaScript
Preface iii

Preface
A monad is just a monoid in the category of endofunctors.

Did I just lose you? Don’t worry, I’d be lost, too! All those terms that only
mean something to the already-initiated in Functional ProgrammingTM (FP) are just
jumbled nonsense to many of the rest of us.
This book is not going to teach you what those words mean. If that’s what you’re
looking for, keep looking. In fact, there are already plenty of great books that teach
FP the right way, from the top-down. Those words have important meanings and if
you formally study FP in-depth, you’ll absolutely want to get familiar with them.
But this book is going to approach the topic quite differently. I’m going to present
fundamental FP concepts from the ground-up, with fewer special or non-intuitive
terms than most approaches to FP. We’ll try to take a practical approach to each
principle rather than a purely academic angle. There will be terms, no doubt. But
we’ll be careful and deliberate about introducing them and explaining why they’re
important.
Sadly, I am not a card-carrying member of the FP Cool Kids Club. I’ve never been
formally taught anything about FP. And though I have a CS academic background
and I am decent at math, mathematical notation is not how my brain understands
programming. I have never written a line of Scheme, Clojure, or Haskell. I’m not an
old-school Lisp’r.
I have attended countless conference talks about FP, each one with the desperate
clinging hope that finally, this time would be the time I understood what this
whole functional programming mysticism is all about. And each time, I came away
frustrated and reminded that those terms got all mixed up in my head and I had no
idea if or what I learned. Maybe I learned things. But I couldn’t figure out what those
things were for the longest time.
Little by little, across those various exposures, I teased out bits and pieces of
important concepts that seem to just come all too naturally to the formal FPer.

Functional-Light JavaScript
Preface iv

I learned them slowly and I learned them pragmatically and experientially, not
academically with appropriate terminology. Have you ever known a thing for a long
time, and only later found out it had a specific name you never knew!?
Maybe you’re like me; I heard terms such as “map-reduce” around industry segments
like “big data” for years with no real idea what they were. Eventually I learned what
the map(..) function did – all long before I had any idea that list operations were a
cornerstone of the FPer path and what makes them so important. I knew what map
was long before I ever knew it was called map(..).
Eventually I began to gather all these tidbits of understanding into what I now call
“Functional-Light Programming” (FLP).

Mission
But why is it so important for you to learn functional programming, even the light
form?
I’ve come to believe something very deeply in recent years, so much so you could
almost call it a religious belief. I believe that programming is fundamentally about
humans, not about code. I believe that code is first and foremost a means of human
communication, and only as a side effect (hear my self-referential chuckle) does it
instruct the computer.
The way I see it, functional programming is at its heart about using patterns in your
code that are well-known, understandable, and proven to keep away the mistakes
that make code harder to understand. In that view, FP – or, ahem, FLP! – might be
one of the most important collections of tools any developer could acquire.

The curse of the monad is that… once you understand… you lose the
ability to explain it to anyone else.

Douglas Crockford 2012 “Monads and Gonads”


https://www.youtube.com/watch?v=dkZFtimgAcM

Functional-Light JavaScript
Preface v

I hope this book “Maybe” breaks the spirit of that curse, even though we won’t talk
about “monads” until the very end in the appendices.
The formal FPer will often assert that the real value of FP is in using it essentially
100%: it’s an all-or-nothing proposition. The belief is that if you use FP in one part of
your program but not in another, the whole program is polluted by the non-FP stuff
and therefore suffers enough that the FP was probably not worth it.
I’ll say unequivocally: I think that absolutism is bogus. That’s as silly to me as
suggesting that this book is only good if I use perfect grammar and active voice
throughout; if I make any mistakes, it degrades the entire book’s quality. Nonsense.
The better I am at writing in a clear, consistent voice, the better your reading
experience will be. But I’m not a 100% perfect author. Some parts will be better
written than others. The parts where I can still improve are not going to invalidate
the other parts of this book which are useful.
And so it goes with our code. The more you can apply these principles to more parts
of your code, the better your code will be. Use them well 25% of the time, and you’ll
get some good benefit. Use them 80% of the time, and you’ll see even more benefit.
With perhaps a few exceptions, I don’t think you’ll find many absolutes in this text.
We’ll instead talk about aspirations, goals, principles to strive for. We’ll talk about
balance and pragmatism and trade-offs.
Welcome to this journey into the most useful and practical foundations of FP. We
both have plenty to learn!

Functional-Light JavaScript
Chapter 1: Why Functional Programming? 1

Chapter 1: Why Functional


Programming?
Functional programmer: (noun) One who names variables “x”, names
functions “f”, and names code patterns “zygohistomorphic prepromor-
phism”

James Iry @jamesiry 5/13/2015


https://twitter.com/jamesiry/status/598547781515485184

Functional Programming (FP) is not a new concept by any means. It’s been around
almost the entire history of programming. However, and I’m not sure it’s fair to
say, but… it sure hasn’t seemed like as mainstream of a concept in the overall
developer world until perhaps the last few years. I think FP has more been the realm
of academics.
That’s all changing, though. A groundswell of interest is growing around FP, not just
at the languages level but even in libraries and frameworks. You very well might be
reading this text because you’ve finally realized FP is something you can’t ignore
any longer. Or maybe you’re like me and you’ve tried to learn FP many times before
but struggled to wade through all the terms or mathematical notation.
This first chapter’s purpose is to answer questions like “Why should I use FP
style with my code?” and “How does Functional-Light JavaScript compare to what
others say about FP?” After we’ve laid that groundwork, throughout the rest of the
book we’ll uncover, piece by piece, the techniques and patterns for writing JS in
Functional-Light style.

Functional-Light JavaScript
Chapter 1: Why Functional Programming? 2

At a Glance
Let’s briefly illustrate the notion of “Functional-Light JavaScript” with a before-and-
after snapshot of code. Consider:

var numbers = [4,10,0,27,42,17,15,-6,58];


var faves = [];
var magicNumber = 0;

pickFavoriteNumbers();
calculateMagicNumber();
outputMsg(); // The magic number is: 42

// ***************

function calculateMagicNumber() {
for (let fave of faves) {
magicNumber = magicNumber + fave;
}
}

function pickFavoriteNumbers() {
for (let num of numbers) {
if (num >= 10 && num <= 20) {
faves.push( num );
}
}
}

function outputMsg() {
var msg = `The magic number is: ${magicNumber}`;
console.log( msg );
}

Now consider a very different style that accomplishes exactly the same outcome:

Functional-Light JavaScript
Chapter 1: Why Functional Programming? 3

var sumOnlyFavorites = FP.compose( [


FP.filterReducer( FP.gte( 10 ) ),
FP.filterReducer( FP.lte( 20 ) )
] )( sum );

var printMagicNumber = FP.pipe( [


FP.reduce( sumOnlyFavorites, 0 ),
constructMsg,
console.log
] );

var numbers = [4,10,0,27,42,17,15,-6,58];

printMagicNumber( numbers ); // The magic number is: 42

// ***************

function sum(x,y) { return x + y; }


function constructMsg(v) { return `The magic number is: ${v}`; }

Once you understand FP and Functional-Light, this is likely how you’d read and
mentally process that second snippet:

We’re first creating a function called sumOnlyFavorites(..) that’s


a combination of three other functions. We combine two filters, one
checking if a value is greater-than-or-equal to 10 and one for less-than-
or-equal to 20. Then we include the sum(..) reducer in the transducer
composition. The resulting sumOnlyFavorites(..) function is a re-
ducer that checks if a value passes both filters, and if so, adds the value
to an accumulator value.
Then we make another function called printMagicNumber(..) which
first reduces a list of numbers using that sumOnlyFavorites(..)
reducer we just defined, resulting in a sum of only numbers that passed
the favorite checks. Then printMagicNumber(..) pipes that final sum
into constructMsg(..), which creates a string value that finally goes
into console.log(..).

Functional-Light JavaScript
Chapter 1: Why Functional Programming? 4

All those moving pieces speak to an FP developer in ways that likely seem highly
unfamiliar to you right now. This book will help you speak that same kind of
reasoning so that it’s as readable to you as any other code, if not more so!
A few other quick remarks about this code comparison:

• It’s likely that for many readers, the former snippet feels closer to comfort-
able/readable/maintainable than the latter snippet. It’s entirely OK if that’s
the case. You’re in exactly the right spot. I’m confident that if you stick it out
through the whole book, and practice everything we talk about, that second
snippet will eventually become a lot more natural, maybe even preferable!
• You might have done the task significantly or entirely different from either
snippet presented. That’s OK, too. This book won’t be prescriptive in dictating
that you should do something a specific way. The goal is to illustrate the
pros/cons of various patterns and enable you to make those decisions. By the
end of this book, how you would approach the task may fall a little closer to
the second snippet than it does right now.
• It’s also possible that you’re already a seasoned FP developer who’s scanning
through the start of this book to see if it has anything useful for you to read.
That second snippet certainly has some bits that are quite familiar. But I’m
also betting that you thought, “Hmmm, I wouldn’t have done it that way…” a
couple of times. That’s OK, and entirely reasonable.
This is not a traditional, canonical FP book. We’ll at times seem quite heretical
in our approaches. We’re seeking to strike a pragmatic balance between the
clear undeniable benefits of FP, and the need to ship workable, maintainable JS
without having to tackle a daunting mountain of math/notation/terminology.
This is not your FP, it’s “Functional-Light JavaScript”.

Whatever your reasons for reading this book, welcome!

Confidence
I have a very simple premise that sort of underlies everything I do as a teacher of
software development (in JavaScript): code that you cannot trust is code that you do

Functional-Light JavaScript
Chapter 1: Why Functional Programming? 5

not understand. The reverse is true also: code that you don’t understand is code you
can’t trust. Furthermore, if you cannot trust or understand your code, then you can’t
have any confidence whatsoever that the code you write is suitable to the task. You
run the program and basically just cross your fingers.
What do I mean by trust? I mean that you can verify, by reading and reasoning,
not just executing, that you understand what a piece of code will do; you aren’t just
relying on what it should do. More often than is perhaps prudent, we tend to rely
on running test suites to verify our programs’ correctness. I don’t mean to suggest
tests are bad. But I do think we should aspire to be able to understand our code well
enough that we know the test suite will pass before it runs.
The techniques that form the foundation of FP are designed from the mindset of
having far more confidence over our programs just by reading them. Someone who
understands FP, and who’s disciplined enough to diligently use it throughout their
programs, will write code that they and others can read and verify that the program
will do what they want.
Confidence is also increased when we use techniques that avoid or minimize likely
sources of bugs. That’s perhaps one of the biggest selling points of FP: FP programs
often have fewer bugs, and the bugs that do exist are usually in more obvious places,
so they’re easier to find and fix. FP code tends to be more bug-resistant – certainly
not bug-proof, though.
As you journey through this book, you will begin to develop more confidence in the
code you write, because you will use patterns and practices that are already well
proven; and you’ll avoid the most common causes of program bugs!

Communication
Why is Functional Programming important? To answer that, we need to take a bigger
step back and talk about why programming itself is important.
It may surprise you to hear this, but I don’t believe that code is primarily a set
of instructions for the computer. Actually, I think the fact that code instructs the
computer is almost a happy accident.
I believe very deeply that the vastly more important role of code is as a means of
communication with other human beings.

Functional-Light JavaScript
Chapter 1: Why Functional Programming? 6

You probably know by experience that an awful lot of your time spent “coding” is
actually spent reading existing code. Very few of us are so privileged as to spend all
or most of our time simply banging out all new code and never dealing with code
that others (or our past selves) wrote.
It’s widely estimated that developers spend 70% of code maintenance time on reading
to understand it. That is eye-opening. 70%. No wonder the global average for a
programmer’s lines of code written per day is about 10. We spend up to 7 hours
of our day just reading the code to figure out where those 10 lines should go!
We need to focus a lot more on the readability of our code. And by the way,
readability is not just about fewer characters. Readability is actually most impacted
by familiarity.¹
If we are going to spend our time concerned with making code that will be more
readable and understandable, FP is central in that effort. The principles of FP are
well established, deeply studied and vetted, and provably verifiable. Taking the time
to learn and employ these FP principles will ultimately lead to more readily and
recognizably familiar code for you and others. The increase in code familiarity, and
the expediency of that recognition, will improve code readability.
For example, once you learn what map(..) does, you’ll be able to almost instantly
spot and understand it when you see it in any program. But every time you see a
for loop, you’re going to have to read the whole loop to understand it. The syntax
of the for loop may be familiar, but the substance of what it’s doing is not; that has
to be read, every time.
By having more code that’s recognizable at a glance, and thus spending less time
figuring out what the code is doing, our focus is freed up to think about the higher
levels of program logic; this is the important stuff that most needs our attention
anyway.
FP (at least, without all the terminology weighing it down) is one of the most effective
tools for crafting readable code. That is why it’s so important.
¹Buse, Raymond P. L., and Westley R. Weimer. “Learning a Metric for Code Readability.” IEEE Transactions on Software
Engineering, IEEE Press, July 2010, dl.acm.org/citation.cfm?id=1850615.

Functional-Light JavaScript
Chapter 1: Why Functional Programming? 7

Readability
Readability is not a binary characteristic. It’s a largely subjective human factor
describing our relationship to code. And it will naturally vary over time as our skills
and understanding evolve. I have experienced effects similar to the following figure,
and anecdotally many others I’ve talked to have as well.

Readability of Declarative FP

You may just find yourself experiencing similar effects as you work through the book.
But take heart; if you stick this out, the curve comes back up!
Imperative describes the code most of us probably already write naturally; it’s
focused on precisely instructing the computer how to do something. Declarative code
– the kind we’ll be learning to write, which adheres to FP principles – is code that’s
more focused on describing the what outcome.
Let’s revisit the two code snippets presented earlier in this chapter.
The first snippet is imperative, focused almost entirely on how to do the tasks; it’s
littered with if statements, for loops, temporary variables, reassignments, value
mutations, function calls with side effects, and implicit data flow between functions.
You certainly can trace through its logic to see how the numbers flow and change to
the end state, but it’s not at all clear or straightforward.
The second snippet is more declarative; it does away with most of those afore-
mentioned imperative techniques. Notice there’s no explicit conditionals, loops, side
effects, reassignments, or mutations; instead, it employs well-known (to the FP
world, anyway!) and trustable patterns like filtering, reduction, transducing, and

Functional-Light JavaScript
Chapter 1: Why Functional Programming? 8

composition. The focus shifts from low-level how to higher level what outcomes.
Instead of messing with an if statement to test a number, we delegate that to a
well-known FP utility like gte(..) (greater-than-or-equal-to), and then focus on
the more important task of combining that filter with another filter and a summation
function.
Moreover, the flow of data through the second program is explicit:

1. A list of numbers goes into printMagicNumber(..).


2. One at a time those numbers are processed by sumOnlyFavorites(..),
resulting in a single number total of only our favorite kinds of numbers.
3. That total is converted to a message string with constructMsg(..).
4. The message string is printed to the console with console.log(..).

You may still feel this approach is convoluted, and that the imperative snippet was
easier to understand. You’re much more accustomed to it; familiarity has a profound
influence on our judgments of readability. By the end of this book, though, you will
have internalized the benefits of the second snippet’s declarative approach, and that
familiarity will spring its readability to life.
I know asking you to believe that at this point is a leap of faith.
It takes a lot more effort, and sometimes more code, to improve its readability as I’m
suggesting, and to minimize or eliminate many of the mistakes that lead to bugs.
Quite honestly, when I started writing this book, I could never have written (or even
fully understood!) that second snippet. As I’m now further along on my journey of
learning, it’s more natural and comfortable.
If you’re hoping that FP refactoring, like a magic silver bullet, will quickly transform
your code to be more graceful, elegant, clever, resilient, and concise – that it will
come easy in the short term – unfortunately that’s just not a realistic expectation.
FP is a very different way of thinking about how code should be structured, to make
the flow of data much more obvious and to help your reader follow your thinking. It
will take time. This effort is eminently worthwhile, but it can be an arduous journey.
It still often takes me multiple attempts at refactoring a snippet of imperative code
into more declarative FP, before I end up with something that’s clear enough for me

Functional-Light JavaScript
Chapter 1: Why Functional Programming? 9

to understand later. I’ve found converting to FP is a slow iterative process rather than
a quick binary flip from one paradigm to another.
I also apply the “teach it later” test to every piece of code I write. After I’ve written
a piece of code, I leave it alone for a few hours or days, then come back and try to
read it with fresh eyes, and pretend as if I need to teach or explain it to someone else.
Usually, it’s jumbled and confusing the first few passes, so I tweak it and repeat!
I’m not trying to dampen your spirits. I really want you to hack through these weeds.
I am glad I did it. I can finally start to see the curve bending upward toward improved
readability. The effort has been worth it. It will be for you, too.

Perspective
Most other FP texts seem to take a top-down approach, but we’re going to go the
opposite direction: working from the ground up, we’ll uncover the basic foundational
principles that I believe formal FPers would admit are the scaffolding for everything
they do. But for the most part we’ll stay arm’s length away from most of the
intimidating terminology or mathematical notation that can so easily frustrate
learners.
I believe it’s less important what you call something and more important that you
understand what it is and how it works. That’s not to say there’s no importance
to shared terminology – it undoubtedly eases communication among seasoned
professionals. But for the learner, I’ve found it can be distracting.
So this book will try to focus more on the base concepts and less on the fancy fluff.
That’s not to say there won’t be terminology; there definitely will be. But don’t get
too wrapped up in the sophisticated words. Wherever necessary, look beyond them
to the ideas.
I call the less formal practice herein “Functional-Light Programming” because I think
where the formalism of true FP suffers is that it can be quite overwhelming if you’re
not already accustomed to formal thought. I’m not just guessing; this is my own
personal story. Even after teaching FP and writing this book, I can still say that the
formalism of terms and notation in FP is very, very difficult for me to process. I’ve
tried, and tried, and I can’t seem to get through much of it.

Functional-Light JavaScript
Chapter 1: Why Functional Programming? 10

I know many FPers who believe that the formalism itself helps learning. But I think
there’s clearly a cliff where that only becomes true once you reach a certain comfort
with the formalism. If you happen to already have a math background or even some
flavors of CS experience, this may come more naturally to you. But some of us don’t,
and no matter how hard we try, the formalism keeps getting in the way.
So this book introduces the concepts that I believe FP is built on, but comes at it by
giving you a boost from below to climb up the cliff wall, rather than condescendingly
shouting down at you from the top, prodding you to just figure out how to climb as
you go.

How to Find Balance


If you’ve been around programming for very long, chances are you’ve heard the
phrase “YAGNI” before: “You Ain’t Gonna Need It”. This principle primarily comes
from extreme programming, and stresses the high risk and cost of building a feature
before it’s needed.
Sometimes we guess we’ll need a feature in the future, build it now believing it’ll be
easier to do as we build other stuff, then realize we guessed wrong and the feature
wasn’t needed, or needed to be quite different. Other times we guess right, but build
a feature too early, and suck up time from the features that are genuinely needed
now; we incur an opportunity cost in diluting our energy.
YAGNI challenges us to remember: even if it’s counterintuitive in a situation, we
often should postpone building something until it’s presently needed. We tend to
exaggerate our mental estimates of the future refactoring cost of adding it later when
it is needed. Odds are, it won’t be as hard to do later as we might assume.
As it applies to functional programming, I would offer this admonition: there will be
plenty of interesting and compelling patterns discussed in this text, but just because
you find some pattern exciting to apply, it may not necessarily be appropriate to do
so in a given part of your code.
This is where I will differ from many formal FPers: just because you can apply FP to
something doesn’t mean you should apply FP to it. Moreover, there are many ways
to slice a problem, and even though you may have learned a more sophisticated

Functional-Light JavaScript
Chapter 1: Why Functional Programming? 11

approach that is more “future-proof” to maintenance and extensibility, a simpler FP


pattern might be more than sufficient in that spot.
Generally, I’d recommend seeking balance in what you code, and to be conservative
in your application of FP concepts as you get the hang of things. Default to the YAGNI
principle in deciding if a certain pattern or abstraction will help that part of the
code be more readable or if it’s just introducing clever sophistication that isn’t (yet)
warranted.

Reminder, any extensibility point that’s never used isn’t just wasted
effort, it’s likely to also get in your way as well

Jeremy D. Miller @jeremydmiller 2/20/15


https://twitter.com/jeremydmiller/status/568797862441586688

Remember, every single line of code you write has a reader cost associated with it.
That reader may be another team member, or even your future self. Neither of those
readers will be impressed with overly clever, unnecessary sophistication just to show
off your FP prowess.
The best code is the code that is most readable in the future because it strikes exactly
the right balance between what it can/should be (idealism) and what it must be
(pragmatism).

Resources
I have drawn on a great many different resources to be able to compose this text. I
believe you, too, may benefit from them, so I wanted to take a moment to point them
out.

Functional-Light JavaScript
Chapter 1: Why Functional Programming? 12

Books
Some FP/JavaScript books that you should definitely read:

• Professor Frisby’s Mostly Adequate Guide to Functional Programming by


Brian Lonsdorf
• JavaScript Allongé by Reg Braithwaite
• Functional JavaScript by Michael Fogus

Blogs/sites
Some other authors and content you should check out:

• Fun Fun Function Videos by Mattias P Johansson


• Awesome FP JS
• Kris Jenkins
• Eric Elliott
• James A Forbes
• James Longster
• André Staltz
• Functional Programming Jargon
• Functional Programming Exercises

Libraries
The code snippets in this book largely do not rely on libraries. Each operation that
we discover, we’ll derive how to implement it in standalone, plain ol’ JavaScript.
However, as you begin to build more of your real code with FP, you’ll soon want a
library to provide optimized and highly reliable versions of these commonly accepted
utilities.
By the way, you need to check the documentation for the library functions you use to
ensure you know how they work. There will be a lot of similarities in many of them

Functional-Light JavaScript
Chapter 1: Why Functional Programming? 13

to the code we build on in this text, but there will undoubtedly be some differences,
even between popular libraries.
Here are a few popular FP libraries for JavaScript that are a great place to start your
exploration with:

• Ramda
• lodash/fp
• functional.js
• Immutable.js

Appendix C takes a deeper look at these libraries and others.

Summary
You may have a variety of reasons for starting to read this book, and different
expectations of what you’ll get out of it. This chapter has explained why I want
you to read the book and what I want you to get out of the journey. It also helps
you articulate to others (like your fellow developers) why they should come on the
journey with you!
Functional programming is about writing code that is based on proven principles so
we can gain a level of confidence and trust over the code we write and read. We
shouldn’t be content to write code that we anxiously hope works, and then abruptly
breathe a sigh of relief when the test suite passes. We should know what it will do
before we run it, and we should be absolutely confident that we’ve communicated all
these ideas in our code for the benefit of other readers (including our future selves).
This is the heart of Functional-Light JavaScript. The goal is to learn to effectively
communicate with our code but not have to suffocate under mountains of notation
or terminology to get there.
The journey to learning functional programming starts with deeply understanding
the nature of what a function is. That’s what we tackle in the next chapter.

Functional-Light JavaScript
Chapter 2: The Nature Of Functions 14

Chapter 2: The Nature Of


Functions
Functional Programming is not just programming with the function keyword.
Oh, if only it was that easy – I could end the book right here! Nevertheless, functions
really are at the center of FP. And it’s how we use functions that makes our code
functional.
But how sure are you that you know what function really means?
In this chapter, we’re going to lay the groundwork for the rest of the book by
exploring all the foundational aspects of functions. Actually, this is a review of all
the things even a non-FP programmer should know about functions. But certainly if
we want to get the most out of FP concepts, it’s essential we know functions inside
and out.
Brace yourself, because there’s a lot more to the function than you may have realized.

What Is a Function?
The question “What is a function?” superficially seems to have an obvious answer: a
function is a collection of code that can be executed one or more times.
While this definition is reasonable, it’s missing some very important essence that is
the core of a function as it applies to FP. So let’s dig below the surface to understand
functions more completely.

Brief Math Review


I know I’ve promised we’d stay away from math as much as possible, but bear with
me for a moment as we quickly observe some fundamental things about functions
and graphs from algebra before we proceed.

Functional-Light JavaScript
Chapter 2: The Nature Of Functions 15

Do you remember learning anything about f(x) back in school? What about the
equation y = f(x)?
Let’s say an equation is defined like this: f (x) = 2x2 + 3. What does that mean?
What does it mean to graph that equation? Here’s the graph:

f (x) = 2x2 + 3

What you can notice is that for any value of x, say 2, if you plug it into the equation,
you get 11. What is 11, though? It’s the return value of the f(x) function, which
earlier we said represents a y value.
In other words, we can choose to interpret the input and output values as a point
at (2,11) on that curve in the graph. And for every value of x we plug in, we get
another y value that pairs with it as a coordinate for a point. Another is (0,3),
and another is (-1,5). Put all those points together, and you have the graph of that
parabolic curve as shown here.
So what’s any of this got to do with FP?
In math, a function always takes input(s), and always gives an output. A term you’ll
often hear around FP is “morphism”; this is a fancy way of describing a set of values
that maps to another set of values, like the inputs of a function related to the outputs
of that function.
In algebraic math, those inputs and outputs are often interpreted as components of
coordinates to be graphed. In our programs, however, we can define functions with all
sorts of input(s) and output(s), even though they’ll rarely be interpreted as a visually
plotted curve on a graph.

Function vs Procedure
So why all the talk of math and graphs? Because essentially Functional Programming
is about embracing using functions as functions in this mathematical sense.

Functional-Light JavaScript
Chapter 2: The Nature Of Functions 16

You may be more accustomed to thinking of functions as procedures. What’s the


difference? A procedure is an arbitrary collection of functionality. It may have inputs,
it may not. It may have an output (return value), it may not.
A function takes input(s) and definitely always has a return value.
If you plan to do Functional Programming, you should be using functions as much
as possible, and trying to avoid procedures wherever possible. All your functions
should take input(s) and return output(s).
Why? The answer to that will have many levels of meaning that we’ll uncover
throughout this book.

Function Input
So far, we can conclude that functions must expect input. But let’s dig into how
function inputs work.
You sometimes hear people refer to these inputs as “arguments” and sometimes as
“parameters”. So what’s that all about?
Arguments are the values you pass in, and parameters are the named variables inside
the function that receive those passed-in values. Example:

function foo(x,y) {
// ..
}

var a = 3;

foo( a, a * 2 );

a and a * 2 (actually, the result of a * 2, which is 6) are the arguments to the


foo(..) call. x and y are the parameters that receive the argument values (3 and 6,
respectively).

Functional-Light JavaScript
Chapter 2: The Nature Of Functions 17

Note
In JavaScript, there’s no requirement that the number of arguments
matches the number of parameters. If you pass more arguments than
you have declared parameters to receive them, the values pass in just fine
untouched. These values can be accessed in a few different ways, including
the old-school arguments object you may have heard of before. If you
pass fewer arguments than the declared parameters, each unmatched
parameter is treated as an “undefined” variable, meaning it’s present and
available in the scope of the function, but just starts out with the empty
undefined value.

Defaulting Parameters
As of ES6, parameters can declare default values. In the case where the argument
for that parameter is not passed, or it’s passed the value undefined, the default
assignment expression is substituted.
Consider:

function foo(x = 3) {
console.log( x );
}

foo(); // 3
foo( undefined ); // 3
foo( null ); // null
foo( 0 ); // 0

It’s always a good practice to think about any default cases that can aid the usability
of your functions. However, defaulting parameters can lead to more complexity in
terms of reading and understanding the variations of how a function is called. Be
judicious in how much you rely on this feature.

Counting Inputs
The number of arguments a function “expects” – how many arguments you’ll likely
want to pass to it – is determined by the number of parameters that are declared:

Functional-Light JavaScript
Chapter 2: The Nature Of Functions 18

function foo(x,y,z) {
// ..
}

foo(..) expects three arguments, because it has three declared parameters. This
count has a special term: arity. Arity is the number of parameters in a function
declaration. The arity of foo(..) is 3.
Furthermore, a function with arity 1 is also called “unary”, a function with arity 2 is
also called “binary”, and a function with arity 3 or higher is called “n-ary”.
You may wish to inspect a function reference during the runtime of a program to
determine its arity. This can be done with the length property of that function
reference:

function foo(x,y,z) {
// ..
}

foo.length; // 3

One reason for determining the arity during execution would be if a piece of
code received a function reference from multiple sources, and sent different values
depending on the arity of each.
For example, imagine a case where an fn function reference could expect one, two,
or three arguments, but you always want to just pass a variable x in the last position:

// `fn` is set to some function reference


// `x` exists with some value

if (fn.length == 1) {
fn( x );
}
else if (fn.length == 2) {
fn( undefined, x );
}

Functional-Light JavaScript
Chapter 2: The Nature Of Functions 19

else if (fn.length == 3) {
fn( undefined, undefined, x );
}

Tip
The length property of a function is read-only and it’s determined at
the time you declare the function. It should be thought of as essentially
a piece of metadata that describes something about the intended usage of
the function.

One gotcha to be aware of is that certain kinds of parameter list variations can
make the length property of the function report something different than you might
expect:

function foo(x,y = 2) {
// ..
}

function bar(x,...args) {
// ..
}

function baz( {a,b} ) {


// ..
}

foo.length; // 1
bar.length; // 1
baz.length; // 1

What about counting the number of arguments the current function call received?
This was once trivial, but now the situation is slightly more complicated. Each
function has an arguments object (array-like) available that holds a reference to each
of the arguments passed in. You can then inspect the length property of arguments
to figure out how many were actually passed:

Functional-Light JavaScript
Chapter 2: The Nature Of Functions 20

function foo(x,y,z) {
console.log( arguments.length );
}

foo( 3, 4 ); // 2

As of ES5 (and strict mode, specifically), arguments is considered by some to be


sort of deprecated; many avoid using it if possible. In JS, we “never” break backward
compatibility no matter how helpful that may be for future progress, so arguments
will never be removed. But it’s now commonly suggested that you avoid using it
whenever possible.
However, I suggest that arguments.length, and only that, is OK to keep using
for those cases where you need to care about the passed number of arguments. A
future version of JS might possibly add a feature that offers the ability to determine
the number of arguments passed without consulting arguments.length; if that
happens, then we can fully drop usage of arguments!
Be careful: never access arguments positionally, like arguments[1]. Stick to argu-
ments.length only, and only if you must.

Except, how will you access an argument that was passed in a position beyond the
declared parameters? I’ll answer that in a moment; but first, take a step back and ask
yourself, “Why would I want to do that?” Seriously. Think about that closely for a
minute.
It should be pretty rare that this occurs; it shouldn’t be something you regularly
expect or rely on when writing your functions. If you find yourself in such a scenario,
spend an extra 20 minutes trying to design the interaction with that function in a
different way. Name that extra argument even if it’s exceptional.
A function signature that accepts an indeterminate amount of arguments is referred
to as a variadic function. Some people prefer this style of function design, but I think
you’ll find that often the FPer wants to avoid these where possible.
OK, enough harping on that point.
Say you do need to access the arguments in a positional array-like way, possibly
because you’re accessing an argument that doesn’t have a formal parameter at that
position. How do we do it?

Functional-Light JavaScript
Chapter 2: The Nature Of Functions 21

ES6 to the rescue! Let’s declare our function with the ... operator – variously
referred to as “spread”, “rest”, or (my preference) “gather”:

function foo(x,y,z,...args) {
// ..
}

See the ...args in the parameter list? That’s an ES6 declarative form that tells the
engine to collect (ahem, “gather”) all remaining arguments (if any) not assigned to
named parameters, and put them in a real array named args. args will always be
an array, even if it’s empty. But it will not include values that are assigned to the
x, y, and z parameters, only anything else that’s passed in beyond those first three
values:

function foo(x,y,z,...args) {
console.log( x, y, z, args );
}

foo(); // undefined undefined undefined []


foo( 1, 2, 3 ); // 1 2 3 []
foo( 1, 2, 3, 4 ); // 1 2 3 [ 4 ]
foo( 1, 2, 3, 4, 5 ); // 1 2 3 [ 4, 5 ]

So, if you really want to design a function that can account for an arbitrary number
of arguments to be passed in, use ...args (or whatever name you like) on the end.
Now, you’ll have a real, non-deprecated, non-yucky array to access those argument
values from.
Just pay attention to the fact that the value 4 is at position 0 of that args, not position
3. And its length value won’t include those three 1, 2, and 3 values. ...args gathers
everything else, not including the x, y, and z.
You can use the ... operator in the parameter list even if there’s no other formal
parameters declared:

Functional-Light JavaScript
Chapter 2: The Nature Of Functions 22

function foo(...args) {
// ..
}

Now args will be the full array of arguments, whatever they are, and you can use
args.length to know exactly how many arguments have been passed in. And
you’re safe to use args[1] or args[317] if you so choose. Please don’t pass in
318 arguments, though.

Arrays of Arguments
What if you wanted to pass along an array of values as the arguments to a function
call?

function foo(...args) {
console.log( args[3] );
}

var arr = [ 1, 2, 3, 4, 5 ];

foo( ...arr ); // 4

Our new friend ... is used, but now not just in the parameter list; it’s also used
in the argument list at the call-site. It has the opposite behavior in this context. In a
parameter list, we said it gathered arguments together. In an argument list, it spreads
them out. So the contents of arr are actually spread out as individual arguments to
the foo(..) call. Do you see how that’s different from just passing in a reference to
the whole arr array?
By the way, multiple values and ... spreadings can be interleaved, as you see fit:

var arr = [ 2 ];

foo( 1, ...arr, 3, ...[4,5] ); // 4

Functional-Light JavaScript
Chapter 2: The Nature Of Functions 23

Think of ... in this symmetric sense: in a value-list position, it spreads. In an


assignment position – like a parameter list, because arguments get assigned to
parameters – it gathers.
Whichever behavior you invoke, ... makes working with arrays of arguments much
easier. Gone are the days of slice(..), concat(..), and apply(..) to wrangle
our argument value arrays.

Tip
Actually, these methods are not entirely useless. There will be a few places
we rely on them throughout the code in this book. But certainly in most
places, ... will be much more declaratively readable, and preferable as a
result.

Parameter Destructuring
Consider the variadic foo(..) from the previous section:

function foo(...args) {
// ..
}

foo( ...[1,2,3] );

What if we wanted to change that interaction so the caller of our function passes
in an array of values instead of individual argument values? Just drop the two ...
usages:

Functional-Light JavaScript
Chapter 2: The Nature Of Functions 24

function foo(args) {
// ..
}

foo( [1,2,3] );

Simple enough. But what if now we wanted to give a parameter name to each of the
first two values in the passed-in array? We aren’t declaring individual parameters
anymore, so it seems we lost that ability.
Thankfully, ES6 destructuring is the answer. Destructuring is a way to declare a
pattern for the kind of structure (object, array, etc.) that you expect to see, and how
decomposition (assignment) of its individual parts should be processed.
Consider:

function foo( [x,y,...args] = [] ) {


// ..
}

foo( [1,2,3] );

Do you spot the [ .. ] brackets around the parameter list now? This is called array
parameter destructuring.
In this example, destructuring tells the engine that an array is expected in this
assignment position (aka parameter). The pattern says to take the first value of that
array and assign to a local parameter variable called x, the second to y, and whatever
is left is gathered into args.

The Importance of Declarative Style


Considering the destructured foo(..) we just looked at, we could instead have
processed the parameters manually:

Functional-Light JavaScript
Chapter 2: The Nature Of Functions 25

function foo(params) {
var x = params[0];
var y = params[1];
var args = params.slice( 2 );

// ..
}

But here we highlight a principle we only briefly introduced in Chapter 1: declarative


code communicates more effectively than imperative code.
Declarative code (for example, the destructuring in the former foo(..) snippet, or
the ... operator usages) focuses on what the outcome of a piece of code should be.
Imperative code (such as the manual assignments in the latter snippet) focuses more
on how to get the outcome. If you later read such imperative code, you have to
mentally execute all of it to understand the desired outcome. The outcome is coded
there, but it’s not as clear because it’s clouded by the details of how we get there.
The earlier foo(..) is regarded as more readable, because the destructuring hides
the unnecessary details of how to manage the parameter inputs; the reader is free
to focus only on what we will do with those parameters. That’s clearly the most
important concern, so it’s what the reader should be focused on to understand the
code most completely.
Wherever possible, and to whatever degrees our language and our libraries/frame-
works will let us, we should be striving for declarative, self-explanatory code.

Named Arguments
Just as we can destructure array parameters, we can destructure object parameters:

Functional-Light JavaScript
Chapter 2: The Nature Of Functions 26

function foo( {x,y} = {} ) {


console.log( x, y );
}

foo( {
y: 3
} ); // undefined 3

We pass in an object as the single argument, and it’s destructured into two separate
parameter variables x and y, which are assigned the values of those corresponding
property names from the object passed in. It didn’t matter that the x property wasn’t
on the object; it just ended up as a variable with undefined like you’d expect.
But the part of parameter object destructuring I want you to pay attention to is the
object being passed into foo(..).
With a normal call-site like foo(undefined,3), position is used to map from
argument to parameter; we put the 3 in the second position to get it assigned to
a y parameter. But at this new kind of call-site where parameter destructuring is
involved, a simple object-property indicates which parameter (y) the argument value
3 should be assigned to.
We didn’t have to account for x in that call-site because in effect we didn’t care
about x. We just omitted it, instead of having to do something distracting like passing
undefined as a positional placeholder.
Some languages have an explicit feature for this: named arguments. In other words,
at the call-site, labeling an input value to indicate which parameter it maps to.
JavaScript doesn’t have named arguments, but parameter object destructuring is the
next best thing.
Another FP-related benefit of using an object destructuring to pass in potentially
multiple arguments is that a function that only takes one parameter (the object) is
much easier to compose with another function’s single output. Much more on that
in Chapter 4.

Unordered Parameters
Another key benefit is that named arguments, by virtue of being specified as object
properties, are not fundamentally ordered. That means we can specify inputs in

Functional-Light JavaScript
Chapter 2: The Nature Of Functions 27

whatever order we want:

function foo( {x,y} = {} ) {


console.log( x, y );
}

foo( {
y: 3
} ); // undefined 3

We’re skipping the x parameter by simply omitting it. Or we could specify an x


argument if we cared to, even if we listed it after y in the object literal. The call-site
is no longer cluttered by ordered-placeholders like undefined to skip a parameter.
Named arguments are much more flexible, and attractive from a readability perspec-
tive, especially when the function in question can take three, four, or more inputs.

Tip
If this style of function arguments seems useful or interesting to you, check
out coverage of the FPO library in Appendix C.

Function Output
Let’s shift our attention from a function’s inputs to its output.
In JavaScript, functions always return a value. These three functions all have identical
return behavior:

Functional-Light JavaScript
Exploring the Variety of Random
Documents with Different Content
Lang’s (A.) A Monk of Fife: a Story of the Days of Joan of Arc.
With 13 Illusts. 3s. 6d.
Lang’s (A.) Myth, Ritual and Religion. 2 vols. 7s.
Lees (J. A.) and Clutterbuck’s (W. J.) B. C. 1857, A
Ramble in British Columbia. With Maps and 75
Illustrations. 3s. 6d.
Levett-Yeats’ (S.) The Chevalier D’Auriac. 3s. 6d.
Macaulay’s (Lord) Complete Works. With 12 Portraits. 12
vols. 3s. 6d. each.
Macaulay’s (Lord) Essays and Lays of Ancient Rome, etc.
With Portrait and 4 Illustrations to the ‘Lays’. 3s. 6d.
Macleod’s (H. D.) Elements of Banking. 3s. 6d.
Marbot’s (Baron de) Memoirs. Translated. 2 vols. 7s.
Marshman’s (J. C.) Memoirs of Sir Henry Havelock. 3s.
6d.
Merivale’s (Dean) History of the Romans under the
Empire. 8 vols. 3s. 6d. each.
Merriman’s (H. S.) Flotsam: A Tale of the Indian Mutiny. 3s.
6d.
Mill’s (J. S.) Political Economy. 3s. 6d.
Mill’s (J. S.) System of Logic. 3s. 6d.
Milner’s (Geo.) Country Pleasures: the Chronicle of a Year
chiefly in a Garden. 3s. 6d.
Nansen’s (F.) The First Crossing of Greenland. With 142
Illustrations and a Map. 3s. 6d.
Phillipps-Wolley’s (C.) Snap: a Legend of the Lone Mountain.
With 13 Illustrations. 3s. 6d.
Proctor’s (R. A.) The Orbs Around Us. 3s. 6d.
Proctor’s (R. A.) The Expanse of Heaven. 3s. 6d.
Proctor’s (R. A.) Light Science for Leisure Hours. First
Series. 3s. 6d.
Proctor’s (R. A.) The Moon. 3s. 6d.
Proctor’s (R. A.) Other Worlds than Ours. 3s. 6d.
Proctor’s (R. A.) Our Place among Infinities: a Series of
Essays contrasting our Little Abode in Space and Time with the
Infinities around us. 3s. 6d.
Proctor’s (R. A.) Other Suns than Ours. 3s. 6d.
Proctor’s (R. A.) Rough Ways made Smooth. 3s. 6d.
Proctor’s (R. A.) Pleasant Ways in Science. 3s. 6d.
Proctor’s (R. A.) Myths and Marvels of Astronomy. 3s. 6d.
Proctor’s (R. A.) Nature Studies. 3s. 6d.
Proctor’s (R. A.) Leisure Readings. By R. A. Proctor,
Edward Clodd, Andrew Wilson, Thomas Foster, and A. C.
Ranyard. With Illustrations. 3s. 6d.
Rossetti’s (Maria F.) A Shadow of Dante. 3s. 6d.
Smith’s (R. Bosworth) Carthage and the Carthaginians.
With Maps, Plans, etc. 3s. 6d.
Stanley’s (Bishop) Familiar History of Birds. With 160
Illustrations. 3s. 6d.
Stephen’s (L.) The Playground of Europe (The Alps). With
4 Illustrations. 3s. 6d.
Stevenson’s (R. L.) The Strange Case of Dr. Jekyll and Mr.
Hyde; with other Fables, 3s. 6d.
Stevenson (R. L.) and Osbourne’s (Ll.) The Wrong Box.
3s. 6d.
Stevenson (Robert Louis) and Stevenson’s (Fanny van de
Grift) More New Arabian Nights.—The Dynamiter. 3s. 6d.
Weyman’s (Stanley J.) The House of the Wolf: a Romance.
3s. 6d.
Wood’s (Rev. J. G.) Petland Revisited. With 33 Illustrations.
3s. 6d.
Wood’s (Rev. J. G.) Strange Dwellings. With 60 Illustrations.
3s. 6d.
Wood’s (Rev. J. G.) Out of Doors. With 11 Illustrations. 3s. 6d.
Cookery, Domestic Management, &c.
Acton.—Modern Cookery. By Eliza Acton. With 150 Woodcuts.
Fcp. 8vo., 4s. 6d.
Ashby.—Health in the Nursery. By Henry Ashby, M.D.,
F.R.C.P., Physician to the Manchester Children’s Hospital, and
Lecturer on the Diseases of Children at the Owens College. With
25 Illustrations. Crown 8vo., 3s. 6d.
Buckton.—Comfort and Cleanliness: The Servant and Mistress
Question. By Mrs. Catherine M. Buckton, late Member of the
Leeds School Board. With 14 Illustrations. Crown 8vo., 2s.
Bull (Thomas, M.D.).
Hints to Mothers on the Management of their Health
during the Period of Pregnancy. Fcp. 8vo., 1s. 6d.
The Maternal Management of Children in Health and
Disease. Fcp. 8vo., 1s. 6d.
De Salis (Mrs.).
Cakes and Confections à la Mode. Fcp. 8vo., 1s. 6d.
Dogs: A Manual for Amateurs. Fcp. 8vo., 1s. 6d.
Dressed Game and Poultry à la Mode. Fcp. 8vo., 1s. 6d.
Dressed Vegetables à la Mode. Fcp. 8vo., 1s. 6d.
Drinks à la Mode. Fcp. 8vo., 1s. 6d.
Entrées à la Mode. Fcp. 8vo., 1s. 6d.
Floral Decorations. Fcp. 8vo., 1s. 6d.
Gardening à la Mode. Fcp. 8vo. Part I., Vegetables, 1s. 6d. Part
II., Fruits, 1s. 6d.
National Viands à la Mode. Fcp. 8vo., 1s. 6d.
New-laid Eggs. Fcp. 8vo., 1s. 6d.
Oysters à la Mode. Fcp. 8vo., 1s. 6d.
Soups and Dressed Fish à la Mode. Fcp. 8vo., 1s. 6d.
Savouries à la Mode. Fcp. 8vo., 1s. 6d.
Puddings and Pastry à la Mode. Fcp. 8vo., 1s. 6d.
Sweets and Supper Dishes à la Mode. Fcp. 8vo., 1s. 6d.
Tempting Dishes for Small Incomes. Fcp. 8vo., 1s. 6d.
Wrinkles and Notions for Every Household. Crown 8vo., 1s.
6d.
Lear.—Maigre Cookery. By H. L. Sidney Lear. 16mo., 2s.
Poole.—Cookery for the Diabetic. By W. H. and Mrs. Poole.
With Preface by Dr. Pavy. Fcp. 8vo., 2s. 6d.
Walker (Jane H.).
A Book for Every Woman.
Part I., The Management of Children in Health and out of
Health. Crown 8vo., 2s. 6d.
Part II. Woman in Health and out of Health. Crown 8vo., 2s.
6d.
A Handbook for Mothers: being Simple Hints to Women on
the Management of their Health during Pregnancy and
Confinement, together with Plain Directions as to the Care of
Infants. Crown 8vo., 2s. 6d.
Miscellaneous and Critical Works.
Armstrong.—Essays and Sketches. By Edmund J. Armstrong.
Fcp. 8vo., 5s.
Bagehot.—Literary Studies. By Walter Bagehot. With
Portrait. 3 vols. Crown 8vo., 3s. 6d. each.
Baring-Gould.—Curious Myths of the Middle Ages. By Rev.
S. Baring-Gould. Crown 8vo., 3s. 6d.
Baynes.—Shakespeare Studies, and other Essays. By the late
Thomas Spencer Baynes, LL.B., LL.D. With a Biographical
Preface by Professor Lewis Campbell. Crown 8vo., 7s. 6d.
Boyd (A. K. H.) (‘A.K.H.B.’).

And see MISCELLANEOUS THEOLOGICAL WORKS, p. 1032.

Autumn Holidays of a Country Parson. Crown 8vo., 3s. 6d.


Commonplace Philosopher. Cr. 8vo., 3s. 6d.
Critical Essays of a Country Parson. Crown 8vo., 3s. 6d.
East Coast Days and Memories. Crown 8vo., 3s. 6d.
Landscapes, Churches, and Moralities. Crown 8vo., 3s. 6d.
Leisure Hours in Town. Crown 8vo., 3s. 6d.
Lessons of Middle Age. Crown 8vo., 3s. 6d.
Our Little Life. Two Series. Crown 8vo., 3s. 6d. each.
Our Homely Comedy: and Tragedy. Crown 8vo., 3s. 6d.
Recreations of a Country Parson. Three Series. Crown 8vo.,
3s. 6d. each.
Butler (Samuel).
Erewhon. Crown 8vo., 5s.
The Fair Haven. A Work in Defence of the Miraculous Element
in our Lord’s Ministry. Cr. 8vo., 7s. 6d.
Life and Habit. An Essay after a Completer View of Evolution.
Cr. 8vo., 7s. 6d.
Evolution, Old and New. Cr. 8vo., 10s. 6d.
Alps and Sanctuaries of Piedmont and Canton Ticino.
Illustrated. Pott 4to., 10s. 6d.
Luck, or Cunning, as the Main Means of Organic
Modification? Cr. 8vo., 7s. 6d.
Ex Voto. An Account of the Sacro Monte or New Jerusalem at
Varallo-Sesia. Crown 8vo., 10s. 6d.
Selections from Works, with Remarks on Mr. G. J. Romanes’
‘Mental Evolution in Animals,’ and a Psalm of Montreal. Crown
8vo., 7s. 6d.
The Authoress of the Odyssey, where and when She wrote,
who She was, the Use She made of the Iliad, and how the
Poem grew under Her hands. With 14 Illustrations. 8vo., 10s.
6d.
The Iliad of Homer. Rendered into English Prose for the use of
those who cannot read the original. Crown 8vo., 7s. 6d.
Charities Register, The Annual, and Digest: being a
Classified Register of Charities in or available in the
Metropolis, together with a Digest of Information respecting
the Legal, Voluntary, and other Means for the Prevention and
Relief of Distress, and the Improvement of the Condition of the
Poor, and an Elaborate Index. With an Introduction by C. S.
Loch, Secretary to the Council of the Charity Organisation
Society, London. 8vo., 4s.
Comparetti.—The Traditional Poetry of the Finns. By
Domenico Comparetti, Socio dell’ Accademia dei Lincei,
Membre de l’Académie des Inscriptions, &c. Translated by
Isabella M. Anderton. With Introduction by Andrew Lang.
8vo., 16s.
Dreyfus.—Lectures on French Literature. Delivered in
Melbourne by Irma Dreyfus. With Portrait of the Author. Large
crown 8vo., 12s. 6d.
Evans.—The Ancient Stone Implements, Weapons and
Ornaments of Great Britain. By Sir John Evans, K.C.B.,
D.C.L., LL.D., F.R.S., etc. With 537 Illustrations. Medium 8vo.,
28s.
Hamlin.—A Text-Book of the History of Architecture. By A.
D. F. Hamlin, A.M. With 229 Illustrations. Crown 8vo., 7s. 6d.
Haweis.—Music and Morals. By the Rev. H. R. Haweis. With
Portrait of the Author, and numerous Illustrations, Facsimiles,
and Diagrams. Cr. 8vo., 7s. 6d.
Hime.—Stray Military Papers. By Lieut.-Colonel H. W. L. Hime
(late Royal Artillery). 8vo, 7s. 6d.
Contents.—Infantry Fire Formations—On Marking at Rifle
Matches—The Progress of Field Artillery—The Reconnoitering
Duties of Cavalry.
Hullah.—The History of Modern Music; a Course of Lectures.
By John Hullah, LL.D. 8vo., 8s. 6d.
Jefferies (Richard).
Field and Hedgerow: With Portrait. Crown 8vo., 3s. 6d.
The Story of My Heart: my Autobiography. With Portrait and
New Preface by C. J. Longman. Cr. 8vo., 3s. 6d.
Red Deer. With 17 Illustrations by J. Charlton and H. Tunaly.
Crown 8vo., 3s. 6d.
The Toilers of the Field. With Portrait from the Bust in
Salisbury Cathedral. Crown 8vo., 3s. 6d.
Wood Magic: a Fable. With Frontispiece and Vignette by E. V. B.
Crown 8vo., 3s. 6d.
Johnson.—The Patentee’s Manual: a Treatise on the Law and
Practice of Letters Patent. By J. & J. H. Johnson, Patent Agents,
etc. 8vo., 10s. 6d.
Joyce.—The Origin and History of Irish Names of Places. By
P. W. Joyce, LL.D. 2 vols. Crown 8vo., 5s. each.
Kingsley.—A Handbook to French Art. By Rose G. Kingsley.
Lang (Andrew).
The Making of Religion. 8vo., 12s.
Modern Mythology: a Reply to Professor Max Müller. 8vo., 9s.
Letters to Dead Authors. Fcp. 8vo., 2s. 6d. net.
Books and Bookmen. With 2 Coloured Plates and 17
Illustrations. Fcp. 8vo., 2s. 6d. net.
Old Friends. Fcp. 8vo., 2s. 6d. net.
Letters on Literature. Fcp. 8vo., 2s. 6d. net.
Essays in Little. With Portrait of the Author. Crown 8vo., 2s.
6d.
Cock Lane and Common-Sense. Crown 8vo., 3s. 6d.
The Book of Dreams and Ghosts. Crown 8vo., 6s.
Macfarren.—Lectures on Harmony. By Sir George A.
Macfarren. 8vo., 12s.
Madden.—The Diary of Master William Silence: a Study of
Shakespeare and Elizabethan Sport. By the Right Hon. D. H.
Madden, Vice-Chancellor of the University of Dublin. 8vo., 16s.
Marquand and Frothingham.—A Text-Book of the History
of Sculpture. By Allan Marquand, Ph.D., and Arthur L.
Frothingham, Junr., Ph.D., Professors of Archæology and the
History of Art in Princetown University. With 113 Illustrations.
Crown 8vo., 6s.
Max Müller (The Right Hon. F.).
India: What can it Teach Us? Crown 8vo., 3s. 6d.
Chips from a German Workshop.
Vol. I. Recent Essays and Addresses. Crown 8vo., 5s.
Vol. II. Biographical Essays. Crown 8vo., 5s.
Vol. III. Essays on Language and Literature. Crown 8vo., 5s.
Vol. IV. Essays on Mythology and Folk Lore. Crown 8vo., 5s.
Contributions to the Science of Mythology. 2 vols. 8vo., 32s.
Milner.—Country Pleasures: the Chronicle of a Year chiefly in a
Garden. By George Milner. Crown 8vo., 3s. 6d.
Morris (William).
Signs of Change. Seven Lectures delivered on various
Occasions. Post 8vo., 4s. 6d.
Hopes and Fears for Art. Five Lectures delivered in
Birmingham, London, etc., in 1878–1881. Cr 8vo., 4s. 6d.
An Address delivered at the Distribution of Prizes to
Students of the Birmingham Municipal School of Art on
21st February, 1894. 8vo., 2s. 6d. net.
Orchard.—The Astronomy of ‘Milton’s Paradise Lost’. By
Thomas N. Orchard, M.D., Member of the British Astronomical
Association. With 13 Illustrations. 8vo., 6s. net.
Poore (George Vivian), M.D., F.R.C.P.
Essays on Rural Hygiene. With 13 Illustrations. Crown 8vo., 6s.
6d.
The Dwelling House. With 36 Illustrations. Crown 8vo., 3s. 6d.
Richmond.—Boyhood: a Plea for Continuity in Education. By
Ennis Richmond. Crown 8vo., 2s. 6d.
Richter.—Lectures on the National Gallery. By J. P. Richter.
With 20 Plates and 7 Illustrations in the Text. Crown 4to., 9s.
Rossetti.—A Shadow of Dante: being an Essay towards studying
Himself, his World and his Pilgrimage. By Maria Francesca
Rossetti. With Frontispiece by Dante Gabriel Rossetti. Crown
8vo., 3s. 6d.
Solovyoff.—A Modern Priestess of Isis (Madame Blavatsky).
Abridged and Translated on Behalf of the Society for Psychical
Research from the Russian of Vsevolod Sergyeevich
Solovyoff. By Walter Leaf, Litt.D. With Appendices. Crown
8vo., 6s.
Soulsby (Lucy H. M.).
Stray Thoughts on Reading. Small 8vo., 2s. 6d. net.
Stray Thoughts for Girls. 16mo., 1s. 6d. net.
Stray Thoughts for Mothers and Teachers. Fcp. 8vo., 2s. 6d.
net.
Stray Thoughts for Invalids. 16mo., 2s. net.
Southey.—The Correspondence of Robert Southey with
Caroline Bowles. Edited, with an Introduction, by Edward
Dowden, LL.D. 8vo., 14s.
Stevens.—On the Stowage of Ships and their Cargoes. With
Information regarding Freights, Charter-Parties, etc. By Robert
White Stevens, Associate-Member of the Institute of Naval
Architects. 8vo., 21s.
Turner and Sutherland.—The Development of Australian
Literature. By Henry Gyles Turner and Alexander
Sutherland. With Portraits and Illustrations. Crown 8vo., 5s.
Tyszkiewicz.—Memories of an Old Collector. By Count
Michael Tyszkiewicz. Translated from the French by Mrs.
Andrew Lang. With 9 Plates. Crown 8vo., 6s.
Van Dyke.—A Text-Book on the History of Painting. By John
C. Van Dyke, Professor of the History of Art in Rutgers College,
U.S. With 110 Illustrations. Crown 8vo, 6s.
Warwick.—Progress in Women’s Education in the British
Empire: being the Report of Conferences and a Congress held in
connection with the Educational Section, Victorian Era
Exhibition. Edited by the Countess of Warwick. Cr. 8vo. 6s.
White.—An Examination of the Charge of Apostacy against
Wordsworth. By W. Hale White, Editor of the ‘Description of
the Wordsworth and Coleridge MSS. in the Possession of Mr. T.
Norton Longman’. Crown 8vo., 3s. 6d.
Willard.—History of Modern Italian Art. By Ashton Rollins
Willard. With Photogravure Frontispiece and 28 Full-page
Illustrations. 8vo., 18s. net.
Miscellaneous Theological Works.

⁂ For Church of England and Roman Catholic Works see


Messrs. Longmans & Co.’s Special Catalogues.

Balfour.—The Foundations of Belief: being Notes Introductory


to the Study of Theology. By the Right Hon. Arthur J. Balfour,
M.P. 8vo., 12s. 6d.
Bird (Robert).
A Child’s Religion. Cr. 8vo., 2s.
Joseph, the Dreamer. Crown 8vo., 5s.
Jesus, the Carpenter of Nazareth. Crown 8vo., 5s.

To be had also in Two Parts, price 2s. 6d. each.

Part I. Galilee and the Lake of Gennesaret.


Part II. Jerusalem and the Peræa.
Boyd (A. K. H.) (‘A.K.H.B.’).
Occasional and Immemorial Days: Discourses. Crown 8vo., 7s.
6d.
Counsel and Comfort from a City Pulpit. Crown 8vo., 3s. 6d.
Sunday Afternoons in the Parish Church of a Scottish
University City. Crown 8vo., 3s. 6d.
Changed Aspects of Unchanged Truths. Crown 8vo., 3s. 6d.
Graver Thoughts of a Country Parson. Three Series. Crown
8vo., 3s. 6d. each.
Present Day Thoughts. Crown 8vo., 3s. 6d.
Seaside Musings. Cr. 8vo., 3s. 6d.
‘To Meet the Day’ through the Christian Year: being a Text of
Scripture, with an Original Meditation and a Short Selection in
Verse for Every Day. Crown 8vo., 4s. 6d.
Campbell.—Religion in Greek Literature. By the Rev. Lewis
Campbell, M.A., LL.D., Emeritus Professor of Greek, University
of St. Andrews. 8vo., 15s.
Davidson.—Theism, as Grounded in Human Nature, Historically
and Critically Handled. Being the Burnett Lectures for 1892 and
1893, delivered at Aberdeen. By W. L. Davidson, M.A., LL.D.
8vo., 15s.
Gibson.—The Abbé de Lamennais, and the Liberal Catholic
Movement in France. By the Hon. W. Gibson. With Portrait.
8vo., 12s. 6d.
Lang.—The Making of Religion. By Andrew Lang. 8vo., 12s.
MacDonald (George).
Unspoken Sermons. Three Series. Crown 8vo., 3s. 6d. each.
The Miracles of our Lord. Crown 8vo., 3s. 6d.
Martineau (James).
Hours of Thought on Sacred Things: Sermons, 2 vols. Crown
8vo. 3s. 6d. each.
Endeavours after the Christian Life. Discourses. Crown 8vo.,
7s. 6d.
The Seat of Authority in Religion. 8vo., 14s.
Essays, Reviews, and Addresses. 4 Vols. Crown 8vo., 7s. 6d.
each.
Home Prayers, with Two Services for Public Worship. Crown
8vo., 3s. 6d.
Max Müller (F.).
The Origin and Growth of Religion, as illustrated by the
Religions of India. The Hibbert Lectures, delivered at the
Chapter House, Westminster Abbey, in 1878. Crown 8vo., 5s.
Introduction to the Science of Religion: Four Lectures
delivered at the Royal Institution. Crown 8vo., 3s. 6d.
Natural Religion. The Gifford Lectures, delivered before the
University of Glasgow in 1888. Crown 8vo., 5s.
Physical Religion. The Gifford Lectures, delivered before the
University of Glasgow in 1890. Crown 8vo., 5s.
Anthropological Religion. The Gifford Lectures, delivered
before the University of Glasgow in 1891. Cr. 8vo., 5s.
Theosophy, or Psychological Religion. The Gifford Lectures,
delivered before the University of Glasgow in 1892. Crown
8vo., 5s.
Three Lectures on the Vedânta Philosophy, delivered at the
Royal Institution in March, 1894. 8vo., 5s.
Râmakrishna: His Life and Sayings. Crown 8vo., 5s.
Romanes.—Thoughts on Religion. By George J. Romanes,
LL.D., F.R.S. Crown 8vo., 4s. 6d.
Vivekananda.—Yoga Philosophy: Lectures delivered in New
York, Winter of 1895–96, by the SWAMI VIVEKANANDA, on
Raja Yoga; or, Conquering the Internal Nature; also Patanjali’s
Yoga Aphorisms, with Commentaries. Crown 8vo, 3s. 6d.
TRANSCRIBER’S NOTES

Page Changed from Changed to


261 which are but started or which are but stated or
hinted at in the ancient hinted at in the ancient

1. Silently corrected palpable typographical errors;


retained non-standard spellings and dialect.
2. Reindexed footnotes using numbers and collected
together at the end of the Index.
*** END OF THE PROJECT GUTENBERG EBOOK AULD LANG SYNE.
SECOND SERIES ***

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
containing a part of this work or any other work associated with
Project Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute


this electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the
Project Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™
works unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or


providing access to or distributing Project Gutenberg™
electronic works provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project


Gutenberg™ electronic work or group of works on different
terms than are set forth in this agreement, you must obtain
permission in writing from the Project Gutenberg Literary
Archive Foundation, the manager of the Project Gutenberg™
trademark. Contact the Foundation as set forth in Section 3
below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on,
transcribe and proofread works not protected by U.S. copyright
law in creating the Project Gutenberg™ collection. Despite these
efforts, Project Gutenberg™ electronic works, and the medium
on which they may be stored, may contain “Defects,” such as,
but not limited to, incomplete, inaccurate or corrupt data,
transcription errors, a copyright or other intellectual property
infringement, a defective or damaged disk or other medium, a
computer virus, or computer codes that damage or cannot be
read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except


for the “Right of Replacement or Refund” described in
paragraph 1.F.3, the Project Gutenberg Literary Archive
Foundation, the owner of the Project Gutenberg™ trademark,
and any other party distributing a Project Gutenberg™ electronic
work under this agreement, disclaim all liability to you for
damages, costs and expenses, including legal fees. YOU AGREE
THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT
LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT
EXCEPT THOSE PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE
THAT THE FOUNDATION, THE TRADEMARK OWNER, AND ANY
DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE LIABLE
TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL,
PUNITIVE OR INCIDENTAL DAMAGES EVEN IF YOU GIVE
NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of
receiving it, you can receive a refund of the money (if any) you
paid for it by sending a written explanation to the person you
received the work from. If you received the work on a physical
medium, you must return the medium with your written
explanation. The person or entity that provided you with the
defective work may elect to provide a replacement copy in lieu
of a refund. If you received the work electronically, the person
or entity providing it to you may choose to give you a second
opportunity to receive the work electronically in lieu of a refund.
If the second copy is also defective, you may demand a refund
in writing without further opportunities to fix the problem.

1.F.4. Except for the limited right of replacement or refund set


forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’,
WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of
damages. If any disclaimer or limitation set forth in this
agreement violates the law of the state applicable to this
agreement, the agreement shall be interpreted to make the
maximum disclaimer or limitation permitted by the applicable
state law. The invalidity or unenforceability of any provision of
this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the


Foundation, the trademark owner, any agent or employee of the
Foundation, anyone providing copies of Project Gutenberg™
electronic works in accordance with this agreement, and any
volunteers associated with the production, promotion and
distribution of Project Gutenberg™ electronic works, harmless
from all liability, costs and expenses, including legal fees, that
arise directly or indirectly from any of the following which you
do or cause to occur: (a) distribution of this or any Project
Gutenberg™ work, (b) alteration, modification, or additions or
deletions to any Project Gutenberg™ work, and (c) any Defect
you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new
computers. It exists because of the efforts of hundreds of
volunteers and donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project
Gutenberg™’s goals and ensuring that the Project Gutenberg™
collection will remain freely available for generations to come. In
2001, the Project Gutenberg Literary Archive Foundation was
created to provide a secure and permanent future for Project
Gutenberg™ and future generations. To learn more about the
Project Gutenberg Literary Archive Foundation and how your
efforts and donations can help, see Sections 3 and 4 and the
Foundation information page at www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-
profit 501(c)(3) educational corporation organized under the
laws of the state of Mississippi and granted tax exempt status
by the Internal Revenue Service. The Foundation’s EIN or
federal tax identification number is 64-6221541. Contributions
to the Project Gutenberg Literary Archive Foundation are tax
deductible to the full extent permitted by U.S. federal laws and
your state’s laws.

The Foundation’s business office is located at 809 North 1500


West, Salt Lake City, UT 84116, (801) 596-1887. Email contact
links and up to date contact information can be found at the
Foundation’s website and official page at
www.gutenberg.org/contact
Section 4. Information about Donations to
the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission
of increasing the number of public domain and licensed works
that can be freely distributed in machine-readable form
accessible by the widest array of equipment including outdated
equipment. Many small donations ($1 to $5,000) are particularly
important to maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws


regulating charities and charitable donations in all 50 states of
the United States. Compliance requirements are not uniform
and it takes a considerable effort, much paperwork and many
fees to meet and keep up with these requirements. We do not
solicit donations in locations where we have not received written
confirmation of compliance. To SEND DONATIONS or determine
the status of compliance for any particular state visit
www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states


where we have not met the solicitation requirements, we know
of no prohibition against accepting unsolicited donations from
donors in such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot


make any statements concerning tax treatment of donations
received from outside the United States. U.S. laws alone swamp
our small staff.

Please check the Project Gutenberg web pages for current


donation methods and addresses. Donations are accepted in a
number of other ways including checks, online payments and
credit card donations. To donate, please visit:
www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could
be freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose
network of volunteer support.

Project Gutenberg™ eBooks are often created from several


printed editions, all of which are confirmed as not protected by
copyright in the U.S. unless a copyright notice is included. Thus,
we do not necessarily keep eBooks in compliance with any
particular paper edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg
Literary Archive Foundation, how to help produce our new
eBooks, and how to subscribe to our email newsletter to hear
about new eBooks.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookfinal.com

You might also like