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

Download ebooks file Functional Light JavaScript Balanced Pragmatic FP in JavaScript 1st Edition Kyle Simpson all chapters

JavaScript

Uploaded by

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

Download ebooks file Functional Light JavaScript Balanced Pragmatic FP in JavaScript 1st Edition Kyle Simpson all chapters

JavaScript

Uploaded by

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

Download the full version of the ebook at

https://ebookfinal.com

Functional Light JavaScript Balanced


Pragmatic FP in JavaScript 1st Edition Kyle
Simpson

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

Explore and download more ebook at https://ebookfinal.com


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

JavaScript Unlocked 1st Edition Sheiko

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

ebookfinal.com

JavaScript bible Danny Goodman

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

ebookfinal.com

JavaScript Creativity 1st edition Edition Hudson

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

ebookfinal.com

You Don t Know JS ES6 Beyond Kyle Simpson

https://ebookfinal.com/download/you-don-t-know-js-es6-beyond-kyle-
simpson/

ebookfinal.com
Learning JavaScript 2nd Edition Shelley Powers

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

ebookfinal.com

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/
ebookfinal.com

Test Driven JavaScript Development 1st Edition Christian


Johansen

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

ebookfinal.com

Pro JavaScript Design Patterns 1st Edition Ross Harmes

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

ebookfinal.com

JavaScript Essentials for Dummies 1st Edition Paul


Mcfedries

https://ebookfinal.com/download/javascript-essentials-for-dummies-1st-
edition-paul-mcfedries/

ebookfinal.com
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
Random documents with unrelated
content Scribd suggests to you:
LES TROIS SEMEURS

Trois jeunes compagnons s’en allaient à travers le monde.


Comme c’était l’hiver, il pleuvait, ventait, neigeait sur tout le pays
environnant ; mais la route où ils passaient se dorait de soleil, et les
touffes d’aubépines fleuries secouaient, à chaque souffle de la brise,
des envolées de papillons et d’abeilles, parce que c’étaient des
enfants de seize ans ; pour que le printemps rie autour des
voyageurs, il suffit qu’ils l’aient en eux ; au contraire, si un vieillard
entre dans un jardin d’avril, par une rose matinée, le jour s’éteint, le
ciel se voile, les églantines blanches sont de petits flocons de neige.
Donc, ils s’en allaient sans savoir où, et c’est la meilleure façon
de suivre son chemin. L’un se nommait Honorat, et l’autre Chrysor ;
le plus jeune avait nom Aloys. Ils étaient beaux, tous trois, avec leurs
cheveux en boucles, que débouclait le vent, avec la fraîche santé de
leurs joues et de leurs bouches. Les voyant marcher sur la route
ensoleillée, vous auriez eu peine à faire quelque différence entre
eux ; pourtant Honorat avait l’air plus hautain, Chrysor l’air plus
sournois, Aloys l’air plus timide. Ce qu’ils semblaient au dehors, ils
l’étaient au dedans. Le corps n’est que la doublure de l’âme, mais
les hommes ont la mauvaise habitude de porter à l’envers leur
naturel habit. Honorat, dans ses chimères, ne pouvait s’empêcher de
penser qu’il était le fils de quelque puissant roi ! Client affamé de
l’auberge Hasard, mangeant les croûtes de pain que jette par la
fenêtre la satiété des gens riches, buvant l’eau des sources dans le
creux de sa main, dormant sous l’auvent des granges, n’importe, il
se voyait enveloppé de somptuosités et de gloires ; ce qu’il rêvait,
c’étaient des courtisans éblouissants de chamarrures, qui
s’agenouillaient dans la salle du trône, entre des colonnades de
jaspe ou de porphyre ; et, par une grande porte ouverte à deux
battants, entraient des ambassadeurs accourus des contrées les
plus lointaines, tandis que, derrière eux, des esclaves africains,
vêtus de satin rouge, portaient des coffres où s’entassaient,
merveilleuses et charmantes, pierreries, perles fines, étoffes de soie
et de brocart, les humbles redevances de l’empereur de Trébizonde
et du roi de Sirinagor ; ou bien il s’imaginait qu’il menait à la victoire
d’innombrables armées, qu’il enfonçait, l’épée au soleil, les masses
en déroute des troupes ennemies, et que ses peuples le portaient en
triomphe sous des arcs décorés de bannières claquantes où
battaient les ailes de la gloire ! Chrysor, lui, songeait des songes
moins épiques. Des monnaies, beaucoup de monnaies, des
monnaies toujours, d’argent et d’or, d’or surtout, et des diamants
sans nombre dont un seul valait tous les trésors du plus riche des
monarques, voilà ce qui étincelait sous ses yeux, ce qui ruisselait
entre ses doigts, à l’heure même où il tendait aux passants sa main
contente de recevoir un sou de cuivre ; si on l’eût placé entre deux
portes, celle du paradis et celle d’un coffre-fort, ce n’est pas la porte
du paradis qu’il eût ouverte. Quant au petit Aloys, — plus joli et plus
frêle que ses compagnons, — il ne s’inquiétait aucunement des
palais, des courtisans, des ambassadeurs, ni des armées ; à une
table chargée d’or, il eût préféré un coin de prairie en fleurs. Avec
son air d’adolescent, d’adolescente même, il baissait volontiers ses
yeux attentifs aux coccinelles qui escaladent les brins d’herbe, ne les
levait que pour admirer à l’horizon la rougeur des juvéniles aurores,
ou celle des couchants pensifs. La seule joie qu’il désirât, — et il
l’avait, — c’était de chanter en marchant la chanson qu’il avait faite
la veille, une chanson aux belles rimes, que les oiseaux
approuvaient, dans les buissons de la route, en reprenant le refrain.
De sorte que si, le soir, dans le clair silence des étoiles, s’éveillait,
grandissait, mourait un de ces bruits qui sont les soupirs de la nature
endormie, « n’est-ce pas l’écho d’une sonnerie de trompette ? »
demandait Honorat ; « n’est-ce pas, disait Chrysor, le son lointain
d’une pièce d’or qui a roulé d’un tiroir ? » mais Aloys murmurait : « Je
pense que c’est le petit gazouillis d’un nid qui se rendort. »
Or une vieille femme, un jour, les vit venir tandis que, dans un
maigre champ, elle creusait de sa bêche de tout petits sillons pour y
semer des graines. Elle était si vieille et si loqueteuse que vous
l’auriez prise pour un très ancien siècle habillé de chiffons ; et son
antiquité se compliquait de laideur. Un œil crevé, tout jaune, l’autre à
demi couvert d’une taie, trois touffes de cheveux gris se
recroquevillant hors d’un foulard de sale cotonnade, la peau rouge,
avec des verrues, et ses lèvres faisant flic ! flac ! faute de dents,
chaque fois qu’elle aspirait l’air, elle était faite à souhait pour le
désespoir des yeux ; celui qui eût passé devant elle, aurait pressé le
pas, dévoré du besoin de voir une belle fille ou une rose. Mais qui
donc assumerait la tâche d’écrire des contes de fées s’il n’avait le
droit de transformer, au cours de ses récits, les plus hideuses
personnes en jeunes dames éclatantes de beauté et de parure ? On
sait bien que, dans nos histoires, plus l’on est repoussante, d’abord,
plus on sera jolie, tout à l’heure. La séculaire sans-dents ne manqua
point de se conformer à la poétique du bon Perrault et de madame
d’Aulnoy. Quand les trois compagnons, — Honorat, Chrysor, Aloys
— l’aperçurent au bord du fossé, elle s’était changée en la plus
adorable fée que l’on puisse voir, et les volants de sa robe étaient si
fleuris de fleurs de pierreries que les papillons voletaient à l’entour,
croyant tous que le mois d’avril, dans ce maigre champ, s’était
épanoui.
— Beaux enfants, arrêtez-vous, dit la fée. Je vous veux du bien
parce que vous êtes jeunes, — ce qui est la plus charmante façon
d’être bon, — et parce que vous prenez toujours garde, en
marchant, de ne pas écraser les insectes qui traversent la venelle.
Venez là, je vous le conseille, et faites vos semailles dans le sillon
que j’ai creusé. Foi de bonne fée, ce vilain champ, plus fécond qu’il
n’en a l’air, vous rendra au centuple tout ce que vous lui aurez
donné.
Vous pensez si les voyageurs furent charmés de voir une aussi
belle personne et d’entendre d’aussi obligeantes paroles ; mais, en
même temps, ils se trouvaient bien embarrassés, étant pauvres au
point qu’ils n’avaient rien du tout à semer dans le féerique sillon.
— Hélas ! madame, dit Honorat (après avoir pris conseil de
Chrysor et d’Aloys), nous ne possédons aucune chose que nous
souhaiterions nous voir rendue au centuple, sinon nos rêves, qui ne
germeraient pas.
— Qu’en savez-vous ? reprit-elle en écartant, d’un remuement de
cheveux, un papillon qui lui frôlait l’oreille (et il avait cette excuse que
c’était un œillet, cette oreille), qu’en savez-vous, enfants étourdis ?
Semez vos songes dans la terre ouverte, nous verrons bien ce qui
poussera.
Alors Honorat, agenouillé, et la bouche vers le sillon, commença
de conter ses chimères ambitieuses : les palais de porphyre et de
jaspe où resplendissent les chamarrures des courtisans, et les
ambassades entrant par la royale porte, et les nègres chargés de
tributs, et les armées et les triomphes ! Il n’eut pas le loisir d’achever.
Des cavaliers au galop se ruèrent dans la plaine, nombreux,
cuirassés d’or, empanachés d’ailes d’aigles, et proclamant qu’ils
cherchaient, pour le conduire dans son royaume, le fils du roi défunt.
Dès qu’ils eurent aperçu Honorat : « C’est lui ! » s’écrièrent-ils, et,
pleins de joie, ils emportèrent leur maître vers les belles demeures
de marbre et les batailles et les trophées !
Ayant vu cela, Chrysor ne se fit point prier pour semer dans le sol
ses désirs de richesse, son amour des vives monnaies sonnantes et
des précieuses pierreries. Il avait à peine prononcé quelques mots
que le creux se remplit d’or, d’argent, de diamants et de perles. Ivre
de joie, il se jeta dessus, les empoigna, s’en remplit les poches, la
bouche aussi, et s’enfuit, plus riche que les plus riches, cherchant
quelque cachette sûre où enfouir ses trésors.
— Eh ! bien, demanda la fée, à quoi pensez-vous, Aloys ? Ne
suivrez-vous pas l’exemple de vos compagnons ?
Il ne répondit point d’abord, ayant à peine pris garde à ce qui se
passait, occupé d’un mariage de myrtils dans un volubilis.
— Eh ! dit-il enfin, je ne désire rien, sinon d’écouter les rossignols
qui se plaignent, le soir, et les cigales qui crient dans le chaud midi.
Tout ce que je pourrais faire, ce serait de chanter vers le sillon
l’épithalame que j’ai fait hier pour l’hymen de deux fauvettes.
— Chante-le ! répliqua la fée ; cette semaille en vaut bien une
autre.
Comme il commençait la seconde strophe, une belle jeune
femme à demi nue — si belle qu’aucun rêve d’amour ne l’eût
souhaitée plus parfaite, — sortit de la terre entr’ouverte, et mettant
ses deux bras, lianes pour l’enlacement et lys pour la blancheur, au
cou de l’enfant ravi : « Oh ! comme tu chantes bien ! je t’aime ! » lui
dit-elle.
C’est ainsi que la bonne fée vint en aide aux trois enfants
vagabonds qui suivaient, sans savoir vers où, la route ensoleillée.
Mais, à peu de temps de là, il se produisit des événements terribles.
Vaincu dans un combat, après des prodiges de courage, par des
ennemis implacables, le roi Honorat fut obligé de quitter sa capitale
et de se réfugier dans un cloître où on lui coupa les cheveux non
sans lui avoir ôté sa couronne ; les larrons, qui sont toujours aux
aguets, finirent par découvrir la cachette où Chrysor-le-Riche avait
enfoui ses trésors, et il en fut réduit, haillonneux, sur les chemins, à
demander l’aumône à ses voleurs, qui ne la lui firent pas. Seul,
Aloys ne cessa point d’être heureux, baisé du soir au matin, et du
matin au soir, par la belle jeune femme dont les bras souples comme
les lianes étaient blancs comme les lys ; et elle lui fut fidèle, toujours,
toujours, parce qu’il avait chanté dans le sillon féerique une chanson
bien rimée !
LA BELLE AU CŒUR DE NEIGE

Il y avait, dans un royaume, une princesse si belle que, de l’avis


de tout le monde, on n’avait jamais rien vu d’aussi parfait sur la terre.
C’était bien inutile qu’elle fût jolie, puisqu’elle ne voulait aimer
personne. Malgré les prières de ses parents, elle refusait avec
mépris tous les partis qu’on lui proposait ; lorsque des neveux ou
des fils d’empereurs venaient à la cour pour demander sa main, elle
ne daignait même pas les regarder, si jeunes et si beaux qu’ils
fussent ; elle détournait la tête avec un air de mépris : « Vraiment, ce
n’était pas la peine de me déranger pour si peu de chose ! » Enfin, à
cause de la froideur qu’elle montrait en toute occasion, cette
princesse avait été surnommée « la Belle au cœur de neige ».
Vainement sa nourrice, une vieille bonne femme, qui avait beaucoup
d’expérience, lui disait, les larmes aux yeux : « Prends garde à ce
que tu fais, ma fille ! Ce n’est pas une chose honnête que de
répondre par de mauvaises paroles aux gens qui nous aiment de
tout leur cœur. Quoi ! parmi tant de beaux jeunes hommes, si bien
parés, qui brûlent de t’obtenir en mariage, il n’en est pas un seul
pour lequel tu éprouves quelque tendre sentiment ? Prends garde, te
dis-je ; les bonnes fées, par qui te fut accordée une beauté
incomparable, s’irriteront, un jour ou l’autre, si tu continues à te
montrer avare de leur présent ; ce qu’elles t’ont donné, elles veulent
que tu le donnes ; plus tu vaux, plus tu dois ; il faut mesurer l’aumône
à la richesse. Que deviendrais-tu, mon enfant, si tes protectrices,
courroucées par ton indifférence, t’abandonnaient à la méchanceté
de certaines fées qui se réjouissent du mal, et rôdent toujours, dans
de mauvaises intentions, autour des jeunes princesses ? » La Belle
au cœur de neige ne tenait aucun compte de ces bons conseils ; elle
haussait l’épaule, se regardait dans un miroir ; et cela lui suffisait.
Quant au roi et à la reine, ils se montraient désolés plus que l’on ne
saurait dire, de l’indifférence où s’obstinait leur fille ; ils en vinrent à
penser qu’un mauvais génie l’avait maléficiée ; ils firent proclamer
par des hérauts, dans tous les pays du monde, qu’ils donneraient la
princesse elle-même à celui qui la délivrerait du Sort dont elle était
victime.

II

Or, vers le même temps, dans une grande forêt, il y avait un


bûcheron, très hideux de sa personne, contrefait, et boiteux à cause
du poids de sa bosse, qui était la terreur de tout le pays ; car, le plus
souvent, il ne se bornait pas à bûcheronner les arbres ; embusqué
dans quelque ravine, il attendait, la hache levée, le voyageur sans
défiance, et lui tranchait le cou, aussi habilement que l’aurait pu faire
le bourreau le plus expérimenté. Cela fait, il fouillait le cadavre, et,
avec l’argent qu’il trouvait dans les poches, il achetait des vivres et
du vin, dont il se gorgeait dans sa hutte en poussant de grands cris
de joie. De sorte que ce méchant homme fut plus heureux que
beaucoup d’honnêtes gens, tant qu’il passa des voyageurs dans sa
forêt. Mais elle eut bientôt si mauvaise renommée que des gens
même très hardis faisaient de longs détours plutôt que de la
traverser ; le bûcheron chôma. Durant quelques jours, il vécut tant
bien que mal du reste de ses anciennes ripailles, rongeant les os,
égouttant dans sa tasse le fond des bouteilles mal vidées. C’était un
maigre régal pour un affamé et pour un ivrogne tel que lui. La rigueur
de l’hiver mit le comble à son infortune. Dans son repaire, où
soufflait le vent, où neigeaient les flocons, il mourait de froid, en
même temps que de faim ; quant à demander secours aux habitants
du proche village, il n’y pouvait pas songer, à cause de la haine qu’il
s’était attirée. Vous pensez : « Pourquoi ne faisait-il point de feu avec
des fagots et des broussailles sèches ? » Eh ! parce que le bois,
comme les feuilles, était si pénétré de gel, qu’il n’y avait pas moyen
de l’allumer. On peut supposer aussi qu’afin de punir ce vilain
homme, une volonté inconnue empêchait le feu de prendre. Quoi
qu’il en soit, le bûcheron passait de fort tristes journées et de plus
tristes nuits, près de sa huche vide, devant son foyer noir ; le voyant
grelottant et maigre, vous n’auriez pas manqué de le plaindre, si
vous aviez ignoré combien il avait mérité sa misère par ses crimes.
Cependant quelqu’un eut pitié de lui. Ce fut une méchante fée,
appelée Mélandrine. Comme elle se plaisait à voir le mal, il était
naturel qu’elle aimât ceux qui le faisaient.
Une nuit donc, qu’il se désolait de plus belle, claquant des dents,
l’onglée aux doigts, et qu’il eût vendu son âme, — qui, à vrai dire, ne
valait pas grand’chose, — pour une flambée de sarment, Mélandrine
se fit voir à lui, sortant de dessous terre ; elle n’était point belle et
blonde avec des guirlandes de fleurs dans les cheveux, elle ne
portait pas une robe de brocart, resplendissante de pierreries ; mais
laide, chauve, bossue aussi, haillonneuse comme une pauvresse,
vous l’auriez prise pour une vieille mendiante des chemins ; car,
étant méchante, on ne peut pas paraître jolie, même quand on est
fée.
— Ne te désespère pas, pauvre homme, dit-elle ; je veux te venir
en aide. Suis-moi.
Un peu étonné de cette apparition, il marcha derrière Mélandrine
jusqu’à une clairière où l’on voyait des amas de neige.
— Maintenant, allume du feu, reprit-elle.
— Eh ! madame, la neige ne brûle pas !
— C’est en quoi tu te trompes. Tiens, prends cette baguette en
bois de cornouiller, que j’apportai pour toi ; il te suffira d’en toucher
l’un de ces grands tas blancs, pour avoir le plus beau feu que l’on vît
jamais.
Il fit comme elle avait dit. Jugez de son étonnement ! A peine la
branche s’en était-elle approchée, que la neige se mit à flamber,
comme si elle eût été, non de la neige, mais de l’ouate ; toute la
clairière fut illuminée de flammes.
A partir de ce moment, le bûcheron, tout en continuant d’avoir
faim, ne connut plus du moins la souffrance d’avoir froid ; dès qu’il
avait un petit frisson, il faisait un tas de neige dans sa hutte ou sur le
chemin, puis il le touchait de la baguette que lui avait laissée
Mélandrine, et se chauffait devant un bon feu.

III

Quelques jours après cette aventure, il y avait une grande


agitation dans la capitale du royaume voisin ; la cour du palais était
pleine de pertuisaniers qui faisaient sonner leurs hallebardes sur les
dalles. Mais c’était surtout dans la salle du trône que l’émotion était
grande : les plus puissants princes de la terre, avec beaucoup
d’autres jeunes hommes, s’y étaient donné rendez-vous pour tenter,
dans une lutte courtoise, d’émouvoir enfin la Belle au cœur de neige.
Le neveu de l’empereur de Trébizonde courba le genou.
— Je commande à plus d’hommes armés qu’il n’y a de feuilles
dans toutes les forêts, et j’ai, dans mes coffres, plus de perles qu’il
n’y a d’étoiles au ciel. Voulez-vous, ô princesse, régner sur mes
peuples et vous parer de mes perles ?
— Qu’a-t-il dit ? demanda la princesse.
A son tour le fils du roi de Mataquin s’agenouilla.
— Quoique jeune encore, j’ai vaincu dans les tournois les plus
illustres preux, et, d’un seul coup d’épée, j’ai tranché les cent têtes
d’une tarasque qui dévorait tous les nouveau-nés et toutes les
vierges de mon royaume. O princesse, voulez-vous partager ma
gloire qui grandira encore ?
— Il a parlé si bas, dit la princesse, que je ne l’ai pas entendu.
Et d’autres princes, après l’héritier de Trébizonde et l’héritier de
Mataquin, vantèrent leur puissance, leur richesse, leur gloire ; il vint
ensuite, s’inclinant avec de tendres paroles, des poètes qui jouaient
de la guitare comme un séraphin de la harpe, des chevaliers qui
avaient défendu l’honneur des dames dans les plus périlleux
combats, de jeunes pages aussi, tremblants, roses de pudeur, dont
la lèvre frémissait dans l’espérance d’un baiser.
Mais la Belle au cœur de neige :
— Que veulent tous ces gens-là ? Qu’on les prie de sortir ; je ne
saurais endurer plus longtemps leur bavardage, et j’ai hâte d’être
seule pour me regarder dans mon miroir.
— Ah ! ma fille, ma fille, dit la nourrice, crains d’irriter les bonnes
fées !
Alors s’avança un rustaud, très hideux de sa personne,
contrefait, boiteux à cause du poids de sa bosse. Les courtisans, qui
étaient au pied du trône, voulurent l’écarter, se moquant de ce
paysan qui se mêlait de prétendre à la main d’une royale personne.
Lui, cependant, continua d’approcher, et, d’une baguette qu’il avait
dans la main, toucha le corsage de l’indifférente enfant. « Ah ! que je
l’aime ! » s’écria-t-elle, sentant tout son être s’allumer et fondre en
tendresse. Vous pensez l’émoi qui s’ensuivit ! Mais un roi n’a que sa
parole ; le père de la princesse dut la laisser aller avec le méchant
bûcheron vers la forêt mal famée ; elle y vécut fort malheureuse, car
son amour ne l’aveuglait pas au point de lui cacher combien en était
indigne celui qui l’avait inspiré ; et ce fut le châtiment de la Belle au
cœur de neige.
LES DEUX MARGUERITES

Lambert et Landry, qui n’étaient point heureux dans leur famille,


étant fils de très pauvres gens, résolurent de s’en aller à travers le
monde, afin de chercher fortune. Ce fut par une matinée de
printemps qu’ils se mirent en chemin. Landry avait quinze ans.
Lambert en avait seize ; ils étaient donc bien jeunes pour
vagabonder de la sorte ; avec beaucoup d’espoir, ils avaient un peu
d’inquiétude. Mais ils furent singulièrement réconfortés par une
aventure qui leur échut dès le commencement du voyage.
Comme ils longeaient la lisière d’un petit bois, une dame vint à
leur rencontre ; elle était toute parée de fleurs ; des boutons d’or et
des pimprenelles riaient dans ses cheveux, les volubilis dont
s’enguirlandait sa robe tombaient jusqu’à ses mignons souliers de
mousse pareille à du velours vert ; ses lèvres ressemblaient à une
églantine, ses yeux à des bleuets. Chaque fois qu’elle bougeait, des
papillons s’envolaient d’elle dans un éparpillement de rosée. Et il
n’était pas surprenant qu’il en fût ainsi, puisque c’était la fée
Primevère, que l’on voit, dès l’avril, passer avec une chanson dans
les bois reverdis et par les prés refleurissants.
— Çà, dit-elle aux deux frères, puisque vous partez pour un long
voyage, je veux faire à chacun de vous un don. Landry, reçois cette
marguerite, et, toi, Lambert, une marguerite aussi. Il vous suffira
d’arracher à ces fleurs un pétale et de le jeter au loin, pour éprouver
à l’instant même une joie sans pareille, qui sera précisément celle
que vous aurez désirée. Allez, suivez votre chemin, et tâchez de
faire bon usage des présents de Primevère.
Ils remercièrent avec beaucoup de politesse cette obligeante fée,
puis ils se remirent en route, aussi satisfaits que possible. Mais,
arrivés en un carrefour, il y eut entre eux un désaccord : Lambert
voulait aller à droite, Landry voulait aller à gauche ; si bien qu’ils
convinrent, pour finir la querelle, que l’un comme l’autre agirait à sa
guise, et ils se séparèrent après s’être embrassés. Peut-être chaque
frère n’était-il point fâché d’être seul afin d’user plus librement du
don que lui avait fait la dame habillée en fleurs.

II

En entrant dans le prochain village, Landry aperçut une jeune fille


accoudée à la fenêtre, et il eut peine à retenir un cri, tant elle lui
paraissait jolie ! Non, il n’avait jamais vu une aussi charmante
personne ; même il n’avait jamais rêvé qu’il pût en exister de pareille.
Presque une enfant encore, avec des cheveux si légers et si blonds
qu’on les distinguait à peine de l’air ensoleillé, elle avait le teint pâle
ici et là un peu rougissant — lys au front, rose aux joues ; ses yeux
s’ouvraient comme une éclosion de pervenches où luirait une perle
de pluie ; il n’était pas de lèvres qui, près des siennes, n’eussent
voulu être abeilles. Landry se garda bien d’hésiter ! Il arracha, jeta
au loin l’un des pétales de sa marguerite : le vent n’avait pas encore
emporté le frêle débris, que l’enfant de la fenêtre était dans la rue,
souriant au voyageur. Ils s’en allèrent vers le bois voisin, les mains
unies, se parlant bas, se disant qu’ils s’aimaient ; rien qu’à
s’entendre, ils éprouvaient de telles délices, qu’ils se croyaient dans
le paradis. Et ils connurent beaucoup de moments pareils à ce
premier moment, beaucoup de jours aussi doux que ce premier jour.
C’eût été le bonheur sans fin, si l’enfant n’avait trépassé un soir
d’automne, pendant que les feuilles flétries, envolées dans la bise,
heurtaient à petits coups les vitres, comme les doigts légers de la
mort qui passe. Landry pleura pendant longtemps ; mais les larmes
n’aveuglent pas si bien que l’on ne puisse regarder au travers : une
fois, il vit une belle passante, vêtue de satin d’or, les yeux hardis, la
lèvre folle ; et, jetant au vent un pétale encore, il partit avec elle. Dès
lors, insoucieux, demandant à chaque heure d’être une joie et à
chaque joie de ne durer qu’une heure, épris sans relâche de ce qui
charme, affole, extasie, il dépensa les jours et les nuits, sans
compter, dans tous les rires et dans tous les baisers. La brise
trouvait à peine le temps de remuer les branches des rosiers et de
soulever les voilettes des femmes, étant toujours occupée à
emporter les pétales de la marguerite.

III

La conduite de Lambert fut tout à fait différente. C’était un jeune


garçon économe, incapable de gaspiller son trésor. Dès qu’il se
trouva seul sur le chemin, il se fit à lui-même la promesse de
ménager le présent de la fée. Car, enfin, si nombreux que fussent
les fleurons de la corolle, un jour viendrait où il n’y en aurait plus, s’il
les arrachait à tout propos. La prudence exigeait de les réserver
pour l’avenir ; en agissant de la sorte il se conformerait certainement
aux intentions de Primevère. Dans la première ville où il passa, il
acheta une petite boîte très solide, fermant à clé ; c’est là dedans
qu’il mit la fleur, résolu à ne jamais la regarder ; il voulait éviter les
tentations. Il n’aurait pas commis la faute, lui, de lever les yeux vers
les jeunes filles des fenêtres, ou de suivre les belles passantes, aux
regards allumés, aux lèvres folles. Raisonnable, méthodique,
s’inquiétant des choses sérieuses, il se fit marchand, gagna de
grosses sommes. Il n’avait que du mépris pour ces étourdis qui
passent le temps en fêtes, sans avoir souci du lendemain ; quand
l’occasion s’en présentait, il ne manquait pas de leur faire de belles
semonces. Aussi était-il fort considéré par les honnêtes gens ; on
s’accordait à le louer, à l’offrir en exemple. Et il continuait de
s’enrichir, travaillant du matin au soir. A vrai dire, il n’était pas
heureux comme il eût voulu l’être ; il songeait, malgré lui, aux joies
qu’il se refusait. Il n’aurait eu qu’à ouvrir la petite boîte, qu’à jeter un
pétale au vent, pour aimer, pour être aimé ! Mais il refrénait tout de
suite ces velléités dangereuses. Il avait le temps ! Il connaîtrait la
joie, plus tard. Il serait bien avancé, quand sa marguerite serait
dépouillée ? « Patience ! ne nous pressons pas ! » Il ne risquait rien à
attendre, puisque la fleur était en sûreté, dans la boîte. La brise, en
rôdant autour de lui, avait beau murmurer : « Jette-moi un pétale,
jette, afin que je l’emporte et que tu souries ! » Il faisait la sourde
oreille ; et le vent s’en allait remuer les branches des rosiers et
taquiner sur la joue des jeunes femmes la dentelle des voilettes.

IV

Or, après beaucoup, beaucoup d’années, il arriva un jour que


Lambert, en visitant ses propriétés, rencontra dans la campagne un
homme assez mal vêtu qui longeait un champ de luzerne.
— Eh ! dit-il, que vois-je ? N’est-ce pas toi, Landry, mon frère ?
— C’est bien moi, répondit l’autre.
— Dans quel fâcheux état je te retrouve ! Tout me porte à croire
que tu as fait un mauvais usage du don de Primevère.
— Hélas ! soupira Landry, j’ai peut-être jeté trop vite tous les
pétales au vent. Pourtant, quoique un peu triste, je ne me repens
pas de mon imprudence. J’ai eu tant de joies, mon frère !
— Cela te fait une belle jambe ! Si tu avais été aussi circonspect
que moi, tu n’en serais pas réduit à de stériles regrets. Car,
apprends-le, je n’ai qu’un geste à faire pour goûter tous les plaisirs
dont tu es sevré.
— Est-il possible ?
— Sans doute, puisque j’ai gardé intact le présent de la fée. Ah !
ah ! je puis me donner du bon temps, si je veux. Voilà ce que c’est
que d’avoir de l’économie.
— Quoi ! intact, vraiment ?
— Regarde plutôt, dit Lambert en ouvrant la boîte qu’il avait tirée
de sa poche.
Mais il devint très pâle, car au lieu de la fraîche marguerite
épanouie, il n’avait sous les yeux qu’un petit tas grisâtre de
poussière, pareil à une pincée de cendre tumulaire.
— Oh ! s’écria-t-il avec rage, maudite soit la méchante fée qui
s’est jouée de moi !
Alors, une jeune dame, toute habillée de fleurs, sortit d’un
buisson de la route :
— Je ne me suis pas jouée de toi, dit-elle, ni de ton frère ; et il est
temps de vous expliquer les choses. Les deux marguerites n’étaient
pas des fleurs en effet, c’étaient vos jeunesses elles-mêmes ; ta
jeunesse, Landry, que tu as jetée à tous les vents du caprice ; ta
jeunesse, Lambert, que tu as laissée se flétrir, sans en faire usage,
dans ton cœur toujours clos ; et tu n’as même pas ce qui reste à ton
frère : le souvenir en fleur de l’avoir effeuillée !
L’ANGE BOITEUX

Un matin qu’il se promenait, en été, sous la neige, — car, dans


ce pays-là, il neige en plein été sous le tiède soleil, et les flocons,
blancheur sans froideur, s’accrochent aux arbrisseaux en jasmins et
en lys, — le fils du roi des Iles-Pâles vit par terre quelque chose de
diamantin et d’argenté, de doucement frémissant comme une harpe
que viennent de quitter les doigts de la musicienne. Plus petite, cette
forme légère, emperlée de larmes d’aurore, aurait pu être l’aile d’une
colombe, qu’arracha et laissa choir la serre d’un autour ; mais,
grande, avec un peu d’azur qui, sans doute d’avoir traversé les
paradis, lui restait au bout des plumes, elle était l’aile d’un ange ; on
ne pouvait s’y méprendre. Le fils de roi, à cette vue, se sentit tout
alangui de mélancolie. Eh ! quoi, un divin messager, peut-être dans
une bataille avec quelque ténébreux esprit, peut-être sous un coup
de vent infernal, avait perdu l’une de ses ailes ? Avait-il commis
l’imprudence de se poser, un soir, — se trompant de chambre, —
près du lit trop parfumé d’une de ces cruelles amoureuses qui n’ont
pas de plus cher plaisir que de meurtrir ce qui vole et de déplumer
les illusions ? Il suffit souvent d’une caresse ou d’un souffle de
femme pour qu’une aile tombe. Quoi qu’il en fût, il devait être fort en
peine maintenant. Quelle humiliation et quelle tristesse pour lui, les
soirs de ces bals où l’on danse avec les plus jolies des onze mille
vierges, d’être raillé par ses frères célestes, pauvre maladroit, qui
valse mal, étant boiteux. Boiteux ? certainement. Puisqu’ils sont, non
des corps, mais des âmes avec des plumes, les anges ne boitent
pas du pied, mais de l’aile. A cause de cette douleur probable, le
prince des Iles-Pâles songeait douloureusement. Il ne pouvait
supporter l’idée, en sa compassion, d’un chérubin ou d’un séraphin
pareil à un ramier blessé ; et, cette chose qu’il avait trouvée, si
blanche, diamantine, argentée, et doucement frémissante, il résolut
de la rendre à qui l’avait perdue. Mais c’était là un dessein plus facile
à concevoir qu’à exécuter. Le moyen de trouver l’ange qui regrettait
son aile ? On n’entre pas comme on veut dans le paradisiaque
séjour. Quant à faire afficher sur les murs des villes, dans tout le
royaume, que celui des élohim à qui manquait un objet précieux le
pourrait retrouver au palais du roi, c’eût été un inutile soin ; les anges
n’ont pas coutume de se promener par les rues comme les badauds
humains. De sorte que le jeune prince était fort perplexe. Il pensa
qu’il ferait bien de consulter une petite fiancée qu’il avait par amour à
l’insu de ses parents. Elle était la fille d’un bûcheron dans la forêt.
L’aile sous le bras, il s’en alla la voir.
Il la rencontra sur la lisière du bois, un peu en avant de la
chaumine où elle habitait.
— Ah ! chère âme, lui dit-il, c’est une triste nouvelle que j’apporte.
— Et laquelle, s’il vous plaît ? demanda-t-elle.
— Un ange a perdu l’une de ses ailes blanches.
Elle rougit, mais elle ne parut pas surprise. On aurait dit qu’elle
était déjà instruite de ce fâcheux événement ; et, quand il eut ajouté :
« Je suis bien décidé à la lui rendre », elle baissa les yeux, plus
rougissante encore.
— Ma chère âme, reprit-il, vous seule pouvez me révéler
comment je dois m’y prendre pour mener à bien mon entreprise.
Vous êtes si jolie et si pure que tous les célestes esprits se donnent
rendez-vous, le jour, dans vos pensées, et, la nuit, dans vos songes.
Il est impossible que, les écoutant, vous n’ayez pas entendu parler
de ce qui est arrivé à l’un d’eux.
— Hélas ! dit-elle, je suis au courant des choses autant qu’il est
possible ; c’est mon ange gardien, justement, qui a perdu l’une de
ses ailes.
— En vérité ? votre ange gardien ? voilà une singulière rencontre.
Apprenez-moi, je vous prie, comment ce malheur lui est advenu.
— Par votre faute, je vous assure ! Vous vous souvenez de cette
promenade que nous fîmes ensemble, l’autre soir, sous les
citronniers où les étoiles tremblaient comme des fruits d’or ?
— Comment l’aurais-je oubliée ? C’est ce soir-là que vous
permîtes à mes lèvres, pour la première fois, de toucher votre joue,
et, depuis ce temps, j’ai la bouche parfumée comme si j’avais mangé
des roses.
— Oui, ce soir-là, vous me donnâtes un baiser, mais, s’il me fut
doux, il fut cruel à l’ange qui me suivait parmi les branches pour
m’avertir et me défendre. L’une de ses ailes s’envola de lui, tandis
que me frôlait votre caresse. C’est la loi des gardiens à qui le ciel
confie les jeunes filles, d’être les premières victimes des péchés
qu’elles font.
— Oh ! la fâcheuse loi ! Je m’imagine que votre ange, estropié,
doit être fort marri.
— Plus que vous ne sauriez le croire ! Penaud, chétif, incapable
de retourner au ciel quand même il l’oserait, il se désole et pleure ; et
j’ai le chagrin, la nuit, de ne pas rêver de vous, car il m’empêche de
dormir, par ses lamentations.
— Il importe donc que nous lui rendions, à tout prix, son aile ! Je
ne saurais me repentir du mal que j’ai fait, mais je voudrais pourtant
qu’il eût un moyen de le réparer.
— Je pense qu’il y en a un, murmura-t-elle.
— Oh ! lequel ? dites vite !
— Il faudrait (elle parlait si bas qu’il l’entendait à peine), il faudrait
remettre les choses en l’état où elles étaient avant la promenade
sous les beaux citronniers. Mon ange a perdu son aile parce que j’ai
reçu votre baiser ; il la reprendrait sans doute, si…
— Si ?… achevez, de grâce ?
— Si je vous le rendais !
En disant ces mots, frémissante et la pudeur aux joues, elle avait
l’air d’une sensitive qui serait une rose ; et comme le prince
s’approchait d’elle, extasié du moyen qu’elle avait imaginé, elle
s’enfuit à travers les branches qui, secouées, éparpillèrent dans le
soleil des gouttelettes de diamant et d’or.
Il courut, la rejoignit, la força de s’asseoir au pied d’un myrte plus
grand que les grands chênes ; dans le mystère profond des bois,
parmi le silence des nids qui se taisaient pour entendre, il lui parlait à
genoux, comme on prie dans les temples.
— Vous que j’aime ! vous que j’adore ! pourquoi me fuir, après
cette parole ! Ne m’avez-vous donné l’espérance de vos lèvres sur
ma joue, que pour me laisser, plus amer, le désespoir de ne les avoir
pas senties s’y poser, doucement ? Oh ! comme les fleurs sont
ravies quand s’y ferme le vol d’un hélïas qui tremble ; c’est de délice
que frémit l’eau rayée de libellules ; on ne peut concevoir la joie des
feuilles qu’une colombe frôle. Mais combien je serais plus heureux
que la fleur où le papillon se clôt, et que l’onde sous le tremblement
des demoiselles, et que le feuillage caressé de plumes, si votre
bouche, — ah ! votre bouche — m’effleurait de son souffle de rose !
Elle ne répondait pas, détournait la tête, ne voulait pas voir le
cher visage d’enfant, épanoui comme le matin où elle aurait eu tant
de plaisir à mettre un long baiser.
Il continua de parler, tristement :
— C’est donc que vous êtes bien cruelle, puisque vous ne voulez
pas ! Je comprendrais que vous me refusiez l’incomparable joie que
j’implore, s’il ne s’agissait que de moi, que vous n’aimez pas assez.
Mais, ô méchante, vous ne songez donc pas à votre ange qui pleure
son aile blanche ? Oubliez-vous qu’en me restituant le baiser reçu,
vous lui rendriez le libre vol parmi les nuées et les étoiles de son
paradis ? Comme il est malheureux, et comme il est à plaindre ! il se
traîne sur le sol, au lieu de planer dans les aurores ; accoutumé à
resplendir de jour, il est tout gris de poussière. Avez-vous jamais vu
une tourterelle à demi morte qui veut regagner sa branche, et ne
peut pas ? C’est à cet oiseau qu’il ressemble. Ah ! le pauvre. Si vous
n’avez point pitié de moi, ayez pitié de lui, et résignez-vous à me
rendre heureux, afin qu’il le soit !
Ce fut certainement à cette considération que céda l’hésitante
jeune fille. Elle jugea que son devoir lui ordonnait de consentir au
bonheur d’un homme pour le bonheur d’un ange ; et, lentement,
avec ce retard des choses qui se savent désirées, ses lèvres
s’approchèrent de la jeune joue en fleur. Elles s’y posèrent ! Un
frémissement secoua les branchages. C’était l’ange qui s’envolait,
avec deux ailes, joyeusement. Seulement les deux ailes, qui furent
blanches, étaient roses, comme les deux baisers.
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