Download full ebook of (Ebook) learning javascript 3e by kan instant download pdf
Download full ebook of (Ebook) learning javascript 3e by kan instant download pdf
Download full ebook of (Ebook) learning javascript 3e by kan instant download pdf
Download full ebook of (Ebook) learning javascript 3e by kan instant download pdf
1. Instant Ebook Access, One Click Away – Begin at ebooknice.com
(Ebook) learning javascript 3e by kan
https://ebooknice.com/product/learning-
javascript-3e-50195302
OR CLICK BUTTON
DOWLOAD EBOOK
Get Instant Ebook Downloads – Browse at https://ebooknice.com
2. Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...
Start reading on any device today!
(Ebook) Reactive Programming with JavaScript by kan
https://ebooknice.com/product/reactive-programming-with-javascript-50194990
ebooknice.com
(Ebook) JavaScript Cookbook, 2nd Edition_ Programming the Web by kan
https://ebooknice.com/product/javascript-cookbook-2nd-edition-programming-the-
web-50195402
ebooknice.com
(Ebook) Jasmine JavaScript Testing, 2nd Edition_ Test your JavaScript applications
efficiently using Jasmine and React.js by kan
https://ebooknice.com/product/jasmine-javascript-testing-2nd-edition-test-your-
javascript-applications-efficiently-using-jasmine-and-react-js-50195432
ebooknice.com
(Ebook) Learning ROS for Robotics Programming by kan
https://ebooknice.com/product/learning-ros-for-robotics-programming-50195320
ebooknice.com
3. (Ebook) Learning Highcharts 4_ Design eye-catching and interactive JavaScript charts
for your web page with Highcharts, one of the leading tools in web charting by kan
https://ebooknice.com/product/learning-highcharts-4-design-eye-catching-and-
interactive-javascript-charts-for-your-web-page-with-highcharts-one-of-the-
leading-tools-in-web-charting-50195336
ebooknice.com
(Ebook) Learning Behavior-driven Development with JavaScript_ Create powerful yet
simple-to-code BDD test suites in JavaScript using the most popular tools in the
community by kan
https://ebooknice.com/product/learning-behavior-driven-development-with-
javascript-create-powerful-yet-simple-to-code-bdd-test-suites-in-javascript-
using-the-most-popular-tools-in-the-community-50195346
ebooknice.com
(Ebook) Learning LibGDX Game Development, 2nd Edition by kan
https://ebooknice.com/product/learning-libgdx-game-development-2nd-
edition-50195342
ebooknice.com
(Ebook) JavaScript Regular Expressions_ Leverage the power of regular expressions to
create an engaging user experience by kan
https://ebooknice.com/product/javascript-regular-expressions-leverage-the-power-
of-regular-expressions-to-create-an-engaging-user-experience-50195398
ebooknice.com
(Ebook) JavaScript: Learn JavaScript in 24 Hours or Less - A Beginner’s Guide To
Learning JavaScript Programming Now (JavaScript, JavaScript Programming). by Robert
Dwight. ISBN B01HDPSYKW
https://ebooknice.com/product/javascript-learn-javascript-in-24-hours-or-less-a-
beginners-guide-to-learning-javascript-programming-now-javascript-javascript-
programming-55923064
ebooknice.com
18. For Mark — a true friend, and fellow creator.
www.it-ebooks.info
19. Preface
Even though this is my second book on technologies in the JavaScript ecosystem, I
still find myself somewhat surprised at my role as a JavaScript expert and evangelist.
Like so many programmers, I held a strong prejudice against JavaScript up until
about 2012. To do such an about-face still feels a little disorienting.
My prejudice was for the usual reasons: I considered JavaScript a “toy” language
(without really learning it properly, and therefore not knowing of what I spoke) that
was practiced by dangerous, sloppy, untrained amateur programmers. There is a little
truth in both of these reasons. ES6 was developed quickly, and even its inventor Bren‐
dan Eich admits there are things that he didn’t get right the first time around — and
by the time he realized it, too many people were relying on the problematic behavior
to effectively change it (show me the language that doesn’t suffer from this problem,
however). As for the second reason, JavaScript did make programming suddenly
accessible. Not only did everyone have a browser, but with only a little effort, could
see the JavaScript that enabled the websites that were rapidly proliferating on the
Internet. People learned by trial and error, by reading each other’s code and — in so
many cases — emulating poorly-written code with insufficient understanding.
I’m glad I have learned enough about JavaScript to recognize that — far from being a
toy language — is based on extremely solid foundations, and is powerful, flexible, and
expressive. I’m also glad I have come to embrace the accessibility that JavaScript
brings. I certainly hold no animosity towards amateurs: everyone has to start some‐
where, and programming is a profitable skill, and a career in programming has many
advantages.
To the new programmer, the amateur, I say this: there is no shame in being an ama‐
teur. There is some shame in staying an amateur (if you make programming your
profession, certainly). If you want to practice programming, practice it. Learn every‐
thing you can — from every source you can. Keep an open mind and — perhaps most
importantly — question everything. Question every expert. Question every experi‐
enced programmer. Constantly ask “Why?”
xiii
www.it-ebooks.info
20. 1 Eich confessed in a 2014 interview to enjoying thumbing his nose at Sun Microsystems, who “hated Java‐
Script.”
For the most part, I have tried to keep this book to the “facts” of JavaScript, but it is
impossible to completely avoid opinion. Where I offer opinions, take them for what
they are: my opinion. You are welcome to disagree, and you are encouraged to seek
out the opinions of other experienced developers.
You are learning JavaScript at a very exciting time. The web is leaving its infancy
(technically speaking), and web development isn’t the confusing, complicated wild
west that it was five and ten years ago. Standards like HTML5 and ES6 are making it
easier to learn web development, and easier to develop high quality applications.
Node.js is extending the reach of JavaScript beyond the browser, and now it is a viable
choice for system scripting, desktop application development, back-end web develop‐
ment, and even embedded applications. Certainly I haven’t had this much fun pro‐
gramming since I started in the mid 1980s.
A Brief History of JavaScript
JavaScript was developed by Brendan Eich, a developer at Netscape Communications
Corporation, in 1995. It’s initial development was very rapid, and much of the criti‐
cism leveled at JavaScript has cited the lack of planning foresight during its develop‐
ment. However, Brendan Eich was not a dabbler: he had a solid foundation in
computer science, and incorporated remarkably sophisticated and prescient ideas
into JavaScript. In many ways, it was ahead of its time, and it took fifteen years for
mainstream developers to catch on to the sophistication the language offered.
JavaScript started life with the name Mocha, and was briefly named LiveScript before
being officially renamed to JavaScript in a Netscape Navigator release in 1995. The
word “Java” in “JavaScript” was not coincidental, but it is confusing: aside from a
common syntactic ancestry, JavaScript has more in common with Self (a prototype-
based language developed at Xerox PARC in the mid-80s) and Scheme (a language
developed in the 1970s by Guy Steele and Gerlad Sussman, which was in turn heavily
influenced by Lisp and ALGOL). Eich was familiar with both Self and Scheme, and
used some of their forward-thinking paradigms in developing JavaScript. The name
JavaScript was partially a marketing attempt to tie into the success Java was enjoying
at the time1
.
In November 1996, Netscape announced that they had submitted JavaScript to Ecma,
a private, international non-profit standards organization that carries significant
influence in the technology and communications industries. Ecma International pub‐
lished the first edition of the ECMA-26 specification which was, in essence, Java‐
Script.
xiv | Preface
www.it-ebooks.info
21. The relationship between Ecma’s specifications — which specify a language called
ECMAScript — and JavaScript is mostly academic. Technically, JavaScript is an imple‐
mentation of ECMAScript, but for practical purposes, JavaScript and ECMAScript
can be thought of interchangeably.
The last major ECMAScript version was 5.1 (generically referred to as ES5), pub‐
lished in June 2011. Browsers “in the wild” that are old enough not to support
ECMAScript 5.1 have fallen well below the single digits, and it’s safe to say that
ECMAScript 5.1 is the current lingua franca of the web.
ECMAScript 6 (ES6) — which is the focus of this book — was published by Ecma
International in June 2015. The working name for the specification prior to publica‐
tion was “Harmony”, and you will hear ES6 referred to as “Harmony”, “ES6 Har‐
mony”, “ES6”, and “ECMAScript 2015.” In this book, we will be referring to it simply
as ES6.
ES6
The attentive reader might be wondering why — if ES5 is the current lingua franca of
the web — that this book focuses on ES6.
ES6 represents a significant advancement in the JavaScript language, and some of
ES5’s major shortcomings are addressed in ES6. I think you will find that ES6 is gen‐
erally a much more pleasant and powerful language to work with (and ES5 was quite
enjoyable to start with). Also — thanks to transcompilers — you can write ES6 today,
and transcompile it to “web compatible” ES5.
With ES6 finally published, browser support for ES6 will grow steadily, and at some
point, transcompilation will no longer be necessary to reach a broad audience (I am
not foolish enough to make a prediction — even a rough one — about when that will
happen).
What’s clear is that ES6 represents the future of JavaScript development, and by
investing your time in learning it now, you will be prepared for the future ahead, with
transcompilers preventing us from sacrificing portability now.
However, not every developer will have the luxury of writing ES6 today. It’s possible
that you’re working on a very large existing ES5 code base that would be prohibitively
expensive to convert to ES6. And some developers will simply not wish to go through
the extra effort involved in transcompilation.
With the exception of Chapter 1, this book will be covering ES6, not ES5. Where
appropriate, I will point out where ES6 differs from ES5, but there will not be side-by-
side code examples, or extensive discussion of doing things “the ES5 way” when there
is a better way in ES6. If you fall into that category of programmers who, for whatever
Preface | xv
www.it-ebooks.info
22. reason, need to stick to ES5, this may not be the book for you (though I hope you will
return to it at some point in the future!).
The editorial choice to focus on ES6 was made carefully. The improvements in ES6
are significant enough that it would have been difficult to maintain a clear pedagogi‐
cal framework. In short, a book that attempts to cover ES5 and ES6 would do both
topics a disservice.
Who this Book is For
This book is primarily for readers who already have some experience with program‐
ming (even an introductory programming class, or an online course). If you’re new to
programming, this book will be helpful, but you might want to supplement it with an
introductory text or class.
Those who already have some JavaScript experience (especially if it’s only in ES5) will
find a practical and thorough coverage of important language concepts.
Programmers who are coming from another language should feel right at home with
the content in this book.
This book does attempt to comprehensively cover the language features, related tools,
techniques, and paradigms that drive modern JavaScript development. Because of
this, the material in this book necessarily spans a range from the simple and straight‐
forward (variables, control flow, functions) to complicated, esoteric topics (asynchro‐
nous programming, regular expressions). Depending on your level of experience, you
may find some chapters more challenging than others: the beginning programmer
will no doubt need to re-visit some of the material more than once.
What this Book is Not
This book is not a comprehensive reference to JavaScript or its related libraries. The
Mozilla Developer Network (MDN) maintains an excellent, thorough, up-to-date,
and free online JavaScript reference, which we will be referring to liberally through‐
out this book. If you prefer a physical book, David Flanagan’s JavaScript: The Defini‐
tive Guide is quite comprehensive (though it does not cover ES6 at the time of this
writing).
Acknowledgments
The opportunity to write books for O’Reilly is a tremendous honor, and I owe a debt
of gratitude to Simon St. Laurent for seeing the potential in me, and bringing me on
board. Meg Foley, my editor, has been supportive, encouraging, and ever-helpful
(there’s a certain green T-shirt in the mail for you, Meg!).
xvi | Preface
www.it-ebooks.info
23. To my technical reviewers: Matt Inman, Shelley Powers, Nick Pinkham, and Cody
Lindley: thanks for your astute feedback, great ideas, and helping make this book
great. To say I couldn’t have done it without you is an understatement. While every‐
one’s feedback was incredibly valuable, I want to give special recognition to Matt: his
experience as an educator provided valuable feedback on all matters of pedagogy, and
the liberal use of Stephen Colbert images in his feedback helped me maintain my san‐
ity!
Shelly Powers — author of previous editions of this book — deserves special thanks.
Not just for passing this title on to me, but for her experienced feedback, and for
making this a better book (and some spirited discussions!).
I would like to thank all the readers of of my previous book (Web Development with
Node and Express). If you didn’t buy that book — and review it so positively! — I
would probably not have had the opportunity to write this book. Special thanks to the
readers who took the time to send in feedback and corrections: I have learned a lot
from your responses!
To everyone at a Pop Art, where I am honored to work: you are my rock. Your sup‐
port humbles me, your enthusiasm motivates me, and your professionalism and dedi‐
cation are what get me out of bed in the morning. Tom Paul in particular deserves my
gratitude: his unwavering principles, innovative business ideas, and exceptional lead‐
ership inspire me not only to do my best today, but to do even better tomorrow.
Thanks to Steve Rosenbaum for founding Pop Art, weathering stormy seas, and suc‐
cessfully passing the torch on to Tom. As I have taken time to finish this book, Col‐
wyn Fritze-Moor and Eric Buchmann worked extra hard to cover duties that I
normally would have handled: thank you both. Thanks to Dylan Hallstrom for being
the very model of reliability. Thanks to Liz Tom and Sam Wilskey for joining Team
Pop Art! Thanks to Carole Hardy, Nikki Brovold, Jennifer Erts, Randy Keener, Patrick
Wu, Lisa Melogue for all of your support. Lastly, thanks always to my predecessors,
from whom I learned so much: Tony Alferez, Paul Inman, and Del Olds.
My enthusiasm for this book — and the subject of programming languages in partic‐
ular — was sparked by Dr. Dan Resler, Associate Professor at Virginia Common‐
wealth University. I registered for his class on compiler theory with a singular lack of
interest, and left that class with a passion for formal language theory. Thank you for
passing your enthusiasm — and some small part of your depth of understanding —
on to me.
Thanks to all of my friends in the PSU part-time MBA cohort — it’s been such a
pleasure getting to know you all! Special thanks to Cathy, Amanda, Miska, Sahar, Paul
S., Cathy, John R., Laurie, Joel, Tyler P. and Tyler S. and Jess: you’ve all enriched my
life so much!
Preface | xvii
www.it-ebooks.info
24. If my co-workers at Pop Art motivate me to greatness, and inspire my days, my
friends motivate me to deepness, and light up my nights. Mark Booth: no friend
knows me better, and there is no one I would sooner trust my deepest secrets to. Your
creativity and talent put me to shame: don’t let me show you up with this stupid book.
Katy Roberts is as reliable as the incoming tide, and as beautiful. Katy, thank you for
your deep and abiding kindness and friendship. Sarah Lewis: I love your face. Byron
and Amber Clayton are true and loyal friends who always bring a smile to my face.
Lorraine, it’s been years, but you still bring out the best in me. To Kate Nahas: I’m so
glad we have reconnected after so many years; I look forward to sharing a toast to
Duke’s memory. To Desember: thank you for your trust, warmth and companionship.
Lastly, thanks to my new friends Chris Onstad and Jessica Rowe: you two have
brought me so much joy and laugher into my life in the last two years, I don’t know
what I would have done without you.
To my mother, Ann: thank you for your unwavering support, love, and patience. My
father, Tom, remains my prototype for curiosity, innovation, and dedication, and
without him I would be a poor engineer (or perhaps not an engineer at all). My sister
Meris will always be a fixed point in my life, representing loyalty and conviction.
xviii | Preface
www.it-ebooks.info
25. CHAPTER 1
Your First Application
Often, the best way to learn is to do: so we’re going to start off by creating a simple
application. The point of this chapter is not to explain everything that’s going on:
there’s a lot that’s going to be unfamiliar and confusing, and my advice to you is to
relax and not get caught up in trying to understand everything right now. The point
of this chapter is to get you excited. Just enjoy the ride; by the time you finish this
book, everything in this chapter will make perfect sense to you.
If you don’t have much programming experience, one of the things
that is going to cause you a lot of frustration at first is how literal
computers are. Our human minds can deal with confusing input
very easily, but computers are terrible at this. If I make a grammati‐
cal error, it may change your opinion about my writing ability, but
you will probably still understand me. JavaScript — like all pro‐
gramming languages — have no such facility to deal with confusing
input. Capitalization, spelling, and the order of words and punctu‐
ation is crucial. If you’re experiencing problems, make sure you’ve
copied everything correctly: you haven’t substituted semicolons for
colons, commas for periods, mixing single quotation and double
quotation marks, and all of your code is capitalized correctly. Once
you’ve had some experience, you’ll learn where you can “do things
your way,” and where you have to be perfectly literal, but for now,
you will experience less frustration by entering the examples
exactly as they’re written.
Historically, programming books have started out with an example called “hello
world,” that simply prints the phrase “hello world” to your terminal. It may interest
you to know that this tradition was started in 1972 by Brian Kernighan, a computer
scientist working at Bell Labs. It was first seen in print in 1978 in The C Programming
19
www.it-ebooks.info
26. 1 I hope you have more compassion for your creations than Dr. Frankenstein — and fare better.
Language, by Brian Kernighan and Dennis Ritchie. To this day, The C Programming
Language is widely considered to be one of the best and most influential program‐
ming language books ever written, and I have taken much inspiration from that work
in writing this book.
While “hello world” may seem dated to an increasingly sophisticated generation of
programming students, the implicit meaning behind that simple phrase is as potent
today as it was in 1978: they are the first words uttered by something that you have
breathed life into. It is proof that you are Prometheus, stealing fire from the gods; a
rabbi scratching the true name of God into a clay golem; Doctor Frankenstein breath‐
ing life into his creation1
. It is this sense of creation, of genesis, that first drew me to
programming. Perhaps one day, some programmer — perhaps you — will give life to
the first artificially sentient being. And perhaps its first words will be “hello world.”
In this chapter, we will balance the tradition that Brian Kernighan started 42 years
ago with the sophistication available to programmers today. We will see “hello world”
on our screen, but it will be a far cry from blocky words etched in glowing phosphor
you would have enjoyed in 1972.
Where To Start
In this book, we will be covering the use of JavaScript in all its current incarnations
(server-side, scripting, desktop, browser-based, and more), but for historical and
practical reasons, we’re going to start with a browser-based program.
One of the reasons we’re starting with a browser-based example is that it gives us easy
access to graphics libraries. Humans are inherently visual creatures, and being able to
relate programming concepts to visual elements is a powerful learning tool. We will
be spending a lot of time in this book staring at lines of text, but let’s start out with
something a little more visually interesting. I’ve also chosen this introductory exam‐
ple because it organically introduces some very important concepts, such as event-
driven programming, which will give you a leg up on later chapters.
The Tools
Just as a carpenter would have trouble building a desk without a saw, we can’t write
software without some tools. Fortunately, the tools we need in this chapter are mini‐
mal: a browser, and a text editor.
I am happy to report that, as I write this, there is not one browser on the market that
is not suited to the task at hand. Even Internet Explorer — which has long been a
thorn in the side of programmers — has cleaned up its act, and is now on par with
20 | Chapter 1: Your First Application
www.it-ebooks.info
27. Chrome, Firefox, Safari, or Opera. That said, my browser of choice is Firefox, and in
this text, I will be describing Firefox features that will help you in your programming
journey. Other browsers also have these features, but I will be describing them as they
are implemented in Firefox, so the path of least resistance while you go through this
book will be to use Firefox.
You will need a text editor to actually write your code. The choice of text editors can
be a very contentious — almost religious — debate. Broadly speaking, text editors can
be categorized as text-mode editors or windowed editors. The two most popular text-
mode editors are vi/vim and Emacs. One big advantage to text-mode editors is that,
in addition to using them on your computer, you can use them over SSH — meaning
you can remotely connect to a computer, and edit your files in a familiar editor. Win‐
dowed editors can feel more modern, and add some helpful (and more familiar) user
interface elements. At the end of the day, however, you are editing text only, so a win‐
dowed editor doesn’t offer an inherent advantage over a text-mode editor. Popular
windowed editors are Atom, Sublime Text, Coda, Visual Studio, Notepad++, TextPad,
and Xcode. If you are already familiar with one of these editors, there is probably no
reason to switch. If you are using Notepad on Windows, however, I highly recom‐
mend you upgrade to a more sophisticated editor (Notepad++ is an easy and free
choice for Windows users).
Describing all the features of your editor is beyond the scope of this book, but there
are a few features that you are going to want to learn how to use:
• Syntax highlighting: syntax highlighting uses color to distinguish syntactic ele‐
ments in your program. For example, literals might be one color and variables
another (you will learn what these terms mean soon!). It can make it easier to
spot problems in your code. Most modern text editors will have syntax highlight‐
ing enabled by default; if your code isn’t multi-colored, consult your editor docu‐
mentation to learn how to enable it.
• Bracket matching: most programming languages make heavy use of parentheses,
curly brackets, and square brackets (collectively referred to as “brackets”). Some‐
times, the contents of these brackets span many lines, sometimes even more than
one screen, and you’ll have brackets within brackets, often of different types. It’s
critical that brackets match up, or “balance”; if they don’t, your program won’t
work correctly. Bracket matching provides visual cues about where brackets
begin and end, and can help you spot problems with mismatched brackets.
Bracket matching is handled differently in different editors, ranging from a very
subtle cue to a very obvious one. Unmatched brackets are a common source of
frustration for beginners, so I strongly recommend that you learn how to use
your editor’s bracket-matching feature.
• Code folding: somewhat related to bracket matching is code folding. Code fold‐
ing refers to the ability to temporarily hide code that’s not relevant to what you’re
Your First Application | 21
www.it-ebooks.info
28. 2 Microsoft’s terminology.
doing at the moment, allowing you to focus. The term comes from the idea of
folding a piece of paper over on itself to hide unimportant details. Like bracket
matching, different editors have different methods of code folding.
• Autocompletion: autocompletion (also called “word completion”, or “Intelli‐
Sense”2
) is a convenience feature that attempts to guess what you are typing
before you finish typing it. It has two purposes: the first is to save typing time.
Instead of typing, for example, encodeURIComponent, you can simply type “enc”,
and select encodeURIComponent from a list. The second is called discoverability.
For example, if you type “enc”, because you want to use encodeURIComponent,
you’ll find (or “discover”) that there’s also a function called encodeURI. Depend‐
ing on the editor, you may even see some documentation to distinguish the two
choices. Autocompletion is more difficult to implement in JavaScript than it is in
many other languages because it’s a loosely typed language, and because of its
scoping rules (things you will be learning about later). If autocompletion is an
important feature to you, you may have to shop around to find an editor that
meets your needs: this is an area in which some editors definitely stand out from
the pack. Other editors (vim, for example) offer very powerful autocompletion,
but not without some extra configuration.
A Comment on Comments
JavaScript — like most programming languages — has a syntax for making comments
in code. Comments are completely ignored by JavaScript; they are meant for you, or
your fellow programmers. They allow you to add natural language explanations of
what’s going on when it’s not clear. In this book, we’ll be using comments liberally in
code samples to explain what’s happening.
In JavaScript, there are two kinds of comments: inline comments and block com‐
ments. An inline comment starts with two forward slashes (//), and extends to the
end of the line. A block comment starts with a forward slash and an asterisk (/*) and
ends with an asterisk and a forward slash (*/), and can span multiple lines. Here’s an
example of both types of comments:
console.log("echo"); // prints "echo" to the console
/*
In the above line, everything up to the double forward-slashes
is JavaScript code, and must be valid syntax. The double
forweard slashes start a comment, and will be ignored by JavaScript.
This text is in a block comment, and will also be ignored
22 | Chapter 1: Your First Application
www.it-ebooks.info
29. by JavaScript. We've chosen to indent the comments of this block
for readability, but that's not necessary.
*/
/*look, ma, no indentation!*/
CSS (which we’ll see shortly) also use JavaScript syntax for block comments (inline
comments are not supported in CSS). HTML (like CSS) doesn’t have inline com‐
ments, and its block comments are different than JavaScript: they are surrounded by
the unwieldy <!-- and -->:
<head>
<title>HTML and CSS Example</title>
<!-- this is an HTML comment...
which can span multiple lines. -->
<style>
body: { color: red; }
/* this is a CSS comment...
which can span multiple lines. */
</style>
<script>
console.log("echo"); // back in JavaScript...
/* ...so both inline and block comments
are supported. */
</script>
</head>
Getting Started
We’re going to start by creating three files: an HTML file, a CSS file, and a JavaScript
source file. We could do everything in the HTML file (JavaScript and CSS can be
embedded in HTML), but there are certain advantages to keeping them separate. If
you’re new to programming, I strongly recommend that you follow along with these
instructions step by step: we’re going to be taking a very exploratory, incremental
approach in this chapter, which will facilitate your learning process.
It may seem like we’re doing a lot of work to do something fairly simple, and there’s
some truth in that. I certainly could have crafted an example that does the same thing
with many fewer steps, but by doing so, I would be teaching you bad habits. The extra
steps you’ll see here are ones you’ll see over and over again, and while it may seem
overcomplicated now, you can at least reassure yourself that you’re learning to do
things the right way.
One last important note about this chapter. This is the lone chapter in the book in
which the code samples will be written in ES5 syntax, not ES6 (Harmony). This is to
ensure that the code samples will run, even if you aren’t using a browser that has
implemented ES6. In following chapters, we will be talking about how to write code
in ES6 and “transcompile” it so that it will run on legacy browsers. After we cover that
Getting Started | 23
www.it-ebooks.info
30. ground, the rest of the book will use ES6 syntax. The code samples in this chapter are
simple enough that it doesn’t represent a significant handicap to use ES5.
For this exercise, you’ll want to make sure the files you create are in
the same directory or folder. I recommend that you create a new
directory or folder for this example so it doesn’t get lost among
your other files.
Let’s start with the JavaScript file. Using a text editor, create a file called main.js. For
now, let’s just put a single line in this file:
console.log('main.js loaded');
Then create the CSS file, main.css. We don’t actually have anything to put in here yet,
so we’ll just include a comment so we don’t have an empty file:
/* Styles go here. */
Then create a file called index.html:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="main.css">
</head>
<body>
<h1>My first application!</h1>
<p>Welcome to <i>Learning JavaScript, 3rd Edition</i>.</p>
<script src="main.js"></script>
</body>
</html>
While this book isn’t about HTML or web application development, many of you are
learning JavaScript for that purpose, so we will be pointing out some aspects of
HTML as they relate to JavaScript development. An HTML document consists of two
main parts: the head and the body. The head contains information that is not directly
displayed in your browser (though it can affect what’s displayed in your browser). The
body contains the contents of your page that will be rendered in your browser. It’s
important to understand that elements in the head will never be shown in the
browser, whereas elements in the body usually are (certain types of elements, like
<script> won’t be visible, and CSS styles can also hide body elements).
In the head, we have the line <link rel="stylesheet" href="main.css">; this is
what links the currently-empty CSS file into your document. Then, at the end of the
body, we have the line <script src="main.js"></script>, which is what links the
JavaScript file into your document. It may seem odd to you that one goes in the head
and the other goes at the end of the body, but there is a reason for it. While we could
24 | Chapter 1: Your First Application
www.it-ebooks.info
31. 3 You will learn more about the difference between a function and a method in Chapter 9.
have put the <script> tag in the head, there are performance and complexity reasons
for putting it at the end of the body.
In the body, we have <h1>My first application!</h1>, which is first-level header
text (which indicates the largest, most important text on the page), followed by a <p>
(paragraph) tag, which contains some text, some of which is italic (denoted by the
<i> tag).
Go ahead and load index.html in your browser. The easiest way to do this on most
systems is to simply double-click on the file from a file browser (you can also usually
drag the file onto a browser window). You’ll see the body contents of your HTML file.
There will be many code samples in this book. Because HTML and
JavaScript files can get very large, I won’t be listing out the whole
files every time: instead, I will be explaining in the text where the
code sample fits into the file. This may cause some trouble for
beginning programmers, but understanding the way code fits
together is important, and can’t be avoided. If you get completely
stuck, you can refer to the accompanying code repository, which
contains the examples in their entirety.
The JavaScript Console
We’ve already written some JavaScript: console.log('main.js loaded’). What did
that do? The console is a text-only tool for programmers to help them diagnose their
work. You will be using the console extensively as you go through this book.
Different browsers have different ways of accessing the console. Since you will be
doing this quite often, I recommend learning the keyboard shortcut. In Firefox, it’s
Ctrl-Shift-K (Windows & Linux) or Command-Option-K (Mac).
In the page you loaded index.html, open the JavaScript console; you should see the
text “main.js loaded” (if you don’t see it, try reloading the page). console.log is a
method3
that will print whatever you want to the console, which is very helpful for
debugging and learning alike.
One of the many helpful features of the console is that, in addition to seeing output
from your program, you can enter JavaScripit directly in the console, thereby testing
things out, learning about JavaScript features, and even modifying your program
temporarily.
The JavaScript Console | 25
www.it-ebooks.info
32. jQuery
We’re going to add an extremely popular client-side scripting library called jQuery to
our page. While it is not necessary, or even germane to the task at hand, it is such a
ubiquitous library that it is often the first library you will include in your web code.
Even though we could easily get by without it in this example, the sooner you start
getting used to seeing jQuery code, the better off you will be.
At the end of the body, before we include our own main.js, we’ll link in jQuery:
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="main.js"></script>
You’ll notice that we’re using an Internet URL, which means your page won’t work
correctly without Internet access. We’re linking in jQuery from a publicly-hosted
content-delivery network (CDN), which has certain performance advantages. If you
will be working on your project offline, you’ll have to download the file and link it
from your computer instead. Now we’ll modify our main.js file to take advantage of
one of jQuery’s features:
$(document).ready(function() {
'use strict';
console.log('main.js loaded');
});
Unless you’ve already had some experience with jQuery, this probably looks like gib‐
berish. There’s actually a lot going on here that won’t become clear until much later.
What jQuery is doing for us here is making sure that the browser has loaded all of the
HTML before executing our JavaScript (which is currently just a single console.log).
Whenever we’re working with browser-based JavaScript, we’ll be doing this just to
establish the practice: any JavaScript you write will go between the $(docu
ment).ready(function() { and }); lines. Also note the line 'use strict'; this is
something we’ll be learning about later, but basically this tells the JavaScript inter‐
preter to treat your code more rigorously. While that may not sound like a good thing
at first, it actually helps you write better JavaScript, and prevents common and
difficult-to-diagnose problems. We’ll certainly be learning to write very rigorous Java‐
Script in this book!
Drawing Graphics Primitive
Among many of the benefits HTML5 brought, a standardized graphics interface was
one of them. The HTML5 canvas allows you to draw graphics primitives like squares,
circles and polygons. Using the canvas directly can be painful, so we’ll be using a
graphics library called Paper.js to take advantage of the HTML5 canvas.
26 | Chapter 1: Your First Application
www.it-ebooks.info
33. 4 If you want to learn more about CSS and HTML, I recommend the Codeacademy’s free HTML & CSS track.
Paper.js is not the only canvas graphics library available: KineticJS,
Fabric.js and EaselJS are very popular and robust alternatives. I’ve
used all of these libraries, and they’re all very high quality.
Before we start using Paper.js to draw things, we’ll need an HTML canvas element to
draw on. Add the following to the body (you can put it anywhere; after the intro para‐
graph, for example):
<canvas id="mainCanvas"></canvas>
Note that we’ve given the canvas an id attribute: that’s how we will be able to easily
refer to it from within JavaScript and CSS. If we load our page right now, we won’t see
anything different; not only haven’t we drawn anything on the canvas, it’s a white can‐
vas on a white page and has no width and height, making it very hard to see indeed.
Every HTML element can have an ID, and for the HTML to be
valid (correctly formed), each ID must be unique. So now that
we’ve created a canvas with the id “mainCanvas”, we can’t re-use
that ID. Because of this, it’s recommended that you use them spar‐
ingly. We’re using it here because it’s often easier for beginners to
deal with one thing at a time, and by definition, an ID can only
refer to one thing on a page.
Let’s modify main.css so our canvas stands out on the page. If you’re not familiar with
CSS, that’s okay: this CSS is simply setting a width and height for our HTML element,
and giving it a black border4
.
#mainCanvas {
width: 400px;
height: 400px;
border: solid 1px black;
}
If you re-load your page, you should see the canvas now.
Now that we have something to draw on, we’ll link in Paper.js to help us with the
drawing. Right after we link in jQuery, but before we link in our own main.js, add the
following line:
<script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.9.24/paper-full.min.js"></script>
Note that, as with jQuery, we’re using a CDN to include Paper.js in our project.
Drawing Graphics Primitive | 27
www.it-ebooks.info
34. You might be starting to realize that the order in which we link
things in is very important. We’re going to use both jQuery and
Paper.js in our own main.js, so we have to link both of those in first.
Neither of them depend on each other so it doesn’t matter which
one comes first, but I always include jQuery first as a matter of
habit, since so many things in web development depend on it.
Now that we have Paper.js linked in, we have to do a little work to configure Paper.js.
Whenever you encounter code like this — repetitive code that is required before you
do something — it’s often called boilerplate. Add the following to main.js, right after
'use strict' (you can remove the console.log if you wish):
paper.install(window);
paper.setup(document.getElementById('mainCanvas'));
// TODO
paper.view.draw();
The first line installs Paper.js in the global scope (which will make more sense in
Chapter 7). The second line attaches Paper.js to the canvas, and prepares Paper.js for
drawing. In the middle, where we put TODO is where we’ll actually be doing the inter‐
esting stuff. The last line tells Paper.js to actually draw something to the screen.
Now that all of the boilerplate is out of the way, let’s draw something! We’ll start with
a green circle in the middle of the canvas. Replace the “TODO” comment with the
following lines:
var c = Shape.Circle(200, 200, 50);
c.fillColor = 'green';
Refresh your browser, and behold, a green circle. You’ve written your first real Java‐
Script. There’s actually a lot going on in those two lines, but for now, it’s only impor‐
tant to know a few things. The first line creates a circle object, and it does so with
three arguments: the x- and y-coordinates of the center of the circle, and the radius of
the circle. Recall we made our canvas 400 pixels wide and 400 pixels tall, so the center
of the canvas lies at (200, 200). And a radius of 50 makes a circle that’s an eighth of
the width and height of the canvas. The second line sets the “fill” color (which is dis‐
tinct from the outline color, which is called the “stroke” in Paper.js parlance). Feel free
to experiment with changing those arguments.
Automating Repetitive Tasks
Consider what you would have to do if you wanted to add not one circle, but fill the
canvas with them, laid out in a grid. If you space the circles 50 pixels apart, and make
them slightly smaller, you could fit 64 of them on the canvas. Certainly you could
copy the code you’ve already written 63 times and, by hand, modify all of the coordi‐
28 | Chapter 1: Your First Application
www.it-ebooks.info
35. nates so that they’re spaced out in a grid. Sounds like a lot of work, doesn’t it? Fortu‐
nately, this kind of repetitive task is what computers excel at. Let’s see how we can
draw out 64 circles, evenly spaced. We’ll replace our code that draws a single circle
with the following:
var c;
for(var x=25; x<400; x+=50) {
for(var y=25; y<400; y+=50) {
c = Shape.Circle(x, y, 20);
c.fillColor = 'green';
}
}
If you refresh your browser, you’ll see we have 64 green circles! If you’re new to pro‐
gramming, what you’ve just written may seem confusing, but you can see it’s better
than writing the 128 lines it would take to do this by hand.
What we’ve used is called a "for loop”, which is part of control flow syntax that we’ll
be learning about in detail in Chapter 4. A for loop allows you to specify an initial
condition (25), an ending condition (less than 400), and an increment value (50). We
use one loop inside of the other to accomplish this for both the x-axis and y-axis.
There are many ways we could have written this example. The way
we’ve written it, we’ve made the x- and y-coordinates the important
pieces of information: we explicitly specify where the circles are to
start and how far apart they’re supposed to be spaced. We could
have come at this problem from another direction: we could say
what’s important is the number of circles we want (64), and let the
program figure out how to space them so that they fit on the can‐
vas. The reason we went with this solution is that it better matches
what we would have done if we had cut and pasted our circle code
64 times and figured out the spacing ourselves.
Handling User Input
So far, what we’ve been doing hasn’t had any input from the user. The user can click
on the circles, but it doesn’t do anything. Likewise, trying to drag a circle would have
no effect. Let’s make this a little more interactive, by allowing the user to choose
where the circles get drawn.
It’s important to get used to the asynchronous nature of user input. An asynchronous
event is an event whose timing you don’t have any control over. A user’s mouse click is
an example of an asynchronous event: you can’t be inside your users’ minds, knowing
when they’re going to click. Certainly you can prompt their click response, but it is up
to them when — and if — they actually click. Asynchronous events arising from user
Handling User Input | 29
www.it-ebooks.info
36. 5 Technical reviewer Matt Inman suggested that the Paper.js developers might have been Photoshop users
familiar with “hand tool”, “direct selection tool”, etc.
input make intuitive sense, but we will be covering much less intuitive asynchronous
events in later chapters.
Paper.js uses an object called a tool to handle user input. If that choice of names seems
unintuitive to you, you are in good company: I agree, and don’t know why the
Paper.js developers used that terminology5
. It might help you to translate “tool” to
“user input tool” in your mind. Let’s replace our code that drew a grid of circles with
the following code:
var tool = new Tool();
tool.onMouseDown = function(event) {
var c = Shape.Circle(event.point.x, event.point.y, 20);
c.fillColor = 'green';
};
The first step in this code is to create our tool object. Once we’ve done that, we can
attach an event handler to it. In this case, the event handler is called onMouseDown.
Whenever the user clicks the mouse, the function we’ve attached to this handler is
invoked. This is a very important point to understand. In our previous code, the code
ran right away: we refreshed the browser, and the green circles appeared automati‐
cally. That is not happening here: if it were, it would draw a single green circle some‐
where on the screen. Instead, the code contained between the curly brackets after
function is executed only when time the user clicks the mouse on the canvas.
The event handler is doing two things for you: it is executing your code when the
mouse is clicked, and it is telling you where the mouse was clicked. That location is
stored in a property of the argument, event.point, which has two properties, x and
y, indicating where the mouse was clicked.
Note that we could save ourselves a little typing by passing the point directly to the
circle (instead of passing the x- and y-coordinates separately):
var c = Shape.Circle(event.point, 20);
This highlights a very important aspect of JavaScript: it’s able to ascertain information
about the variables that are passed in. In the previous case, if it sees three numbers in
a row, it knows that they represent the x- and y-coordinates and the radius. If it sees
two arguments, it knows that the first one is a point object, and the second one is the
radius. We’ll be learning more about this in Chapter 6 and Chapter 9.
30 | Chapter 1: Your First Application
www.it-ebooks.info
37. Hello World
Let’s conclude this chapter with a manifestation of Brian Kernighan’s 1972 example.
We’ve already done all the heavy lifting: all that remains is to add the text. Before your
onMouseDown handler, add the following:
var c = Shape.Circle(200, 200, 80);
c.fillColor = 'black';
var text = new PointText(200, 200);
text.justification = 'center';
text.fillColor = 'white';
text.fontSize = 20;
text.content = 'hello world';
This addition is fairly straightforward: we create another circle, which will be a back‐
drop for our text, then we actually create the text object (PointText). We specify
where to draw it (the center of the screen), and some additional properties (justifica‐
tion, color, and size). Lastly, we specify the actual text contents (“hello world”).
Note that this is not the first time we emitted text with JavaScript: we did that first
with console.log earlier in this chapter. We certainly could have changed that text to
“hello world”. In many ways, that would be more analogous to the experience you
would have had in 1972, but the point of the example is not the text, or how it’s ren‐
dered: the point is that you’re creating something autonomous, that has observable
effects.
By refreshing your browser with this code, you are participating in a venerable tradi‐
tion of “hello world” examples. If this is your first “hello world”, let me be the first to
welcome you to the club. If it is not, I hope that this example has given you some
insight into JavaScript.
Hello World | 31
www.it-ebooks.info
39. CHAPTER 2
JavaScript Development Tools
While you can write JavaScript with nothig more than an editor and a browser (as we
saw in the last chapter), JavaScript developers rely on some useful development tools.
Furthermore, since we are focusing on ES6 for the rest of this book, we’ll need a way
to convert our ES6 code to portable ES5 code. The tools we’ll be discussing in this
chapter a very common, and you are likely to encounter them in any open-source
project or software development team. The tools we’ll be introducing are:
• Git, a version control tool that helps you manage your project as it grows, and
collaborate with other developers.
• Node, which allows you to run JavaScript outside of the browser (and comes with
npm, which gives you access to the rest of the tools on this list).
• Gulp, a build tool that automates common development tasks (Grunt is a popular
alternative).
• Babel, a transcompiler that converts ES6 code to portable ES5 code.
• ESLint, a linter, that helps you avoid common mistakes, and makes you a better
programmer!
Don’t think of this chapter as a distraction from the topic at hand (JavaScript). Think
of it as a practical introduction to some important tools and techniques that are com‐
monly used in JavaScript development.
Writing ES6 Today
I have good news and bad news. The good news is that ES6 (aka Harmony aka Java‐
Script 2015) is an exciting, delightful evolution in the history of JavaScript. The bad
news is the world isn’t quite ready for it. That doesn’t mean you can’t use it now, but it
33
www.it-ebooks.info
40. 1 Some JavaScript engines — Node, for example — do compile your JavaScript, but it happens transparently.
is going to put an extra burden on the programmer, as ES6 code has to be transcom‐
piled into “safe” ES5 to ensure that it can run anywhere.
Programmers who have been around a while might be thinking “big deal; back in my
day, there wasn’t such a thing as a language that didn’t have to be compiled and
linked!” I’ve been writing software long enough to remember that time, but I do not
miss it: I enjoy the lack of fuss in interpreted languages like JavaScript1
.
One of the advantages of JavaScript has always been its ubiquity: it became the stan‐
dard browser scripting language almost overnight, and with the advent of Node, its
use broadened beyond the browser. So it is a bit painful to recognize that it will prob‐
ably be a few years before you can ship ES6 code without worrying about browsers
that don’t support it. If you’re a Node developer, the situation is a little bit brighter:
since you only have one JavaScript engine to worry about, you can track the progress
of ES6 support in Node.
The ES6 examples in this book can be run in Firefox, or on a web‐
site such as ES6 Fiddle. For “real world code,” however, you will
want to know the tools and techniques in this chapter.
One interesting aspect about JavaScript’s transition from ES5 to ES6 is that, unlike
language releases of the past, the adoption is gradual. That is, the browser you’re using
right now probably has some — but not all — features available in ES6. This gradual
transition is made possible in part by the dynamic nature of JavaScript, and in part by
the changing nature of browser updates. You may have heard the term “evergreen”
used to describe browsers: browser manufacturers are moving away from the concept
of having discrete browser versions that have to be updated. Browsers, they reason,
should be able to keep themselves up to date since they are always connected to the
internet (at least if they are going to be useful). Browsers still have versions, but it is
now more reasonable to assume that your users have the latest version — because
evergreen browsers don’t give users the option not to upgrade.
Even with evergreen browsers, however, it will be a while before you can rely on all of
the great features of ES6 being available on the client-side. So for the time being,
transcompilation (also called transpilation) is a fact of life.
ES6 Features
There are a lot of new features in ES6; so many that even the transcompilers we’ll be
talking about don’t currently support all of them. To help control the chaos, New
34 | Chapter 2: JavaScript Development Tools
www.it-ebooks.info
41. York-based developer kangax maintains an excellent compatibility table of ES6 (and
ES7) features. As of August 2015, the most complete implementation (Babel) is only
at 72%. While that may sound discouraging, it’s the most important features that have
been implemented first, and all of the features discussed in this book are available in
Babel.
We have a little bit of prep work to do before we can start transcompiling. We’ll need
to make sure we have the tools we need, and learn how to set up a new project to use
them, a process that will become automatic after you do it a few times. In the mean‐
time, you will probably want to refer back to this chapter as you start new projects.
Installing Git
If you don’t have Git installed on your system, you can find downloads and instruc‐
tions for your operating system on the Git homepage.
The Terminal
Throughout this chapter, we’ll be working in the terminal (also known as the com‐
mand line or command prompt). The terminal is a text-based way of interacting with
your computer, and is commoly used by programmers. Though it is certainly possible
to be an effective programmer without ever using the terminal, I believe it is an
important skill to have: many tutorials and books assume you’re using a terminal, and
many tools are designed to be used on the terminal.
The most ubiquitous terminal experience is a shell (terminal interface) called bash,
and it is avaialble by default on Linux and OSX machines. While Windows has its
own command line experience, Git (which we will be installing next) provides a bash
command line, which I recommend you use. In this book, we will be using bash.
On Linux and OSX, look in your programs for the Termainal program. On Windows,
after you install Git, look for “Git Bash” in your programs.
When you start the terminal, you see a prompt, which is where you will type com‐
mands. The default prompt may include the name of your computer or the directory
you’re in, and it will normally end with a dollar sign ($). Because of this, in the code
samples in this chapter, I will use a dollar sign to indicate the prompt. What follows
the prompt is what you should type. For example, to get a listing of the files in the
current directory, type ls at the prompt:
$ ls
In Unix, and therefore bash, directory names are separated with a forward slash (/).
Even in Windows, where directories are normally separated by backslashees (), Git
Bash translates backslashes to forward slashes. Bash also uses the tilde (~) as a short‐
cut for your home directory (where you should normally be storing your files).
ES6 Features | 35
www.it-ebooks.info
42. The basics you’ll need are the ability to change the current directory (cd), and make
new directories (mkdir). For example, to go to your home directory, type:
$ cd ~
The command pwd (print working directory) tells you what directory you’re currently
in:
$ pwd
To create a subdirectory called test, type:
$ mkdir test
To change to this newly-created directory, type:
$ cd test
Two periods (..) are a shortcut for “parent directory”. So to go “up” a directory (if
you’ve been following along, this will take you back to your home directory), type:
$ cd ..
There’s a lot more to learn about the terminal, but these basic commands are all you
need to get through the material in this chapter. If you want to learn more, I recom‐
mend the Console Foundations course on Treehouse.
Your Project Root
You’ll want to create a directory for each project. We’ll call this directory the project
root. For example, if you’re following along with the examples in this book, you could
create a lj directory, which would be your project root. In all the command-line
examples in this book, we’ll be assuming that you’re in the project root. If you try an
example, and it doesn’t work, the first thing to verify is that you’re in the project root.
Any files we create will be relative to the project root. For example, if your project
root is /home/joe/work/lj, and we ask you to create a file public/js/test.js, the full path
to that file should be /home/joe/work/lj/public/js/test.js.
Version Control: git
We won’t be discussing version control in detail in this book, but if you’re not using
version control, you should be. If you’re not familiar with Git, I encourage you to use
this book as an opportunity to practice.
First, from your project root, initialize a repository:
$ git init
This will create a project repository for you (there’s now a hidden directory called .git
in your project root).
36 | Chapter 2: JavaScript Development Tools
www.it-ebooks.info
43. Inevitably, there will be some files you never want tracked in version control: build
artifacts, temporary files, and the like. These files can be explicitly excluded in a file
called .gitignore. Go ahead and create a .gitignore file now with the following contents:
# npm debugging logs
npm-debug.log*
# project dependencies
node_modules
# OSX folder attributes
.DS_Store
# temporary files
*.tmp
*~
If there are any other “junk” files that you know, you’re welcome to add them here
(for example, if you know your editor creates .bak files, you would add *.bak to this
list).
A command you’ll be running a lot is git status, which tells you the current status
of your repository. Go ahead and run it now. You should see:
$ git status
On branch master
Initial commit
Untracked files:
(use "git add <file>..." to include in what will be committed)
.gitignore
nothing added to commit but untracked files present (use "git add" to track)
The important thing that Git is telling you is that there’s a new file in the directory
(.gitignore), but it’s untracked, meaning Git doesn’t recognize it.
The basic unit of work in a Git repository is the commit. Currently, your repository
doesn’t have any commits (you’ve just initialized it, and created a file, but haven’t reg‐
istered any of that work with Git). Git doesn’t make any assumptions about what files
you want to track, so you have to explicitly add .gitignore to the repository:
$ git add .gitignore
We still haven’t created a commit; we’ve simply staged the file .gitignore to go in the
next commit. If we run git status again, we will see:
$ git status
On branch master
ES6 Features | 37
www.it-ebooks.info
44. Initial commit
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: .gitignore
Now .gitignore is to be committed. We still haven’t created a commit yet, but when we
do, our changes to .gitignore will be in it. We could add more files, but let’s go ahead
and create a commit now:
$ git commit -m "Initial commit: added .gitignore."
The string that follows +-m” is the commit message: a brief description of the work
you’ve done in this commit. This allows you to look back at your commits, and see
the history of your project unfold.
You can think of a commit as a snapshot of your project at a moment in time. We’ve
now taken a snapshot of the project (with only the .gitignore file in it), and you could
go back to that at any time. If you run git status now, Git will tell you:
On branch master
nothing to commit, working directory clean
Let’s make some additional changes to our project. In our .gitignore file, we’re ignor‐
ing any files named npm-debug.log, but let’s say we want to ignore any files with
the .log extension (which is standard practice). Edit the .gitignore file and change that
line to *.log. Let’s also add a file README.md, which is a standard file that explains
the project in the popular Markdown format:
= Learning JavaScript, 3rd Edition
== Chapter 2: JavaScript Development Tools
In this chapter we're learning about Git and other
development tools.
Now type git status:
$ git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: .gitignore
Untracked files:
(use "git add <file>..." to include in what will be committed)
README.md
38 | Chapter 2: JavaScript Development Tools
www.it-ebooks.info
45. We now have two changes: one to a tracked file (.gitignore) and one to a new file
(README.md). We could add the changes as we did before:
$ git add .gitignore
$ git add README.md
But this time we’ll use a shortcut to add all changes, then create a commit with all of
those changes:
$ git add -A
$ git commit -m "Ignored all .log files and added README.md."
This is a common pattern you’ll be repeating frequently (adding changes and then
committing them). Try to make your commits small and logically consistent: think of
them as telling a story to someone else, explaining your thought process. Whenever
you make changes to your repository, you’ll be following the same pattern: add one or
more changes, then create a commit:
$ git add -A
$ git commit -m "<brief description of the changes you just made>"
Beginners are often confused by git add; the name makes it seem
like you’re adding files to the repository. Those changes can be new
files, but just as likely they’re changes to files already in the reposi‐
tory. In other words, you’re adding changes, not files (and a new file
is just a special type of change).
This represents the simplest possible Git workflow; if you want to learn more about
Git, I recommend GitHub’s Git Tutorial and Jon Loeliger’s book, Version Control
with Git, 2nd Edition.
Package Management: npm
While understanding npm is not strictly necessary to JavaScript development, it’s
increasingly becoming the package management tool of choice. For Node develop‐
ment, it’s practically essential. Whether you’re actually writing Node apps, or just
doing browser development, you’ll find that life is a lot easier with npm. In particular,
we’ll be using npm to install our build tools and transcompilers.
npm comes bundled with Node, so if you haven’t installed Node already, go to the
Node.js homepage and click on the big green “INSTALL” button. Once you’ve
installed Node, verify that npm and node are functioning on your system. From the
command line, do the following:
$ node -v
v0.12.0
$ npm -v
2.5.1
ES6 Features | 39
www.it-ebooks.info
46. Your version numbers may vary as Node and npm are updated. Broadly speaking,
npm manages installed packages. A package can be anything from a full application,
to sample code, to a module or library that you’ll use in your project.
npm supports installing packages at two levels: globally and locally. Global packages
are usually command-line tools that you’ll use in the development process Local
packages are project-specific. Installing a package is done with the npm install com‐
mand. Let’s install the popular Underscore package to see how it works: in your
project root, run the following:
$ npm install underscore
underscore@1.8.3 node_modulesunderscore
npm is telling you that it installed the latest version of Underscore (1.8.3 as I write
this; yours will probably be different). Underscore is a module with no dependencies,
so the output from npm is very brief; for some complex modules, you may see pages
of text go by! If we wanted to install a specific version of Underscore, we can specify
the version number explicitly:
$ npm install underscore@1.8.0
underscore@1.8.0 node_modulesunderscore
So where did this module actually get installed? If you look in your directory, you’ll
see a new subdirectory called node_modules; any local modules you install will go in
this directory. Go ahead and delete the node_modules directory; we’ll be re-creating it
in a moment.
As you install modules, you’ll want to keep track of them somehow; the modules you
install (and use) are called dependencies of your project. As your project matures,
you’ll want a concise way to know what packages your project depends on, and npm
does this with a file called package.json. You don’t have to create this file yourself: you
can run npm init, and interactively answer some questions (you can simply press
enter for each question and accept the defaults: you can always edit the file and
change your answers later). Go ahead and do this now, and take a look at the gener‐
ated package.json file.
Dependencies are split into regular dependencies and dev dependencies. Dev depen‐
dencies are packages that your app can run without, but are helpful or necessary in
building your project (we’ll see examples of these soon). From here on out, when you
install local packages, you should add either the --save or --saveDev flag; if you
don’t, the package will be installed, but not listed in the package.json file. Let’s go
ahead and re-install Underscore with the --save flag:
$ npm install --save underscore
npm WARN package.json lj@1.0.0 No description
npm WARN package.json lj@1.0.0 No repository field.
underscore@1.8.3 node_modulesunderscore
40 | Chapter 2: JavaScript Development Tools
www.it-ebooks.info
47. You might be wondering what all of these warnings are. Npm is telling you that there
are some components missing from your package. For the purposes of this book, you
can ignore these warnings: you only need to worry about them if you’re using npm to
publish your own packages, which is beyond the scope of this book.
Now if you look at your package.json file, you’ll see that Underscore is listed as a
dependency. The idea of dependency management is that the dependencies refer‐
enced in package.json are all you need to re-create the dependencies. Let’s try this out.
Delete the node_modules directory again, and then run npm install (note we don’t
specify any specific package name). Npm will install any packages listed in the pack‐
age.json file. You can look at the newly-created node_modules directory to verify this.
The Transcompilers
As I write this, the two most popular transcompilers are Babel and Traceur. I have
used both, and they are both quite capable and easy to use. I am currently leaning
slightly towards Babel, and we’ll be using it as the transcompiler in this book. So let’s
get started!
There are multiple ways to use Babel, from the command line to build tool integra‐
tions. We’ll start with babel-node, which gives you a run-eval-print loop (REPL),
which is a great learning tool, and for testing out small bits of code.
First, install Babel (here we’re using the -g switch to install this package globally):
$ npm install -g babel
If you’re on Linux or OSX, you’ll need elevated privileges to use the
-g (global) switch when running npm: sudo install -g babel.
You’ll be prompted for your password and given superuser privi‐
leges (for that command only). If you are on a system that someone
else manages, you might have to ask them to put you in the sudoers
file.
Once we’ve installed Babel, we can start a REPL by typing babel-node. You’ll be pre‐
sented with a right angle bracket (>) prompt, which indicates to you that you can
input JavaScript (this is the “R” part of REPL: reading your input). Then the REPL
will evaluate (the “E”) the code, print the result (“P”), and return you to the prompt
(“L” back to “R”). Try it out with the following example:
$ > let name = "<your name>"
'use strict'
$ > `Hello, ${name}, welcome to ES6!`
'Hello, <your name>! Welcome to ES6!'
The Transcompilers | 41
www.it-ebooks.info
48. For statements (such as variable assignment) that don’t evaluate to a value, babel-
node currently prints 'use strict', an artifact of its implementation. If you enter an
expression, the value of the expression will be printed.
This is a great way to play around and try out features in an interactive manner, but
it’s pretty limited for anything more sophisticated.
Build Tools: Gulp and Grunt
For most development, you’ll probably want a build tool, which automates the repeti‐
tive tasks you perform as part of the development process. The two most popular
build tools for JavaScript, currently, are Grunt and Gulp. These are both capable build
systems. Grunt has been around a couple of years longer than Gulp, so the commu‐
nity is larger, but Gulp is catching up fast. Because Gulp seems to be the increasingly
popular choice for new JavaScript programmers, we’ll use Gulp in this book, though I
am not prepared to say Gulp is superior to Grunt (or vice versa).
First, you’ll install Gulp globally with npm install -g gulp. You’ll only need to do
that once for each system you develop on. Then, for each project, you’ll need a local
Gulp, so from your project root, run npm install --save-dev gulp (Gulp is an
example of a dev dependency: your app won’t need it to run, but you’ll use it to help
with your development process). Now that Gulp has been installed, we create a Gulp‐
file (gulpfile.js):
var gulp = require('gulp');
// Gulp dependencies go here
gulp.task('default', function() {
// Gulp tasks go here
});
We haven’t actually configured Gulp to do anything yet, but we can verify that Gulp
can run successfully now:
$ gulp
[16:16:28] Using gulpfile /home/joe/work/lj/gulpfile.js
[16:16:28] Starting 'default'...
[16:16:28] Finished 'default' after 68 μs
42 | Chapter 2: JavaScript Development Tools
www.it-ebooks.info
49. If you’re a Windows user, you may get the error “The build tools
for Visual Studio 2010 (Platform Toolset = v100) cannot be found.”
Many npm packages have a dependency on Visual Studio build
tools. You can get a free version of Visual Studio at https://www.visu
alstudio.com/en-us/visual-studio-homepage-vs.aspx. Once you’ve
installed Visual Studio, look for “Developer Command Prompt” in
your program files. In that command prompt, navigate to your
project root and try to install Gulp again, and you should have bet‐
ter luck. You don’t need to continue using the Visual Studio Devel‐
oper Command Prompt, but it’s the easiest way to install npm
modules that have dependencies on Visual Studio.
Project Structure
Before we use Gulp and Babel to convert our ES6 code to ES5, we need to think about
where we’re going to put our code within our project. There’s no one universal stan‐
dard for project layout in JavaScript development: the ecosystem is just too diverse
for that. Very commonly, you’ll see source code in src or js directories. We’re going to
put our source in es6 directories, to make it perfectly clear that we’re writing ES6
code.
Since many projects include both of server-side (Node) code and client-side
(browser) code, we’re going to separate these two categories as well. Server-side code
will simply go in the es6 directory in our project root, and code destined for the
browser will go in public/es6 (by definition, any JavaScript sent to the browser is pub‐
lic, and this is a very common convention).
In the next section, we’ll be taking our ES6 code and converting it to ES5, so we’ll
need a place to put that ES5 code (we don’t want to mix it in with ES6 code). A com‐
mon convention is to put that code in a directory called dist (for “distribution”).
Putting it all together, your project root will look something like this:
.git # Git
.gitignore
package.json # npm
node_modules
es6 # Node source
dist
public/ # browser source
es6/
dist/
The Transcompilers | 43
www.it-ebooks.info
51. MÉMOIRE
POUR ELISABETH- FRANÇOISE POIRIER D' ARINGY, Fille majeure,
Intimée;
CONTRE ses Beaux-Freres.
RÉSOLUE de donner ma main à M. de B...., Trésorier de France à
Paris, j'en avois fait part à ma famille; cette alliance qui, à tous
égards, me fait honneur, & m'est avantageuse, a déplu à mes beaux-
freres, ils y ont formé opposition; c'est, disent-ils, mon bien qu'ils ont
uniquement en vue, & c'est ce principe qui est l'ame de toutes leurs
démarches; je le crois comme eux: mais je suis majeure, sans pere
ni mere, maîtresse par-conséquent de mon choix; celui-ci seul me
convient, il est réfléchi, & le suffrage de tous les gens désintéressés
le justifie: ainsi j'espere que la Cour confirmera par son Arrêt la
Sentence que j'ai obtenue depuis long-tems au Châtelet qui me fait
main-levée de leur opposition à mon mariage.
Signé, POIRIER D' ARIGNY.
Me
. COQUELEY DE
CHAUSSE-PIERRE,
Avocat.
54. PRÉCIS
POUR le Sieur BOUCHER DE VILLERS, Peintre, Dessinateur des
Médailles pour le Cabinet du Roi, Demandeur;
CONTRE le Sieur C....., Apothicaire, Défendeur.
UN Apothicaire qui s'est fait peindre ne veut pas satisfaire son
Peintre, il ne lui offre pour paiement que de mauvaises drogues; le
portrait, dit-il, n'est pas ressemblant; comme si une Partie pouvoit
être Juge dans sa propre cause, ou que l'on dût s'en rapporter à un
Apothicaire pour juger de la ressemblance des visages? Si le sieur
C...... eût examiné de bien près sa prétention, il auroit vu qu'elle est
absolument sans fondement, & l'auroit sans doute abandonnée sur
le champ.
FA I T.
Le sieur C..., Apothicaire, vint, il y a plus d'un an, prier le sieur de
Villers de lui faire son portrait. Un autre Peintre quelque tems avant,
avoit déja peint l'Apothicaire, à l'huile; mais celui-ci vouloit une
miniature pour faire un brasselet à sa femme.
Le sieur de Villers y consentit; mais comme leurs occupations, qui
ont des objets diamétralement opposés, ne leur permettoient pas de
trouver des occasions de se réunir, le sieur C.... proposa d'envoyer
son portrait, & le sieur de Villers s'engagea d'en faire une copie pour
laquelle il voulut bien se restreindre à 96 liv. que le sieur C.... promit
de lui payer.
L'ouvrage fini, le sieur C...., qui le vint voir, le trouva bien; mais au
lieu d'un petit bonnet & d'une robe de chambre, il demanda en grace
55. une perruque nouée & un habit noir. Le sieur de Villers pour les 96
liv. n'étoit assurément pas obligé d'habiller & de deshabiller ainsi le
sieur C... à sa volonté; cependant, quoique le premier portrait fût en
robe de chambre, & que le sieur C.... qui étoit d'une figure très-
agréable, fût très-bien en deshabillé, le sieur de Villers voulut bien se
prêter à lui mettre sa perruque & son habit, sans prétendre aucune
augmentation au prix convenu.
Quand tout fut fait au gré du sieur C.... & qu'il n'y avoit plus qu'à
payer, son empressement se ralentit, il employa toutes sortes de
délais, de défaites peu vraisemblables & de finesses maladroites
pour avoir ses portraits & ne rien donner; le sieur de Villers qui s'en
apperçut aisément, l'a fait avertir dix fois, sans succès, de les retirer
en lui donnant 96 livres; il n'a répondu que par des propos vagues,
& a été jusqu'à compromettre le Lieutenant de Police, en se vantant
qu'avec un simple placet il obligeroit le sieur de Villers à rendre le
portrait à l'huile, & garder le portrait en miniature.
Le sieur de Villers a donc été forcé de faire sommer le sieur C..... de
le payer en lui remettant les deux portraits, & trois jours après de le
faire assigner au Châtelet aux mêmes fins.
Le sieur C..... dans ses défenses a dénaturé tous les faits, en
convenant néanmoins du marché fait à 96 livres. Ainsi ce marché est
une chose constante entre les Parties; mais il a prétendu avoir fourni
au sieur C.... pour 60 liv. 9 sous de drogues, dont il a demandé la
condamnation contre lui en lui offrant 35 liv. 11 sous pour le surplus,
au cas que par des gens de l'art le portrait en miniature fût jugé
ressemblant.
Le sieur de Villers par ses repliques a rétabli les faits; il convient
d'abord que le sieur C.... lui a fourni plusieurs drogues, tant bonnes
que mauvaises, détaillées dans un mémoire que le sieur de Villers
rapporte & qu'il a fait régler par un homme de l'art, car on sçait
qu'un mémoire d'Apothicaire est dans le cas au moins, autant que
bien d'autres, d'être réglé; à l'égard de l'Apothicaire en miniature, il
le soutient ressemblant à l'Apothicaire à l'huile, & c'est tout ce qu'il
56. avoit promis de faire. Quelques réflexions très-courtes vont lever le
voile, & montrer au sieur C.... la vérité à découvert.
M O Y E N S .
Le sieur de Villers s'est engagé à faire le portrait en miniature du
sieur C...., d'après un portrait à l'huile de ce même sieur C...., la
preuve en résulte de ce que le sieur C.... lui a envoyé ce portrait à
l'huile, qui est encore entre les mains du sieur de Villers; le prix fut
fixé à 96 livres. Le sieur C... en convient; l'Apothicaire à l'huile est en
robe de chambre, le sieur de Villers mit en robe de chambre sa
miniature; le sieur C.... voulut une perruque nouée & un habit noir,
le sieur de Villers s'y prêta & ne demande rien de plus: tous ces faits
sont constans: il faut donc que le sieur C.... lui paye 96 liv.
Celui-ci, qui voudroit avoir ses portraits & ne pas payer, s'alembique
l'esprit pour trouver un remede à son embarras; il voudroit s'en tirer
avec de la manne en sorte, de la casse cuite & du petit lait;
assurément de la bonne casse est bonne, mais il ne suffit pas de
purger son créancier pour se libérer avec lui, il lui restera toujours de
l'humeur tant qu'il ne sera pas payé, & des parties d'Apothicaire
enflées de moitié, n'opéreront jamais un paiement légitime.
Le sieur C.... a promis de payer 96 livres, il ne le nie pas, il a fourni
au sieur de Villers pour 40 liv. de drogues; suivant son mémoire
réglé, il doit donc encore 56 livres. Le sieur C... n'a jamais rien fait
de plus clair que ce calcul, & le sieur de Villers nie formellement qu'il
lui ait jamais été rien fourni de plus par le sieur C...., qui d'ailleurs,
aux termes de la Coutume de Paris, n'a plus d'action.
Aussi se méfiant de cette ressource, il avance que le portrait ne lui
ressemble pas. Mais c'est de sa part une équivoque qu'il faut
éclaircir. Il est possible que la miniature ne lui ressemble pas au
dernier point de perfection; & voici pourquoi. Dans tout ceci, c'est le
sieur C.... qui est original, les deux portraits sont copies, le sieur de
Villers s'étoit engagé pour 96 liv. de faire ressembler le portrait en
miniature au portrait que lui avoit envoyé le sieur C.....: or le sieur
57. de Villers met en fait que l'Apothicaire en miniature ressemble, non
pas peut-être à l'Apothicaire original, il ne s'y étoit pas engagé, mais
très-parfaitement à l'Apothicaire à l'huile.
Une seconde raison est, qu'on ne se reconnoît pas si bien soi-même,
& dès-là il est moins étonnant que le sieur C... s'y trompe.
D'ailleurs lorsqu'on le peignit à l'huile il avoit cinq ou six ans de
moins, & possédoit alors la plus jolie figure d'Apothicaire, sans
comparaison, qu'il y ait à Paris; mais le tems peut lui avoir enlevé
quelqu'une de ses graces.
Enfin, dans le portrait à l'huile, il est peint en robe de chambre, à
son fourneau, près d'une cornuë, d'un récipient & de plusieurs
phioles; au lieu que dans la miniature, à cause du petit espace, tout
ce qu'il y avoit de cornuë, de récipient, &c. a été supprimé, & il a
voulu une perruque & un habit noir. Peut-être toutes ces différences
lui ont-elles fait illusion; le sieur de Villers aime à se le persuader, &
voudroit sauver le sieur C.... du soupçon de mauvaise foi, en le
supposant dans l'erreur.
Mais il en faut revenir au vrai, le portrait en miniature ressemble au
portrait à l'huile, le sieur de Villers le soutient, la vue seule en
décide. Resteroit-il du doute? le sieur de Villers veut bien consentir,
quoique ce ne soit pas le cas, que des Experts donnent leur avis, si
les Juges le croient nécessaire. Ces Experts peuvent se passer du
sieur C..., ils ne doivent même pas voir l'original, ils n'ont à juger
que la ressemblance d'une copie à l'autre. D'après leur avis, il ne
restera plus qu'à condamner le sieur C..... au paiement de 96 livres,
prix convenu & avoué, à la déduction de 40 livres & quelques sous
pour les drogues que le sieur de Villiers consent avoir reçues, & en
tous les dépens.
Ce Mémoire est de Me.
Coqueley de Chausse-
Pierre, Avocat.
60. MÉMOIRE
POUR les Coëffeurs des Dames de Paris.
NOUS sommes par essence des Coëffeurs des Dames, & des
fonctions pareilles ont dû nous assurer de la protection, mais cette
protection a fait des envieux; tel est l'ordre des choses. Les Maîtres
Barbiers-Perruquiers sont accourus avec des têtes de bois à la main;
ils ont eu l'indiscrétion de prétendre que c'étoit à eux de coëffer
celles des Dames. Ils ont abusé d'Arrêts qui nous sont étrangers,
pour faire emprisonner plusieurs d'entre nous; ils nous tiennent en
quelque sorte le rasoir sur la gorge, & c'est contre cette tyrannie que
nous nous trouvons aujourd'hui forcés d'implorer le secours de la
Justice.
Nous avons commencé par consulter un Jurisconsulte, qui nous a
dit, que les Loix Romaines ne statuoient rien sur les droits que nous
réclamons; qu'il y a grande apparence que nous n'existions pas, lors
des capitulaires de Charlemagne; qu'il est possible que nous ayons
eu l'être civil à Athenes, dans ses jours de délices; qu'au surplus,
depuis cette époque jusqu'à nous, il s'étoit écoulé plus de deux mille
ans de tems, utile pour la prescription.
Ce langage nous a d'abord donné de l'inquiétude; nous avons
cherché d'autres secours, & nous les avons trouvés. La science des
Jurisconsultes n'est pas celle qui convient à l'exposition de nos
moyens; la question dont il s'agit ici exige des détails étrangers à
leur doctrine.
Les Perruquiers prétendent que c'est à eux seuls qu'il appartient de
coëffer les Dames.
61. Pour renverser leur prétention nous établirons; 1o
. que l'Art de
coëffer les Dames, est un Art libre, étranger à la Profession des
Maîtres Perruquiers; 2o
. que les Statuts des Perruquiers ne leur
donnent pas le droit exclusif qu'ils prétendent avoir; 3o
. qu'ils ont
abusé des Arrêts de la Cour pour exercer des vexations contre nous,
& qu'ils nous doivent des dommages & intérêts considérables.
P R E M I E R O B J E T.
Il faut faire une grande différence entre le métier de Barbier-
Perruquier & le talent de coëffer les Dames. La profession de
Perruquier appartient aux Arts méchaniques: la profession de
Coëffeurs des Dames appartient aux Arts libéraux.
Les Arts méchaniques ont donné naissance à l'établissement des
différens Corps & Communautés. Ces Arts se bornent à une pratique
purement manuelle, bien au-dessous des créations du génie, & se
tiennent renfermés dans la sphere étroite qui leur est propre.
Il n'en est pas de même des Arts libéraux pour lesquels on payeroit
inutilement une Maîtrise; ce n'est point avec quelque piece de métal
qu'on peut acheter ce goût, cette faculté active d'inventer & de
produire, qui leur donne l'existence & la vie; il faut porter dans son
ame le germe des talens créateurs: quiconque a le génie propre à
l'Art qu'il adopte, doit l'exercer avec pleine liberté; telles sont les
maximes protectrices des beaux Arts, celles à la faveur desquelles ils
ont fait en France des progrès si merveilleux. Il eût été ridicule
d'ériger en Corps & Communauté les Poëtes, les Statuaires, les
Peintres, les Musiciens, comme les Perruquiers, les Cordonniers & les
Tailleurs.
Le Peintre anime la toile, le Statuaire un bloc de marbre, l'un &
l'autre parlent aux yeux pour les tromper, & ce prestige est la
perfection de l'ouvrage. Le Musicien & le Poëte portent à l'ame les
objets sur lesquels ils s'exercent, & quand ils ont le génie de leur Art,
62. ils peignent en traits de flammes, ils échauffent tout ce qui se trouve
dans la sphere de leur activité.
Nous ne sommes ni Poëtes, ni Peintres, ni Statuaires, mais par les
talens qui nous sont propres, nous donnons des graces nouvelles à
la beauté, que chante le Poëte; c'est souvent d'après nous que le
Peintre & le Statuaire la représentent; & si la chevelure de Bérénice
a été mise au rang des Astres, qui nous dira que pour parvenir à ce
haut degré de gloire, elle n'ait pas eu besoin de notre secours?
Les détails que notre Art embrasse se multiplient à l'infini.
Un front plus ou moins grand, un visage plus ou moins rond,
demandent des traitemens bien différens; par-tout il faut embellir la
nature, ou réparer ses disgraces. Il convient encore de concilier avec
le ton de chair la couleur sous laquelle l'accommodage doit être
présenté. C'est ici l'Art du Peintre, il faut connoître les nuances,
l'usage du clair obscur, & la distribution des ombres, pour donner
plus de vie au teint & plus d'expression aux graces; quelquefois la
blancheur de la peau sera relevée par la teinte rembrunie de la
chevelure, & l'éclat trop vif de la blonde sera modéré par la couleur
cendrée, dont nous revêtirons ses cheveux.
L'accommodage se varie encore à raison des situations différentes.
La coëffure de l'entrevue n'est pas celle du mariage, & celle du
mariage n'est pas celle du lendemain. L'art de coëffer la prude, & de
laisser percer les prétentions sans les annoncer, celui d'afficher la
coquette, & de faire de la mere la sœur aînée de sa fille; d'assortir le
genre aux affections de l'ame, qu'il faut quelquefois deviner; au desir
de plaire, qui se manifeste; à la langueur du maintien qui ne veut
qu'intéresser; à la vivacité qui ne veut pas qu'on lui résiste; d'établir
des nouveautés, de seconder le caprice, & de le maîtriser
quelquefois; tout cela demande une intelligence qui n'est pas
commune, & un tact pour lequel il faut en quelque sorte être né.
Les progrès de notre Art se portent encore plus loin. Sur ce Théâtre
où regne l'illusion, où les Dieux, les Héros, les Démons, les Fées, les
63. Magiciens, se reproduisent sans cesse; une tête sortant de nos
mains est tantôt celle d'une Divinité, tantôt celle d'une Héroïne,
tantôt celle d'une simple Bergere; la chevelure d'Armide n'a rien de
commun avec celle de Diane, & celle de Diane n'a rien de commun
avec celle d'Alcimadure; les cheveux serpentans & entrelacés des
furies, ne forment-ils pas le plus parfait contraste avec les
ondulations des cheveux flottans de l'Amour? C'est en saisissant les
nuances attachées à ces différens genres, que le charme se
perpétue, & qu'on reconnoît la main d'un Artiste habile.
L'Art des Coëffeurs des Dames est donc un Art qui tient au génie, &
par conséquent un Art libéral & libre.
L'arrangement des cheveux & des boucles ne remplit pas même tout
notre objet. Nous avons sans cesse sous nos doigts les trésors de
Golconde. C'est à nous qu'appartient la disposition des diamans, des
croissans, des sultanes, des aigrettes. Le Général d'Armée sçait quel
fond il doit faire sur une demi-lune placée en avant; il a ses
Ingénieurs en titre; nous sommes Ingénieurs en cette partie, avec
un croissant avantageusement placé, il est bien difficile qu'on nous
résiste, & que l'ennemi ne se rende: c'est ainsi que nous assurons &
que nous étendons sans cesse l'empire de la beauté.
Les fonctions des Barbiers-Perruquiers sont bien différentes; tondre
une tête, acheter sa dépouille, donner à des cheveux qui n'ont plus
de vie la courbe nécessaire avec le fer & le feu; les tresser, les
disposer sur un simulacre de bois, employer le secours du marteau,
comme celui du peigne, mettre sur la tête d'un Marquis la chevelure
d'un Savoyard, & quelquefois pis encore, se faire payer bien cher la
métamorphose; barbouiller des figures pour les rendre plus propres;
enlever avec un acier tranchant, au menton d'un homme, l'attribut
de son sexe, baigner, étuver, &c; ce ne sont-là que des fonctions
purement méchaniques, & qui n'ont aucun rapport nécessaire avec
l'Art que nous venons de décrire.
Les Perruquiers auront, si l'on veut encore, la faculté de faire
l'accommodage des cheveux naturels des hommes, parce que cet
64. accommodage ne doit être qu'un arrangement de propreté. Nous
aurions pû cependant leur disputer la coëffure des Petits-Maîtres, par
une raison d'analogie; mais nous laisserons volontiers leurs têtes
entre les mains d'un Perruquier, pour qu'ils fassent moins de progrès
dans la coquetterie; en un mot, nous ne coëffons que les Dames;
leurs maris même ne sont pas de notre compétence, & tant que
nous nous renfermerons dans des bornes pareilles, la jalousie des
Perruquiers pourra crier, mais la Police n'aura rien à nous dire.
En vain les Perruquiers objecteroient-ils, que s'ils ont la main trop
pesante pour la coëffure des Dames, ils peuvent avoir chez eux des
Garçons qui l'ayent beaucoup plus légere.
Cette objection seroit un aveu, que l'Art de coëffer les Dames ne
seroit pas propre à leur état, puisque les Maîtres n'auroient pas le
talent nécessaire pour l'exercer; & de-là nous pourrions conclure,
que leurs Garçons distraits par d'autres soins ne l'acquerroient pas
davantage; mais une raison bien plus puissante s'oppose, à ce que
les Dames employent les Garçons Perruquiers pour leur coëffure: les
Garçons Perruquiers changent à chaque instant de boutique, & ces
changemens perpétuels ne permettent pas de les admettre à un
ministere de confiance tel que le nôtre.
Le Coëffeur d'une femme est en quelque sorte le premier Officier de
sa toilette; il la trouve sortant des bras du repos, les yeux encore à
demi-fermés, & leur vivacité, comme enchaînée par les impressions
d'un sommeil, qui est à peine évanoui. C'est dans les mains de cet
Artiste, c'est au milieu des influences de son Art, que la rose
s'épanouit en quelque sorte, & se revêt de son éclat le plus beau;
mais il faut que l'Artiste respecte son ouvrage, que placé si près par
son service il ne perde pas de vue l'intervalle, quelquefois immense,
que la différence des états établit; qu'il ait assez de goût pour sentir
les impressions que son Art doit faire, & assez de prudence pour les
regarder comme étrangeres à lui.
Il est donc vrai de dire, que ni les Perruquiers ni leurs Garçons, ne
sont pas propres à faire l'office des Coëffeurs des Dames; que l'Art
65. des Coëffeurs est étranger à la Communauté des Maîtres
Perruquiers, comme étant un Art libre & libéral.
Voyons maintenant si les Statuts de la Communauté des Maîtres
Perruquiers ne présentent rien qui puisse porter la plus légere
atteinte aux vérités que nous venons d'établir: c'est le second objet
de nos réflexions.
D E U X I E M E O B J E T.
L'article 58 des Statuts des Maîtres Perruquiers, s'exprime ainsi, aux
seuls Barbiers-Perruquiers, Baigneurs, Etuvistes, appartiendra le
droit de faire poil, bains, perruques, étuves, & toutes sortes
d'ouvrages de cheveux, tant pour hommes que pour femmes, à
peine de confiscation des ouvrages, cheveux & ustensiles.
Cet article seul suffiroit pour faire sentir la différence essentielle qui
se trouve entre les Perruquiers & les Coëffeurs des Dames.
Le Perruquier a une matiere d'ouvrage, & le Coëffeur n'a qu'un sujet.
La matiere est ce que l'on emploie dans le travail; le sujet est ce sur
quoi l'on travaille. Le Perruquier travaille avec les cheveux, le
Coëffeur sur les cheveux. Le Perruquier fait des ouvrages de
cheveux, tels que des perruques, des boucles; le Coëffeur ne fait
que maniérer les cheveux naturels, leur donner une modification
élégante & agréable: le Perruquier est un Marchand qui vend sa
matiere & son ouvrage; le Coëffeur ne vend que ses services; la
matiere sur laquelle il s'exerce, n'est point à lui.
D'après ces définitions, l'article cité ne présentera point
d'équivoques; les Perruquiers auront seuls le droit de faire & de
vendre des ouvrages de cheveux, tels que des perruques & boucles
factices, il sera défendu aux autres d'en fabriquer & vendre, à peine
de confiscation desdits ouvrages, cheveux & ustensiles; mais ils ne
confisqueront pas la frisure naturelle d'une Dame, qui n'aura point
employé leur ministere, parce que cette frisure n'est point dans le
Commerce, & parce que la chevelure, qui fait ici la matiere de
66. l'ouvrage, appartenant par ses racines à la tête qui la porte, les
Perruquiers ne peuvent avoir aucun droit sur cette matiere & sur sa
modification.
Les Perruquiers objectent qu'ils ont, en vertu de l'article cité, le droit
exclusif de faire l'accommodage des cheveux naturels des hommes,
& que par conséquent ils doivent avoir également le droit de faire
celui des femmes exclusivement.
Nous leur répondons d'abord que l'article cité ne leur donne pas le
droit exclusif d'accommoder les cheveux naturels des hommes,
puisqu'il ne s'explique que sur les ouvrages de cheveux, sujets à
confiscation. Nous ajouterons, que si les Perruquiers sont en
possession de faire l'accommodage des cheveux naturels des
hommes, ce ne peut être qu'en vertu d'un ancien usage, mais qu'ils
ne peuvent invoquer ni l'usage ni la possession, relativement à
l'accommodage des cheveux naturels des femmes.
2o
. Si les Perruquiers avoient par leurs Statuts le droit exclusif de
coëffer les Dames, ils n'auroient certainement pas souffert qu'il
s'établît dans cette Capitale une quantité de Coëffeuses aussi
considérable. Que leur importe donc que les Dames se fassent
coëffer par des femmes ou par des hommes, puisqu'aussi bien ils ne
sont point en possession de les coëffer, & qu'ils n'en auroient pas
même le talent?
3o
. Il est certain que les hommes, dans ce genre, ont le goût
beaucoup plus sûr; car s'il est vrai que dans leur parure les femmes
cherchent à plaire aux hommes, les Artistes de ce sexe, premiers
juges des impressions de leur ouvrage, dirigeront plus efficacement
vers cet objet, les agrémens dont on leur sera redevable.
4o
. Les Maîtres Perruquiers de Marseille sont établis à l'instar des
Maîtres Perruquiers de Paris: les Perruquiers de Marseille voyoient
avec peine en 1760, dans cette ville, une quantité de Coëffeurs à
l'usage des Dames; ils leur ont suscité un Procès; ils ont suivi la
route que leur avoient tracée les Perruquiers de cette Capitale, &
67. obtenu au Parlement d'Aix les mêmes Arrêts que ceux-ci ont obtenus
en la Cour; mais il en est intervenu un définitif le 20 Juin 1761, qui a
rejetté les prétentions des Perruquiers, & assuré aux Coëffeurs des
Dames le plein & entier exercice de leur état.
Il est donc vrai de dire, que les Maîtres Perruquiers ne peuvent se
prévaloir de leurs Statuts, pour porter atteinte à la profession des
Coëffeurs des Dames.
Il nous reste un troisieme objet à remplir, c'est de faire voir l'abus
que les Maîtres Perruquiers ont fait vis-à-vis de nous, de quelques
Arrêts de la Cour; & la nécessité d'assurer la tranquillité & la liberté
des Coëffeurs des Dames par un Jugement irrévocable.
T R O I S I E M E O B J E T.
Plusieurs Garçons Perruquiers, dont le nombre est immense dans
cette Capitale, peuvent s'être mal comportés, ces inconvéniens sont
communs à la plupart des gens qui sont dans la fougue de l'âge; on
s'est occupé du soin de réprimer leur licence. Les Maîtres Perruquiers
ont fait une délibération qu'ils ont fait homologuer par Sentence du
Magistrat de Police, & par Arrêt de la Cour du 12 Décembre 1760; la
Sentence fait défenses à tous Garçons Perruquiers de s'assembler &
s'attrouper; d'entrer chez les Maîtres sans certificat &
enregistrement; de les quitter sans les avoir avertis huit jours
auparavant, & sans avoir fini les ouvrages qu'ils auroient
commencés: il est enjoint aux Garçons venant de Province, de se
faire enregistrer au Bureau de la Communauté dans huitaine du jour
de leur arrivée, le tout sous peine de prison contre les Garçons, &
d'amende contre les Maîtres.
Les précautions prises par cette Sentence, pour empêcher les écarts
des Garçons Perruquiers, sont bien dignes de la sagesse & de la
sagacité du Magistrat, qui dans cette Capitale préside à la Police
avec un applaudissement universel.
68. Le nommé Coursel, Garçon Perruquier & quelques autres, avoient
été arrêtés pour contravention à ce Réglement; ils ont interjetté
appel de la Sentence du Magistrat de Police, & formé opposition à
l'Arrêt qui en ordonnoit l'exécution, & ils en ont été déboutés par un
Arrêt contradictoire du 29 Juillet 1761.
Tout ceci est absolument étranger aux Coëffeurs des Dames;
cependant les Syndics de la Communauté des Perruquiers, jaloux de
leurs succès, ont fait emprisonner plusieurs Coëffeurs, entr'autres le
sieur Barbulé, sur le fondement qu'ils étoient contrevenus à la
Sentence de Police, & aux Arrêts de la Cour, en ne se faisant pas
enregistrer au Bureau de la Communauté.
Nous avons formé une tierce opposition à ces Arrêts, seulement en
ce qu'on en voudroit induire, que leurs dispositions s'étendent contre
nous; mais cette tierce opposition est de pure surabondance; car
nous ne sommes point Garçons Perruquiers, nous possédons un
talent qui n'a rien de commun avec celui de faire des barbes & des
perruques. La plupart d'entre nous ont appris leur Art d'autres
Coëffeurs, & seroient fort embarrassés, s'il falloit qu'ils s'occupassent
de la profession des Perruquiers.
On dira peut-être que quelques Coëffeurs se sont fait enregistrer au
Bureau de la Communauté; la chose est possible, & cette espece de
soumission aura été l'effet de l'inquiétude occasionnée par l'activité
même avec laquelle les Syndics abusoient des Arrêts que nous
venons de citer; mais il ne résultera pas de là, que ces Syndics ayent
eu le droit de nous faire emprisonner, sur le fondement que nous ne
nous serions point fait enregistrer au Bureau de leur Communauté;
car avant de pouvoir être punis comme réfractaires à une Loi, il faut
qu'elle existe: or il n'y avoit ni Loi ni Réglement qui assujettisse les
Coëffeurs des Dames à se faire enregistrer au Bureau de la
Communauté des Perruquiers.
Ces vérités ont été déjà senties dans un provisoire que la Cour a
jugé, & les Magistrats ont en même tems reconnu que les Coëffeurs
des Dames ne devoient point être troublés dans l'exercice de leur Art
69. par les Perruquiers, tant qu'ils ne se mêleroient point de coëffer les
hommes; en conséquence il est intervenu Arrêt sur les conclusions
de M. l'Avocat Général Seguier, qui a ordonné que le sieur Barbulé,
l'un d'entre nous, seroit mis en liberté; a fait par provision défenses
aux Syndics des Perruquiers, d'emprisonner les Coëffeurs de Dames,
en défendant néanmoins à ces derniers de s'immiscer en rien dans
ce qui peut concerner la coëffure des hommes. Il y a tout lieu de
croire, que la Cour statuant en définitif, suivra le plan qu'elle s'est
elle-même tracé par ces dispositions provisoires; & en le suivant, elle
ne manquera pas sans doute de condamner la Communauté des
Maîtres Perruquiers en des dommages & intérêts considérables,
relativement aux vexations que le sieur Barbulé & plusieurs autres
d'entre nous ont essuyé de leur part.
Nous terminerons par cette observation. Nous sommes environ 1200
dans cette Capitale, qui subsistons & faisons subsister nos femmes &
nos enfans par les ressources que nous trouvons dans l'Art que nous
professons. Si l'on nous surprend faisant des barbes, fabriquant des
Perruques, accommodant des hommes, nous aurons tort, les
Perruquiers se plaindront avec raison; mais aussi si nous nous
renfermons dans les bornes de notre état, pourquoi ne nous
conserveroit-on pas notre existence?
Quelques Censeurs séveres diront peut-être qu'on se passeroit bien
de nous, & que s'il y avoit moins de prétentions & d'aprêt dans la
toilette des Dames, les choses n'en iroient que mieux; ce n'est pas à
nous de juger si les mœurs de Sparte étoient préférables à celles
d'Athenes, & si la Bergere qui se mire dans la fontaine & se pare
avec des fleurs, mérite plus d'hommages que de brillantes
Citoyennes qui usent de tous les rafinemens de la parure. Les Arts
utiles ont amené les richesses; les richesses ont produit le luxe; le
luxe a donné naissance aux Arts frivoles: tel est le cours des choses,
parmi toutes les nations; il faut prendre le siecle dans l'état où il est,
puisqu'aussi bien sa réforme subite seroit contre l'ordre des
événemens humains. C'est au ton des mœurs actuelles que nous
70. devons notre existence, & tant qu'elles subsisteront nous devons
subsister avec elles.
Que si le genre de notre défense paroît trop au-dessous de la dignité
de la Justice, c'est un malheur dont nous nous plaignons d'avance;
mais la gravité du style du Barreau étoit-elle propre à présenter des
détails de toilette, & ces détails n'étoient-ils pas nécessaires,
puisqu'ils sont nos moyens?
Une réflexion nous rassure. Le droit de juger les hommes est un
attribut divin; l'Etre éternel juge jusqu'aux moindres actions des
humains: les Magistrats connoissent de toutes les contestations,
même les plus frivoles; la recherche de la vérité, si précieuse par
elle-même, ennoblit toutes les matieres dont ils s'occupent; & de
même que l'astre du jour se leve & luit pour tous les Etres, les
Citoyens de tous les Ordres peuvent, avec le même succès, implorer
les secours de la Justice.
BIGOT DE LA
BOISSIERE, Proc.
71. 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!
ebooknice.com