You are on page 1of 53

Javascript info Ebook Part 1 The

JavaScript language 1st Edition Ilya


Kantor
Visit to download the full and correct content document:
https://textbookfull.com/product/javascript-info-ebook-part-1-the-javascript-language-1
st-edition-ilya-kantor/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Javascript info Ebook Part 3 Additional articles 1st


Edition Ilya Kantor

https://textbookfull.com/product/javascript-info-ebook-
part-3-additional-articles-1st-edition-ilya-kantor/

Javascript info Ebook Part 2 Browser Document Events


Interfaces 1st Edition Ilya Kantor

https://textbookfull.com/product/javascript-info-ebook-
part-2-browser-document-events-interfaces-1st-edition-ilya-
kantor/

JavaScript Learn JavaScript in 24 Hours or Less A


Beginner s Guide To Learning JavaScript Programming Now
JavaScript JavaScript Programming 1st Edition Robert
Dwight.
https://textbookfull.com/product/javascript-learn-javascript-
in-24-hours-or-less-a-beginner-s-guide-to-learning-javascript-
programming-now-javascript-javascript-programming-1st-edition-
robert-dwight/

Functional Programming in JavaScript How to improve


your JavaScript programs using functional techniques 1
edition Edition Luis Atencio

https://textbookfull.com/product/functional-programming-in-
javascript-how-to-improve-your-javascript-programs-using-
functional-techniques-1-edition-edition-luis-atencio/
JavaScript Design Patterns 1 / converted Edition Hugo
Di Francesco

https://textbookfull.com/product/javascript-design-
patterns-1-converted-edition-hugo-di-francesco/

The Joy of JavaScript 1st Edition Atencio

https://textbookfull.com/product/the-joy-of-javascript-1st-
edition-atencio/

Practical Modern JavaScript Dive into ES6 and the


Future of JavaScript Nicolás Bevacqua

https://textbookfull.com/product/practical-modern-javascript-
dive-into-es6-and-the-future-of-javascript-nicolas-bevacqua/

Beginning Functional JavaScript. Functional Programming


with JavaScript using EcmaScript 6 1st Edition Anto
Aravinth

https://textbookfull.com/product/beginning-functional-javascript-
functional-programming-with-javascript-using-ecmascript-6-1st-
edition-anto-aravinth/

Simplifying JavaScript Writing Modern JavaScript with


ES5 ES6 and Beyond 1st Edition Joe Morgan

https://textbookfull.com/product/simplifying-javascript-writing-
modern-javascript-with-es5-es6-and-beyond-1st-edition-joe-morgan/
Part 1

The JavaScript
language

Ilya Kantor
Built at July 10, 2019
The last version of the tutorial is at https://javascript.info.

We constantly work to improve the tutorial. If you find any mistakes, please write at our github.
● An introduction

An Introduction to JavaScript

Manuals and specifications
● Code editors

Developer console
● JavaScript Fundamentals
● Hello, world!
● Code structure

The modern mode, "use strict"
● Variables

Data types
● Type Conversions

Operators
● Comparisons

Interaction: alert, prompt, confirm

Conditional operators: if, '?'

Logical operators

Loops: while and for

The "switch" statement

Functions
● Function expressions and arrows
● JavaScript specials
● Code quality
● Debugging in Chrome
● Coding Style
● Comments

Ninja code
● Automated testing with mocha
● Polyfills

Objects: the basics

Objects
● Garbage collection
● Symbol type

Object methods, "this"
● Object to primitive conversion
● Constructor, operator "new"

Data types
● Methods of primitives
● Numbers
● Strings

Arrays
● Array methods
● Iterables

Map, Set, WeakMap and WeakSet

Object.keys, values, entries
● Destructuring assignment
● Date and time

JSON methods, toJSON
● Advanced working with functions
● Recursion and stack
● Rest parameters and spread operator
● Closure
● The old "var"
● Global object
● Function object, NFE
● The "new Function" syntax
● Scheduling: setTimeout and setInterval

Decorators and forwarding, call/apply
● Function binding
● Currying and partials

Arrow functions revisited
● Object properties configuration
● Property flags and descriptors

Property getters and setters
● Prototypes, inheritance
● Prototypal inheritance
● F.prototype
● Native prototypes
● Prototype methods, objects without __proto__
● Classes
● Class basic syntax
● Class inheritance
● Static properties and methods
● Private and protected properties and methods
● Extending built-in classes

Class checking: "instanceof"
● Mixins
● Error handling

Error handling, "try..catch"
● Custom errors, extending Error
● Promises, async/await
● Introduction: callbacks
● Promise
● Promises chaining
● Error handling with promises
● Promise API
● Promisification
● Microtasks
● Async/await
● Generators, advanced iteration

Generators
● Async iterators and generators
● Modules

Modules, introduction
● Export and Import
● Dynamic imports

Miscellaneous

Proxy and Reflect
● Eval: run a code string
Here we learn JavaScript, starting from scratch and go on to advanced concepts like OOP.
We concentrate on the language itself here, with the minimum of environment-specific notes.

An introduction
About the JavaScript language and the environment to develop with it.

An Introduction to JavaScript
Let’s see what’s so special about JavaScript, what we can achieve with it, and which other
technologies play well with it.

What is JavaScript?

JavaScript was initially created to “make web pages alive”.

The programs in this language are called scripts. They can be written right in a web page’s
HTML and run automatically as the page loads.

Scripts are provided and executed as plain text. They don’t need special preparation or
compilation to run.
In this aspect, JavaScript is very different from another language called Java  .

 Why JavaScript?
When JavaScript was created, it initially had another name: “LiveScript”. But Java was very
popular at that time, so it was decided that positioning a new language as a “younger
brother” of Java would help.

But as it evolved, JavaScript became a fully independent language with its own specification
called ECMAScript  , and now it has no relation to Java at all.

Today, JavaScript can execute not only in the browser, but also on the server, or actually on any
device that has a special program called the JavaScript engine  .

The browser has an embedded engine sometimes called a “JavaScript virtual machine”.

Different engines have different “codenames”. For example:


● V8  – in Chrome and Opera.
● SpiderMonkey  – in Firefox.
● …There are other codenames like “Trident” and “Chakra” for different versions of IE,
“ChakraCore” for Microsoft Edge, “Nitro” and “SquirrelFish” for Safari, etc.

The terms above are good to remember because they are used in developer articles on the
internet. We’ll use them too. For instance, if “a feature X is supported by V8”, then it probably
works in Chrome and Opera.
 How do engines work?
Engines are complicated. But the basics are easy.

1. The engine (embedded if it’s a browser) reads (“parses”) the script.


2. Then it converts (“compiles”) the script to the machine language.
3. And then the machine code runs, pretty fast.

The engine applies optimizations at each step of the process. It even watches the compiled
script as it runs, analyzes the data that flows through it, and applies optimizations to the
machine code based on that knowledge. When it’s done, scripts run quite fast.

What can in-browser JavaScript do?

Modern JavaScript is a “safe” programming language. It does not provide low-level access to
memory or CPU, because it was initially created for browsers which do not require it.

JavaScript’s capabilities greatly depend on the environment it’s running in. For instance,
Node.js  supports functions that allow JavaScript to read/write arbitrary files, perform network
requests, etc.

In-browser JavaScript can do everything related to webpage manipulation, interaction with the
user, and the webserver.

For instance, in-browser JavaScript is able to:


● Add new HTML to the page, change the existing content, modify styles.
● React to user actions, run on mouse clicks, pointer movements, key presses.

Send requests over the network to remote servers, download and upload files (so-called
AJAX  and COMET  technologies).

Get and set cookies, ask questions to the visitor, show messages.

Remember the data on the client-side (“local storage”).

What CAN’T in-browser JavaScript do?

JavaScript’s abilities in the browser are limited for the sake of the user’s safety. The aim is to
prevent an evil webpage from accessing private information or harming the user’s data.
Examples of such restrictions include:
● JavaScript on a webpage may not read/write arbitrary files on the hard disk, copy them or
execute programs. It has no direct access to OS system functions.

Modern browsers allow it to work with files, but the access is limited and only provided if the
user does certain actions, like “dropping” a file into a browser window or selecting it via an
<input> tag.

There are ways to interact with camera/microphone and other devices, but they require a
user’s explicit permission. So a JavaScript-enabled page may not sneakily enable a web-
camera, observe the surroundings and send the information to the NSA  .
● Different tabs/windows generally do not know about each other. Sometimes they do, for
example when one window uses JavaScript to open the other one. But even in this case,
JavaScript from one page may not access the other if they come from different sites (from a
different domain, protocol or port).
This is called the “Same Origin Policy”. To work around that, both pages must agree for data
exchange and contain a special JavaScript code that handles it. We’ll cover that in the
tutorial.
This limitation is, again, for the user’s safety. A page from http://anysite.com which a
user has opened must not be able to access another browser tab with the URL
http://gmail.com and steal information from there.
● JavaScript can easily communicate over the net to the server where the current page came
from. But its ability to receive data from other sites/domains is crippled. Though possible, it
requires explicit agreement (expressed in HTTP headers) from the remote side. Once again,
that’s a safety limitation.

Such limits do not exist if JavaScript is used outside of the browser, for example on a server.
Modern browsers also allow plugin/extensions which may ask for extended permissions.

What makes JavaScript unique?

There are at least three great things about JavaScript:

● Full integration with HTML/CSS.



Simple things are done simply.

Support by all major browsers and enabled by default.
JavaScript is the only browser technology that combines these three things.

That’s what makes JavaScript unique. That’s why it’s the most widespread tool for creating
browser interfaces.

While planning to learn a new technology, it’s beneficial to check its perspectives. So let’s move
on to the modern trends affecting it, including new languages and browser abilities.

Languages “over” JavaScript

The syntax of JavaScript does not suit everyone’s needs. Different people want different
features.

That’s to be expected, because projects and requirements are different for everyone.

So recently a plethora of new languages appeared, which are transpiled (converted) to


JavaScript before they run in the browser.

Modern tools make the transpilation very fast and transparent, actually allowing developers to
code in another language and auto-converting it “under the hood”.

Examples of such languages:


● CoffeeScript  is a “syntactic sugar” for JavaScript. It introduces shorter syntax, allowing us
to write clearer and more precise code. Usually, Ruby devs like it.
● TypeScript  is concentrated on adding “strict data typing” to simplify the development and
support of complex systems. It is developed by Microsoft.

Flow  also adds data typing, but in a different way. Developed by Facebook.

Dart  is a standalone language that has its own engine that runs in non-browser
environments (like mobile apps), but also can be transpiled to JavaScript. Developed by
Google.

There are more. Of course, even if we use one of transpiled languages, we should also know
JavaScript to really understand what we’re doing.

Summary
● JavaScript was initially created as a browser-only language, but is now used in many other
environments as well.

Today, JavaScript has a unique position as the most widely-adopted browser language with
full integration with HTML/CSS.
● There are many languages that get “transpiled” to JavaScript and provide certain features. It
is recommended to take a look at them, at least briefly, after mastering JavaScript.

Manuals and specifications


This book is a tutorial. It aims to help you gradually learn the language. But once you’re familiar
with the basics, you’ll need other sources.

Specification
The ECMA-262 specification contains the most in-depth, detailed and formalized information
about JavaScript. It defines the language.

But being that formalized, it’s difficult to understand at first. So if you need the most trustworthy
source of information about the language details, the specification is the right place. But it’s not
for everyday use.

The latest draft is at https://tc39.es/ecma262/  .

To read about new bleeding-edge features, that are “almost standard”, see proposals at
https://github.com/tc39/proposals  .

Also, if you’re in developing for the browser, then there are other specs covered in the second
part of the tutorial.

Manuals
● MDN (Mozilla) JavaScript Reference is a manual with examples and other information. It’s
great to get in-depth information about individual language functions, methods etc.

One can find it at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference  .

Although, it’s often best to use an internet search instead. Just use “MDN [term]” in the query,
e.g. https://google.com/search?q=MDN+parseInt  to search for parseInt function.

MSDN – Microsoft manual with a lot of information, including JavaScript (often referrerd to as
JScript). If one needs something specific to Internet Explorer, better go there:
http://msdn.microsoft.com/  .

Also, we can use an internet search with phrases such as “RegExp MSDN” or “RegExp
MSDN jscript”.

Feature support

JavaScript is a developing language, new features get added regularly.

To see their support among browser-based and other engines, see:


● http://caniuse.com  – per-feature tables of support, e.g. to see which engines support
modern cryptography functions: http://caniuse.com/#feat=cryptography  .
● https://kangax.github.io/compat-table  – a table with language features and engines that
support those or don’t support.

All these resources are useful in real-life development, as they contain valuable information
about language details, their support etc.

Please remember them (or this page) for the cases when you need in-depth information about a
particular feature.

Code editors
A code editor is the place where programmers spend most of their time.
There are two main types of code editors: IDEs and lightweight editors. Many people use one
tool of each type.

IDE

The term IDE  (Integrated Development Environment) refers to a powerful editor with many
features that usually operates on a “whole project.” As the name suggests, it’s not just an editor,
but a full-scale “development environment.”

An IDE loads the project (which can be many files), allows navigation between files, provides
autocompletion based on the whole project (not just the open file), and integrates with a version
management system (like git  ), a testing environment, and other “project-level” stuff.

If you haven’t selected an IDE yet, consider the following options:


● Visual Studio Code  (cross-platform, free).

WebStorm  (cross-platform, paid).

For Windows, there’s also “Visual Studio”, not to be confused with “Visual Studio Code”. “Visual
Studio” is a paid and mighty Windows-only editor, well-suited for the .NET platform. It’s also
good at JavaScript. There’s also a free version Visual Studio Community  .

Many IDEs are paid, but have a trial period. Their cost is usually negligible compared to a
qualified developer’s salary, so just choose the best one for you.

Lightweight editors

“Lightweight editors” are not as powerful as IDEs, but they’re fast, elegant and simple.

They are mainly used to open and edit a file instantly.

The main difference between a “lightweight editor” and an “IDE” is that an IDE works on a
project-level, so it loads much more data on start, analyzes the project structure if needed and
so on. A lightweight editor is much faster if we need only one file.

In practice, lightweight editors may have a lot of plugins including directory-level syntax
analyzers and autocompleters, so there’s no strict border between a lightweight editor and an
IDE.

The following options deserve your attention:



Atom  (cross-platform, free).

Sublime Text  (cross-platform, shareware).

Notepad++  (Windows, free).

Vim  and Emacs  are also cool if you know how to use them.

Let’s not argue

The editors in the lists above are those that either I or my friends whom I consider good
developers have been using for a long time and are happy with.

There are other great editors in our big world. Please choose the one you like the most.
The choice of an editor, like any other tool, is individual and depends on your projects, habits,
and personal preferences.

Developer console
Code is prone to errors. You will quite likely make errors… Oh, what am I talking about? You are
absolutely going to make errors, at least if you’re a human, not a robot  .

But in the browser, users don’t see errors by default. So, if something goes wrong in the script,
we won’t see what’s broken and can’t fix it.

To see errors and get a lot of other useful information about scripts, “developer tools” have been
embedded in browsers.

Most developers lean towards Chrome or Firefox for development because those browsers
have the best developer tools. Other browsers also provide developer tools, sometimes with
special features, but are usually playing “catch-up” to Chrome or Firefox. So most developers
have a “favorite” browser and switch to others if a problem is browser-specific.

Developer tools are potent; they have many features. To start, we’ll learn how to open them,
look at errors, and run JavaScript commands.

Google Chrome

Open the page bug.html.

There’s an error in the JavaScript code on it. It’s hidden from a regular visitor’s eyes, so let’s
open developer tools to see it.
Press F12 or, if you’re on Mac, then Cmd+Opt+J .

The developer tools will open on the Console tab by default.

It looks somewhat like this:

The exact look of developer tools depends on your version of Chrome. It changes from time to
time but should be similar.

Here we can see the red-colored error message. In this case, the script contains an unknown
“lalala” command.

On the right, there is a clickable link to the source bug.html:12 with the line number
where the error has occurred.
Below the error message, there is a blue > symbol. It marks a “command line” where we can
type JavaScript commands. Press Enter to run them ( Shift+Enter to input multi-line
commands).

Now we can see errors, and that’s enough for a start. We’ll come back to developer tools later
and cover debugging more in-depth in the chapter Debugging in Chrome.

Firefox, Edge, and others

Most other browsers use F12 to open developer tools.

The look & feel of them is quite similar. Once you know how to use one of these tools (you can
start with Chrome), you can easily switch to another.

Safari

Safari (Mac browser, not supported by Windows/Linux) is a little bit special here. We need to
enable the “Develop menu” first.

Open Preferences and go to the “Advanced” pane. There’s a checkbox at the bottom:

Now Cmd+Opt+C can toggle the console. Also, note that the new top menu item named
“Develop” has appeared. It has many commands and options.

Multi-line input

Usually, when we put a line of code into the console, and then press Enter , it executes.

To insert multiple lines, press Shift+Enter .

Summary

Developer tools allow us to see errors, run commands, examine variables, and much more.
● They can be opened with F12 for most browsers on Windows. Chrome for Mac needs
Cmd+Opt+J , Safari: Cmd+Opt+C (need to enable first).

Now we have the environment ready. In the next section, we’ll get down to JavaScript.

JavaScript Fundamentals
Let’s learn the fundamentals of script building.

Hello, world!
This part of the tutorial is about core JavaScript, the language itself. Later on, you’ll learn about
Node.js and other platforms that use it.

But we need a working environment to run our scripts and, since this book is online, the
browser is a good choice. We’ll keep the amount of browser-specific commands (like alert )
to a minimum so that you don’t spend time on them if you plan to concentrate on another
environment (like Node.js). We’ll focus on JavaScript in the browser in the next part of the
tutorial.
So first, let’s see how we attach a script to a webpage. For server-side environments (like
Node.js), you can execute the script with a command like "node my.js" .

The “script” tag

JavaScript programs can be inserted into any part of an HTML document with the help of the
<script> tag.

For instance:

<!DOCTYPE HTML>
<html>

<body>

<p>Before the script...</p>

<script>
alert( 'Hello, world!' );
</script>

<p>...After the script.</p>

</body>

</html>

The <script> tag contains JavaScript code which is automatically executed when the
browser processes the tag.

Modern markup
The <script> tag has a few attributes that are rarely used nowadays but can still be found in
old code:

The type attribute: <script type=…>


The old HTML standard, HTML4, required a script to have a type . Usually it was
type="text/javascript" . It’s not required anymore. Also, the modern HTML standard,
HTML5, totally changed the meaning of this attribute. Now, it can be used for JavaScript
modules. But that’s an advanced topic; we’ll talk about modules in another part of the tutorial.

The language attribute: <script language=…>


This attribute was meant to show the language of the script. This attribute no longer makes
sense because JavaScript is the default language. There is no need to use it.

Comments before and after scripts.


In really ancient books and guides, you may find comments inside <script> tags, like this:

<script type="text/javascript"><!--
...
//--></script>

This trick isn’t used in modern JavaScript. These comments hid JavaScript code from old
browsers that didn’t know how to process the <script> tag. Since browsers released in the
last 15 years don’t have this issue, this kind of comment can help you identify really old code.

External scripts

If we have a lot of JavaScript code, we can put it into a separate file.

Script files are attached to HTML with the src attribute:

<script src="/path/to/script.js"></script>

Here, /path/to/script.js is an absolute path to the script file (from the site root).

You can also provide a relative path from the current page. For instance, src="script.js"
would mean a file "script.js" in the current folder.

We can give a full URL as well. For instance:

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.2.0/lodash.js"></script>

To attach several scripts, use multiple tags:

<script src="/js/script1.js"></script>
<script src="/js/script2.js"></script>

 Please note:
As a rule, only the simplest scripts are put into HTML. More complex ones reside in
separate files.
The benefit of a separate file is that the browser will download it and store it in its cache  .

Other pages that reference the same script will take it from the cache instead of
downloading it, so the file is actually downloaded only once.
That reduces traffic and makes pages faster.

⚠ If src is set, the script content is ignored.

A single <script> tag can’t have both the src attribute and code inside.

This won’t work:

<script src="file.js">
alert(1); // the content is ignored, because src is set
</script>

We must choose either an external <script src="…"> or a regular <script> with


code.

The example above can be split into two scripts to work:

<script src="file.js"></script>
<script>
alert(1);
</script>

Summary
● We can use a <script> tag to add JavaScript code to a page.
● The type and language attributes are not required.

A script in an external file can be inserted with <script src="path/to/script.js">
</script> .

There is much more to learn about browser scripts and their interaction with the webpage. But
let’s keep in mind that this part of the tutorial is devoted to the JavaScript language, so we
shouldn’t distract ourselves with browser-specific implementations of it. We’ll be using the
browser as a way to run JavaScript, which is very convenient for online reading, but only one of
many.

✔ Tasks

Show an alert
importance: 5

Create a page that shows a message “I’m JavaScript!”.

Do it in a sandbox, or on your hard drive, doesn’t matter, just ensure that it works.

Demo in new window 

To solution

Show an alert with an external script


importance: 5

Take the solution of the previous task Show an alert. Modify it by extracting the script content
into an external file alert.js , residing in the same folder.

Open the page, ensure that the alert works.

To solution

Code structure
The first thing we’ll study is the building blocks of code.

Statements

Statements are syntax constructs and commands that perform actions.


We’ve already seen a statement, alert('Hello, world!') , which shows the message
“Hello, world!”.

We can have as many statements in our code as we want. Statements can be separated with a
semicolon.

For example, here we split “Hello World” into two alerts:

alert('Hello'); alert('World');

Usually, statements are written on separate lines to make the code more readable:

alert('Hello');
alert('World');

Semicolons

A semicolon may be omitted in most cases when a line break exists.

This would also work:


alert('Hello')
alert('World')

Here, JavaScript interprets the line break as an “implicit” semicolon. This is called an automatic
semicolon insertion  .

In most cases, a newline implies a semicolon. But “in most cases” does not mean
“always”!
There are cases when a newline does not mean a semicolon. For example:

alert(3 +
1
+ 2);

The code outputs 6 because JavaScript does not insert semicolons here. It is intuitively
obvious that if the line ends with a plus "+" , then it is an “incomplete expression”, so the
semicolon is not required. And in this case that works as intended.
But there are situations where JavaScript “fails” to assume a semicolon where it is really
needed.
Errors which occur in such cases are quite hard to find and fix.
 An example of an error
If you’re curious to see a concrete example of such an error, check this code out:

[1, 2].forEach(alert)

No need to think about the meaning of the brackets [] and forEach yet. We’ll study
them later. For now, just remember the result of the code: it shows 1 then 2 .

Now, let’s add an alert before the code and not finish it with a semicolon:

alert("There will be an error")

[1, 2].forEach(alert)

Now if we run the code, only the first alert is shown and then we have an error!

But everything is fine again if we add a semicolon after alert :

alert("All fine now");

[1, 2].forEach(alert)

Now we have the “All fine now” message followed by 1 and 2 .

The error in the no-semicolon variant occurs because JavaScript does not assume a
semicolon before square brackets [...] .

So, because the semicolon is not auto-inserted, the code in the first example is treated as a
single statement. Here’s how the engine sees it:

alert("There will be an error")[1, 2].forEach(alert)

But it should be two separate statements, not one. Such a merging in this case is just
wrong, hence the error. This can happen in other situations.

We recommend putting semicolons between statements even if they are separated by


newlines. This rule is widely adopted by the community. Let’s note once again – it is possible to
leave out semicolons most of the time. But it’s safer – especially for a beginner – to use them.

Comments

As time goes on, programs become more and more complex. It becomes necessary to add
comments which describe what the code does and why.
Comments can be put into any place of a script. They don’t affect its execution because the
engine simply ignores them.
One-line comments start with two forward slash characters // .

The rest of the line is a comment. It may occupy a full line of its own or follow a statement.
Like here:

// This comment occupies a line of its own


alert('Hello');

alert('World'); // This comment follows the statement

Multiline comments start with a forward slash and an asterisk /* and end with an
asterisk and a forward slash */ .

Like this:

/* An example with two messages.


This is a multiline comment.
*/
alert('Hello');
alert('World');

The content of comments is ignored, so if we put code inside /* … */ , it won’t execute.

Sometimes it can be handy to temporarily disable a part of code:

/* Commenting out the code


alert('Hello');
*/
alert('World');

 Use hotkeys!
In most editors, a line of code can be commented out by pressing the Ctrl+/ hotkey for a
single-line comment and something like Ctrl+Shift+/ – for multiline comments (select a
piece of code and press the hotkey). For Mac, try Cmd instead of Ctrl .

⚠ Nested comments are not supported!


There may not be /*...*/ inside another /*...*/ .

Such code will die with an error:

/*
/* nested comment ?!? */
*/
alert( 'World' );
Please, don’t hesitate to comment your code.
Comments increase the overall code footprint, but that’s not a problem at all. There are many
tools which minify code before publishing to a production server. They remove comments, so
they don’t appear in the working scripts. Therefore, comments do not have negative effects on
production at all.
Later in the tutorial there will be a chapter Code quality that also explains how to write better
comments.

The modern mode, "use strict"


For a long time, JavaScript evolved without compatibility issues. New features were added to
the language while old functionality didn’t change.
That had the benefit of never breaking existing code. But the downside was that any mistake or
an imperfect decision made by JavaScript’s creators got stuck in the language forever.
This was the case until 2009 when ECMAScript 5 (ES5) appeared. It added new features to the
language and modified some of the existing ones. To keep the old code working, most
modifications are off by default. You need to explicitly enable them with a special directive:
"use strict" .

“use strict”

The directive looks like a string: "use strict" or 'use strict' . When it is located at
the top of a script, the whole script works the “modern” way.

For example:

"use strict";

// this code works the modern way


...

We will learn functions (a way to group commands) soon.

Looking ahead, let’s just note that "use strict" can be put at the start of most kinds of
functions instead of the whole script. Doing that enables strict mode in that function only. But
usually, people use it for the whole script.
⚠ Ensure that “use strict” is at the top
Please make sure that "use strict" is at the top of your scripts, otherwise strict mode
may not be enabled.

Strict mode isn’t enabled here:

alert("some code");
// "use strict" below is ignored--it must be at the top

"use strict";

// strict mode is not activated

Only comments may appear above "use strict" .

⚠ There’s no way to cancel use strict


There is no directive like "no use strict" that reverts the engine to old behavior.

Once we enter strict mode, there’s no return.

Browser console

For the future, when you use a browser console to test features, please note that it doesn’t use
strict by default.

Sometimes, when use strict makes a difference, you’ll get incorrect results.

You can try to press Shift+Enter to input multiple lines, and put use strict on top, like
this:

'use strict'; <Shift+Enter for a newline>


// ...your code
<Enter to run>

It works in most browsers, namely Firefox and Chrome.

If it doesn’t, the most reliable way to ensure use strict would be to input the code into
console like this:

(function() {
'use strict';

// ...your code...
})()

Always “use strict”


We have yet to cover the differences between strict mode and the “default” mode.
In the next chapters, as we learn language features, we’ll note the differences between the strict
and default modes. Luckily, there aren’t many and they actually make our lives better.
For now, it’s enough to know about it in general:

1. The "use strict" directive switches the engine to the “modern” mode, changing the
behavior of some built-in features. We’ll see the details later in the tutorial.
2. Strict mode is enabled by placing "use strict" at the top of a script or function. Several
language features, like “classes” and “modules”, enable strict mode automatically.
3. Strict mode is supported by all modern browsers.
4. We recommended always starting scripts with "use strict" . All examples in this tutorial
assume strict mode unless (very rarely) specified otherwise.

Variables
Most of the time, a JavaScript application needs to work with information. Here are two
examples:
1. An online shop – the information might include goods being sold and a shopping cart.
2. A chat application – the information might include users, messages, and much more.

Variables are used to store this information.

A variable

A variable  is a “named storage” for data. We can use variables to store goodies, visitors, and
other data.

To create a variable in JavaScript, use the let keyword.

The statement below creates (in other words: declares or defines) a variable with the name
“message”:

let message;

Now, we can put some data into it by using the assignment operator = :

let message;

message = 'Hello'; // store the string

The string is now saved into the memory area associated with the variable. We can access it
using the variable name:

let message;
message = 'Hello!';
alert(message); // shows the variable content

To be concise, we can combine the variable declaration and assignment into a single line:

let message = 'Hello!'; // define the variable and assign the value

alert(message); // Hello!

We can also declare multiple variables in one line:

let user = 'John', age = 25, message = 'Hello';

That might seem shorter, but we don’t recommend it. For the sake of better readability, please
use a single line per variable.

The multiline variant is a bit longer, but easier to read:

let user = 'John';


let age = 25;
let message = 'Hello';

Some people also define multiple variables in this multiline style:

let user = 'John',


age = 25,
message = 'Hello';

…Or even in the “comma-first” style:

let user = 'John'


, age = 25
, message = 'Hello';

Technically, all these variants do the same thing. So, it’s a matter of personal taste and
aesthetics.
 var instead of let
In older scripts, you may also find another keyword: var instead of let :

var message = 'Hello';

The var keyword is almost the same as let . It also declares a variable, but in a slightly
different, “old-school” way.

There are subtle differences between let and var , but they do not matter for us yet.
We’ll cover them in detail in the chapter The old "var".

A real-life analogy

We can easily grasp the concept of a “variable” if we imagine it as a “box” for data, with a
uniquely-named sticker on it.

For instance, the variable message can be imagined as a box labeled "message" with the
value "Hello!" in it:

We can put any value in the box.


We can also change it as many times as we want:

let message;

message = 'Hello!';

message = 'World!'; // value changed

alert(message);

When the value is changed, the old data is removed from the variable:

We can also declare two variables and copy data from one into the other.
let hello = 'Hello world!';

let message;

// copy 'Hello world' from hello into message


message = hello;

// now two variables hold the same data


alert(hello); // Hello world!
alert(message); // Hello world!

 Functional languages
It’s interesting to note that there exist functional  programming languages, like Scala 
or Erlang  that forbid changing variable values.

In such languages, once the value is stored “in the box”, it’s there forever. If we need to
store something else, the language forces us to create a new box (declare a new variable).
We can’t reuse the old one.
Though it may seem a little odd at first sight, these languages are quite capable of serious
development. More than that, there are areas like parallel computations where this limitation
confers certain benefits. Studying such a language (even if you’re not planning to use it
soon) is recommended to broaden the mind.

Variable naming

There are two limitations on variable names in JavaScript:

1. The name must contain only letters, digits, or the symbols $ and _ .
2. The first character must not be a digit.

Examples of valid names:

let userName;
let test123;

When the name contains multiple words, camelCase  is commonly used. That is: words go
one after another, each word except first starting with a capital letter: myVeryLongName .

What’s interesting – the dollar sign '$' and the underscore '_' can also be used in names.
They are regular symbols, just like letters, without any special meaning.

These names are valid:

let $ = 1; // declared a variable with the name "$"


let _ = 2; // and now a variable with the name "_"

alert($ + _); // 3
Examples of incorrect variable names:

let 1a; // cannot start with a digit

let my-name; // hyphens '-' aren't allowed in the name

 Case matters
Variables named apple and AppLE are two different variables.

 Non-Latin letters are allowed, but not recommended


It is possible to use any language, including cyrillic letters or even hieroglyphs, like this:

let имя = '...';


let 我 = '...';

Technically, there is no error here, such names are allowed, but there is an international
tradition to use English in variable names. Even if we’re writing a small script, it may have a
long life ahead. People from other countries may need to read it some time.

⚠ Reserved names
There is a list of reserved words  , which cannot be used as variable names because they
are used by the language itself.

For example: let , class , return , and function are reserved.

The code below gives a syntax error:

let let = 5; // can't name a variable "let", error!


let return = 5; // also can't name it "return", error!
⚠ An assignment without use strict
Normally, we need to define a variable before using it. But in the old times, it was technically
possible to create a variable by a mere assignment of the value without using let . This
still works now if we don’t put use strict in our scripts to maintain compatibility with old
scripts.

// note: no "use strict" in this example

num = 5; // the variable "num" is created if it didn't exist

alert(num); // 5

This is a bad practice and would cause an error in strict mode:

"use strict";

num = 5; // error: num is not defined

Constants

To declare a constant (unchanging) variable, use const instead of let :

const myBirthday = '18.04.1982';

Variables declared using const are called “constants”. They cannot be changed. An attempt
to do so would cause an error:

const myBirthday = '18.04.1982';

myBirthday = '01.01.2001'; // error, can't reassign the constant!

When a programmer is sure that a variable will never change, they can declare it with const
to guarantee and clearly communicate that fact to everyone.

Uppercase constants
There is a widespread practice to use constants as aliases for difficult-to-remember values that
are known prior to execution.

Such constants are named using capital letters and underscores.

For instance, let’s make constants for colors in so-called “web” (hexadecimal) format:

const COLOR_RED = "#F00";


const COLOR_GREEN = "#0F0";
const COLOR_BLUE = "#00F";
const COLOR_ORANGE = "#FF7F00";

// ...when we need to pick a color


let color = COLOR_ORANGE;
alert(color); // #FF7F00

Benefits:

COLOR_ORANGE is much easier to remember than "#FF7F00" .
● It is much easier to mistype "#FF7F00" than COLOR_ORANGE .

When reading the code, COLOR_ORANGE is much more meaningful than #FF7F00 .

When should we use capitals for a constant and when should we name it normally? Let’s make
that clear.
Being a “constant” just means that a variable’s value never changes. But there are constants
that are known prior to execution (like a hexadecimal value for red) and there are constants that
are calculated in run-time, during the execution, but do not change after their initial assignment.

For instance:

const pageLoadTime = /* time taken by a webpage to load */;

The value of pageLoadTime is not known prior to the page load, so it’s named normally. But
it’s still a constant because it doesn’t change after assignment.

In other words, capital-named constants are only used as aliases for “hard-coded” values.

Name things right

Talking about variables, there’s one more extremely important thing.


A variable name should have a clean, obvious meaning, describe the data that it stores.

Variable naming is one of the most important and complex skills in programming. A quick
glance at variable names can reveal which code was written by a beginner versus an
experienced developer.
In a real project, most of the time is spent modifying and extending an existing code base rather
than writing something completely separate from scratch. When we return to some code after
doing something else for a while, it’s much easier to find information that is well-labeled. Or, in
other words, when the variables have good names.

Please spend time thinking about the right name for a variable before declaring it. Doing so will
repay you handsomely.

Some good-to-follow rules are:



Use human-readable names like userName or shoppingCart .

Stay away from abbreviations or short names like a , b , c , unless you really know what
you’re doing.
● Make names maximally descriptive and concise. Examples of bad names are data and
value . Such names say nothing. It’s only okay to use them if the context of the code makes
it exceptionally obvious which data or value the variable is referencing.
● Agree on terms within your team and in your own mind. If a site visitor is called a “user” then
we should name related variables currentUser or newUser instead of
currentVisitor or newManInTown .

Sounds simple? Indeed it is, but creating descriptive and concise variable names in practice is
not. Go for it.

 Reuse or create?
And the last note. There are some lazy programmers who, instead of declaring new
variables, tend to reuse existing ones.

As a result, their variables are like boxes into which people throw different things without
changing their stickers. What’s inside the box now? Who knows? We need to come closer
and check.
Such programmers save a little bit on variable declaration but lose ten times more on
debugging.

An extra variable is good, not evil.

Modern JavaScript minifiers and browsers optimize code well enough, so it won’t create
performance issues. Using different variables for different values can even help the engine
optimize your code.

Summary

We can declare variables to store data by using the var , let , or const keywords.
● let – is a modern variable declaration. The code must be in strict mode to use let in
Chrome (V8).
● var – is an old-school variable declaration. Normally we don’t use it at all, but we’ll cover
subtle differences from let in the chapter The old "var", just in case you need them.

const – is like let , but the value of the variable can’t be changed.

Variables should be named in a way that allows us to easily understand what’s inside them.

✔ Tasks

Working with variables


importance: 2

1. Declare two variables: admin and name .


2. Assign the value "John" to name .
3. Copy the value from name to admin .
4. Show the value of admin using alert (must output “John”).
Another random document with
no related content on Scribd:
Mais, cela même, il se le dit assez vaguement, pour ne pas
s’effrayer. Il avait coutume, quand il s’agissait de prendre une grande
résolution, de se boucher un des yeux, comme on fait à un cheval de
picador.
Le jour du départ venu, il s’appliqua, pour ne pas donner l’éveil à
son père et à sa mère, à ne pas les embrasser avec trop d’effusions.
Il avait projeté de se rendre d’abord à Saint-Jacut de la mer,
entre Saint-Lunaire et Saint-Cast, non loin de Dinard. C’est là qu’un
de ses cousins, le peintre Isidore Gormas, l’artiste de la famille, avait
une résidence d’été.
Certainement, Isidore était un homme d’esprit libre… Aux yeux
des Nordement et de la plupart des Gormas, il passait pour un
garçon excentrique, qui ne faisait jamais rien comme tout le monde.
Quand il venait dîner en famille, il parlait aux parents de Robert
sur un ton de continuelle ironie.
Le jeune homme comptait bien sur cet être indépendant, en
marge de la société, pour se fortifier dans son rude dessein.
Il arriva chez le peintre à midi, par la diligence qui faisait le
service du Guildo, la petite station de chemin de fer qui desservait
Saint-Jacut. Isidore n’était pas chez lui. Mais il était prévenu de la
visite de Robert. Le jeune homme fut reçu par Julie, la concubine de
son cousin. Julie était un ancien modèle très déformé, et qui n’avait
plus à offrir qu’un morceau de cuisse présentable aux appétits d’art
de son compagnon : depuis plusieurs années, d’ailleurs, il se
spécialisait dans les marines.
Julie, après s’être fait connaître de Robert, lui servit du pain et du
fromage…
— Quand il part sur la grève, on ne sait jamais quand il lui plaira
de rentrer déjeuner…
Cette irrégularité dans les heures de repas, si différente des
habitudes réglées de la famille, parut à Robert un excellent indice de
l’indépendance d’idées de son cousin, et pour lui-même un bon
prélude à sa vie de grandes aventures.
Ce jour-là, Isidore ne s’attarda pas trop. Vers deux heures, il
s’encadra, avec un temps d’arrêt peut-être voulu, sur le seuil de la
maison rustique.
C’était un quinquagénaire trapu, à la barbe soigneusement
inculte, et le seul homme de cette localité campagnarde qui fût
encore habillé en paysan.
On mangea de l’omelette au lard et de petites côtelettes
carbonisées, le tout arrosé d’un liquide pâle, que le peintre
proclamait « du vrai cidre ». Il se faisait servir par Julie, qu’il appelait
« femme de l’Écriture », ce qui sembla fort pittoresque à Robert, au
moins les trois ou quatre premières fois.
Après le déjeuner, le fils Nordement déclina l’offre de prêt,
pourtant bien cordiale, d’une bonne vieille pipe usagée. Il préféra
aller chercher des cigarettes dans sa valise. Puis Isidore l’emmena à
travers ce village maritime, dont il se considérait visiblement comme
le maître, à sa façon large de marcher, d’interpeller les habitants, et
de projeter à droite et à gauche des crachats de pipe, à des
distances considérables.
Le moment était venu pour Robert de raconter toute l’histoire, ce
projet bourgeois et monstrueux de l’unir à Mlle Ourson.
Mais l’indignation révoltée du peintre ne se manifestait pas.
Il posa à son cousin mille questions sur la fortune des parents de
la jeune Irma.
— D’ailleurs, ajouta-t-il, ton père a certainement pris des
renseignements. Le père Nordement ne s’embarque pas sans
biscuit. Je ne t’apprendrai rien en te disant que c’est un homme des
plus forts que je connaisse. Quant à la maman, c’est une femme de
tête et qui sait bien ce qu’elle veut. Chaque fois que j’ai une petite
affaire en vue, un placement de fonds, quelque bout de terrain à
vendre dans mon pays là-bas, je suis allé demander des conseils à
ton père, et je les ai toujours suivis aveuglément.
Robert parla de la fadeur incurable de Mlle Ourson.
— Oh ! elle se fera, dit Isidore… Une personne jeune, avec tout
ce qu’il faut pour s’acheter de jolies toilettes…
Robert était un peu chancelant dans sa rébellion. Mais Isidore
diminua l’autorité de sa parole, en se proposant trop vite pour la
décoration d’une splendide villa, que Robert ne manquerait pas
d’édifier, aussitôt son mariage accompli.
— Le terrain est là, dit-il, à trois quarts de lieue sur la côte. On
peindrait sur les murs intérieurs des paysages marins…
Tandis qu’il décrivait, avec d’amples gestes, cette magnifique
demeure, Robert se demandait s’il lui serait possible de quitter, le
soir même, Saint-Jacut, Isidore et Julie. L’omelette au lard ne lui
avait pas paru d’une fraîcheur absolue, et le vrai cidre commençait à
lui donner d’authentiques crampes d’estomac.
Il pensait que la soirée serait insoutenable entre l’ancien modèle
et ce peintre, si superficiellement indépendant.
Alors il inventa une histoire de rendez-vous à Dinard. Il irait, dit-il
à Isidore, passer un jour ou deux là-bas, puis reviendrait ensuite à
Saint-Jacut, où il pourrait séjourner quelque temps.
Le peintre, heureusement, n’était pas homme à se cramponner à
un invité. Peut-être n’était-il pas maître chez lui autant qu’il en
donnait l’impression, et qui sait si la chute du jour ne voyait pas la
« femme de l’Écriture » se départir de son attitude de soumission
biblique ? Toujours est-il qu’Isidore s’occupa avec une vigilance
extraordinaire de trouver un tacot qui pût transporter, séance
tenante, le jeune homme à Dinard. Il semblait subitement considérer
le rendez-vous allégué par Robert comme une obligation
sentimentale quasi sacrée, dont personne n’avait le droit de gêner
l’accomplissement. Quant au principe consolateur du retour à Saint-
Jacut, il fut sauvegardé au moment du départ par un « A bientôt… Je
compte sur toi » tout à fait vague.
Robert, sur son auto de louage, partit donc dans le crépuscule
vers l’inconnu. A la nuit, il arriva à Dinard. La saison s’avançait, et la
ville commençait à se dépeupler. Robert trouva facilement une
chambre dans l’hôtel le plus en vue. Il dîna hâtivement au
restaurant, puis endossa son smoking. Il se rendit au Casino. Il
n’avait, pour ainsi dire, jamais joué au baccara. Mais l’idée lui était
venue tout à coup d’y risquer trois ou quatre cents francs, afin de
ramasser une petite fortune, qui lui donnerait plus de solidité pour
tenir son rôle d’enfant prodigue.
Il gagna cent francs, puis deux cents francs qu’il reperdit, et il
quitta le Casino vers minuit, ayant perdu trois fois la somme qu’il
s’était assignée comme rigoureuse limite. Il eut assez de force
d’âme ou de manque d’estomac pour garder les quinze louis qui lui
restaient sur l’allocation du voyage.
Décidément, le Destin voulait faciliter la séparation de Robert et
de sa famille. Car il était radicalement impossible d’annoncer cette
première mésaventure à M. Nordement, l’homme le plus austère du
monde sur la question des jeux de hasard.
Il restait à Robert de quoi se défrayer à l’hôtel pendant trois ou
quatre jours.
Sa vie difficile commençait.
Son âme fut partagée par parties inégales entre un âpre orgueil
et une assez vive appréhension.
Il était rentré dans sa chambre.
Longtemps il demeura accoudé à sa fenêtre, comme Rolla, le
héros romantique, dans la gravure qui illustre le poème de Musset.
Il se sentait plein d’un grand courage, qu’il ne savait à quoi
employer.
Le temps était passé où les enfants prodigues, exilés du foyer
paternel, n’avaient qu’un tour à faire dans la campagne pour trouver
une place de gardeur de pourceaux.
Pour se présenter dans une ferme, il eût fallu se procurer une
mise spéciale et remplacer ces vêtements de fils de famille par des
effets de toile, de préférence un peu usagés.
Il était trop grand pour se proposer comme mousse dans un
navire en partance. On aurait peut-être pu l’engager comme
steward, pour servir les passagers. Mais c’était encore un emploi
auquel il se sentait mal préparé. Et, par surcroît, il avait grand’peur
du mal de mer.
Se placer comme chauffeur ? Il savait conduire une auto, c’est-à-
dire qu’il avait passé son brevet. Mais il ignorait tout du mécanisme
des voitures. Les mots de « bougie », de « magnéto » l’effrayaient
comme des noms de maladie. Il ne voulait pas s’exposer, en pleine
route déserte, à avouer brusquement son incompétence à des
patrons suffoqués.
La nuit précédente s’était passée en chemin de fer. Le grand air
de la promenade en auto, la séance du casino l’avaient un peu
aplati. Il se jeta sur son lit et remit au lendemain la recherche d’une
position sociale.
IV

Or, une affiche manuscrite était apposée depuis huit jours dans le
hall de l’hôtel. Elle demandait un professeur de français pour être
attaché à une famille aisée.
C’était le seul emploi que Robert fût capable de remplir ; c’était le
seul auquel il n’eût pas songé.
Il aperçut la pancarte le lendemain matin, en descendant pour
son petit déjeuner, qu’il avait décidé de prendre, non à l’hôtel, mais
dans un petit café du pays ; car il fallait ménager ses ressources.
On demande un professeur de français pour famille aisée.
S’adresser au portier de l’hôtel.
Il fallut à Robert un certain effort pour surmonter sa gêne et pour
demander au portier quelle était la famille aisée en question. C’était
abdiquer un peu la dignité de voyageur indépendant et fastueux.
La nationalité exacte de M. et Mme Orega échappait à l’historien,
comme le lieu de naissance du divin Homère. Seul, un diagnostic un
peu aventuré d’ethnographe parvenait à situer approximativement
leur origine dans les régions équatoriales du nouveau continent.
De même, les âges plausibles de ce petit homme rasé
s’échelonnaient sur un long espace, entre trente et cinquante ans.
M. Orega connaissait un certain nombre de phrases françaises
qu’il débitait sans trop d’accent, en vous faisant brusquement la
surprise d’une faute invraisemblable, comme de dire : un table, ou :
une chapeau.
Mme Orega était une sorte de Fatma de deuxième fraîcheur, à qui
son apathie conférait une sorte de majesté. Elle ne semblait plus
très ferme, comme si, au cours de son existence, elle eût été
plusieurs fois gonflée et dégonflée.
« Le Paradis sur terre, a dit à peu près Victor Hugo, ce serait les
parents toujours jeunes, et les enfants toujours petits. » La jeunesse
des parents Orega était compromise, mais leur fils unique Esteban,
qui n’avait que quatorze ans, était resté petit et puéril comme un tout
jeune garçon.
C’était d’ailleurs un être charmant, à la fois attardé et précoce.
Tantôt, secouant ses cheveux bouclés, il avait des colères
enfantines. Et d’autres fois, il étonnait Robert par sa gravité mûrie,
par son langage éclatant d’images imprévues. Il semblait que la
nature ne l’eût laissé si petit que pour lui garder plus longtemps un
aspect d’enfant sublime.
Robert, qui avait été ébloui dès leur premier entretien, fut
stupéfait de voir qu’Esteban, la plume à la main, formait
grossièrement ses lettres, et qu’il avait une orthographe de cuisinière
peau-rouge.
Dès la présentation, c’est-à-dire le lendemain de son arrivée à
Dinard, il avait été agréé comme précepteur. Il prit tout de suite ses
repas à la table des Orega, non dans la salle du restaurant, mais
dans un petit salon à part. Il n’en fut pas fâché, car il pouvait
rencontrer à Dinard des personnes de connaissance, qui risquaient
ainsi d’être mises au courant de son nouvel emploi.
Les Orega, d’ailleurs, avaient des raisons à eux pour ne pas se
faire servir en public. Robert s’aperçut, dès la première minute, que
le repas de famille n’était qu’une occasion de disputes furieuses
entre M. et Mme Orega.
Il comprenait mal l’espagnol ; mais, si l’objet même de la
discussion lui échappait, il pouvait suivre du moins toutes les phases
de la lutte sur le visage étincelant des matcheurs. Parfois, c’était une
sèche imputation de son mari qui marquait le visage fatigué de la
belle Fatma d’une douleur extra-humaine. D’autres fois, sur une
réplique de la compagne de sa vie, on voyait M. Orega tout près de
défaillir, et le bronze de son visage passer du rouge marron à un
vert-de-gris superbe.
Robert avait été engagé sans discussion à mille francs par mois,
logé et nourri. Il avait demandé ce prix sur les indications du gérant.
Et, comme M. Orega « n’avait pas pipé », il considéra d’abord son
patron comme un homme fort généreux. Mais il ne fut pas long à
s’apercevoir que cette apparente largesse était faite d’une timidité
d’étranger, ignorant des usages. Dès que M. Orega était renseigné
sur le prix d’un objet, il discutait férocement pour soixante-quinze
centimes. Il payait à l’hôtel six à sept cents francs par jour pour lui et
sa suite, et quand le jeune Esteban demandait un peu d’argent de
poche, papa se faisait prier pour sortir un billet de quarante sous.
Robert était depuis trois jours au service de la famille Orega. Il
avait déjà écrit deux mots à ses parents. Il leur écrirait jusqu’à
nouvel ordre de courtes lettres, où il leur dirait simplement, comme
chaque fois d’ailleurs qu’il s’absentait, que sa santé était bonne. Et il
terminait en leur envoyant mille baisers, pas un de plus, pas un de
moins. Ces communications, rédigées de cette façon uniforme,
succinctes comme un chèque d’affection, il les leur enverrait jusqu’à
nouvel ordre. Car il n’était encore un enfant prodigue que pour lui-
même, et se rupture avec sa famille n’était consommée qu’en son
for intérieur.
Son état d’âme était au fond plus que satisfaisant. Il était installé
d’une façon confortable, mangeait bien, et ses fonctions ne lui
déplaisaient pas ; il commençait à s’attacher à ce petit Esteban, en
qui il retrouvait l’ardeur généreuse de son pauvre ami Francis
Picard, et il avait cette fois cette satisfaction supplémentaire d’être
l’aîné, l’éducateur d’âme. La grâce native de son élève lui donnait du
goût pour ce métier de directeur d’esprit, et il s’enorgueillissait à
l’idée de développer, d’épanouir les qualités certaines de ce jeune
aiglon de la famille Orega.
Le troisième jour de son entrée en fonctions, Robert avait
déjeuné, comme à son ordinaire, avec ses patrons et son élève. Le
choc avait été particulièrement rude entre les époux. Ils étaient
arrivés à table l’un et l’autre dans une parfaite condition de combat.
Comme des boulets et des pots d’huile bouillante, des griefs
réciproques, remontant à plus de vingt années, s’étaient croisés
sans répit par-dessus les plats… Vers le dessert, les lutteurs
reprenaient haleine, mais on sentait que l’empoignade
recommencerait aux liqueurs.
Le petit Esteban, un peu blasé sur ces émotions sportives, qui
avaient fini par le laisser indifférent, proposa à Robert d’aller faire un
tour sur la plage. Le précepteur accepta avec empressement. Il
s’arrêta au bureau de l’hôtel pour écrire à ses parents les deux
lignes protocolaires, pendant qu’Esteban allait chercher un
pardessus au premier étage, dons l’appartement qu’il occupait avec
ses parents.
Sa lettre écrite depuis quelques minutes, Robert s’étonna de ne
pas voir redescendre son élève. Il prit le parti d’aller voir ce qui se
passait…
Comme il débouchait sur le palier du premier, il vit Esteban se
glisser hors d’une chambre, qui ne dépendait pas de l’appartement
de sa famille, et regarder autour de lui avec précautions dans le
couloir désert.
Le jeune garçon aperçut Robert, eut soudain l’air gêné, et fit à
son précepteur un signe de silence.
Tous deux, sans rien dire, descendirent l’escalier. Dans la rue,
Esteban n’avait toujours pas ouvert la bouche.
— Hé bien, qu’est-ce que tout cela signifie ? se décida à
demander Robert.
Esteban répondit évasivement.
— Ce n’est rien… une farce… Je vous dirai plus tard…
Après tout, il n’y avait peut-être là qu’une gaminerie. Robert n’en
était pas sûr, mais il détestait les enquêtes, quand elles menaçaient
de le conduire à une découverte désagréable.
Il ne put cependant s’empêcher de remarquer qu’Esteban, après
s’être tu, s’était mis maintenant à parler, avec une volubilité
extraordinaire, de sujets sans grand intérêt… Il y avait un effort
visible dans ce flux de paroles, comme un besoin de changer les
idées de son compagnon et de l’attirer n’importe où, mais loin de ses
soupçons.
— Dites-moi des vers, demanda-t-il à Robert, dès qu’ils se furent
assis sur la plage.
Robert, nourri de poésie, résistait difficilement à une invitation de
ce genre, d’autant plus qu’il trouvait chez le petit Esteban un
auditeur frénétiquement sensible, qui écoutait les poèmes avec des
yeux insatiables.
Cette séance de lyrisme dura jusqu’à l’heure du goûter. Ils se
rendirent au Casino. Esteban voulut à toutes forces payer les
consommations, et, au grand étonnement de son précepteur, sortit
de sa poche un billet de cent francs. Or, Esteban, au déjeuner, avait
eu besoin de grands efforts pour soutirer quarante sous au père
Orega.
Mais Robert n’était pas au bout de ses surprises.
— Papa et maman, dit le jeune garçon, sont partis en auto sur la
côte. Ils ne rentreront pas avant le dîner… Voulez-vous me faire un
grand plaisir ?
— Voyons cela, fit Robert.
— C’est de jouer à la boule pour moi. Comme je suis trop jeune,
les employés ne me laisseraient pas jouer… Soyez gentil, dites ?
Jouez pour moi…
L’éducateur essaya de résister. Son disciple avait pris sur lui une
telle autorité que sa résistance fut courte, et qu’il se décida à
s’approcher de la boule, pendant que le petit Orega restait près de
lui, mais en dehors de cette corde de soie, qui prétendait creuser un
abîme infranchissable entre les majeurs et les mineurs.
Le petit jeune homme jouait par louis, et passa à Robert, à la
dérobée, deux ou trois billets de cent francs, qui fondirent en
quelques minutes.
Il tirait d’autres billets de sa poche… Mais Robert se gendarma…
— Je ne veux plus que vous jouiez… C’est très mal… Voyez-
vous que vos parents viennent à l’apprendre ?
— Et c’est sur vous que cela retombera ?
— Ce n’est pas ça, dit Robert gêné… Ce n’est pas du tout pour
cette raison… Et puis, je vous ai déclaré que vous ne joueriez plus…
Vous ne jouerez plus, voilà tout.
Et, ce disant, il s’en alla d’un pas résolu vers la sortie.
Esteban le suivait docilement jusqu’à l’hôtel. Arrivé dans le hall,
Robert, machinalement, s’arrêta devant une sorte de tableau où l’on
placardait les nouvelles du jour…
Or, parmi les informations des agences et les résultats des
courses, il vit une petite affiche manuscrite. On annonçait qu’il avait
été perdu dans l’hôtel une broche « émeraude et saphir ».
Robert, sans s’en rendre compte, ne put s’empêcher de tourner
les yeux vers Esteban, mais le petit Orega regardait cette même
affiche avec une indifférence parfaite.
— Allons travailler un peu avant le dîner, fit Robert.
Ils montèrent ensemble l’escalier. Sur le palier du premier,
Esteban s’arrêta pour donner la main à une jeune fille très forte et
très brune, qui était encore habillée en petite fille, et coiffée avec des
nattes pendantes.
— Ma petite amie Concepcion, dit le jeune garçon… Mon
professeur, M. Robert Nordement…
Concepcion fit une sorte de révérence un peu gauche, sourit à
Robert de toute sa bonne figure et sourit ensuite de même à son
petit ami Esteban, qu’elle dépassait de la tête.
Ils quittèrent la jeune fille pour se diriger vers l’appartement des
Orega. Ils passèrent devant la chambre d’où Esteban était sorti avec
mystère après le déjeuner.
La porte de cette chambre était grande ouverte. Deux
domestiques de l’étage étaient en arrêt sur le seuil. Robert s’arrêta,
lui aussi, et vit que, dans la chambre, le gérant de l’hôtel était en
conférence avec deux messieurs inconnus.
Esteban n’était pas curieux : il s’éloignait, sans hâte apparente,
dans la direction de leur appartement. Robert, s’adressant à un des
domestiques, fit un signe d’interrogation…
— C’est monsieur le commissaire qui se trouve là, dit le
domestique, rapport à une broche qui s’a trouvé perdue. Voilà la
seconde fois en huit jours qu’il se perd un bijou chez ces personnes.
On commence à se dire que ce n’est guère naturel. Heureusement
que, nous autres, on est connu, et que l’on sait qui nous sommes.
Mais, tout de même, ça finit par n’être pas agréable.
— Qui est-ce qui habite ici ? demanda Robert.
— Un vieux monsieur argentin et sa demoiselle.
— Ah !… La demoiselle, n’est-ce pas cette jeune fille, avec des
nattes dans le dos, que j’ai vue tout à l’heure sur le palier ?
— Justement, monsieur. C’est à elle la broche que l’on est en
train de cercher.
… Robert, malgré lui, regarda dans la direction où Esteban était
parti. Mais il y avait beau temps que le petit garçon avait disparu.
Robert gagna l’appartement des Orega. Esteban était dans le
salon, à la table où il s’asseyait pour prendre sa leçon. Sans
attendre son précepteur, il avait pris un cahier… Il était déjà en train
d’écrire, avec une application extraordinaire.
Robert fit d’abord, de long en large, une vingtaine de pas…
— Écoutez, Esteban…
— Monsieur…
— Je veux en avoir le cœur net. Pourquoi êtes-vous sorti
mystérieusement de cette chambre il y a trois heures ? Pourquoi
cette broche a-t-elle disparu ?
Esteban s’était levé. Il s’efforçait de regarder son précepteur bien
en face…
— Je ne sais pas, murmura-t-il…
— Vous savez, dit avec autorité Robert.
Esteban était toujours debout, les lèvres serrées…
— Hé bien ? dit Robert.
Esteban le regardait un peu haletant, avec des yeux qui
semblaient craintifs…
Il vit alors dans le regard de son maître une expression dont
l’excessive dureté l’étonna. Il comprit alors de quoi on le
soupçonnait, et dit à voix basse, comme sur un ton de reproche…
— Oh non ! pas ça tout de même !
… Vous ne supposez pas que c’est moi qui ai pris cette broche ?
Et comme Robert ne répondait rien…
— Oh non ! voyons ! Vous ne me croyez pas capable d’une chose
pareille ? Je ne sais pas quelles bêtises je ferai plus tard… mais je
ne serai jamais un voleur. J’en suis sûr, ajouta-t-il avec une bonne
petite simplicité, qui, ma foi, n’était pas dénuée d’une certaine
noblesse.
Robert en fut tout impressionné.
— Oh ! cela, je pense bien… répondit-il.
Et il fut, à partir de cet instant, profondément convaincu qu’il
n’avait jamais soupçonné d’un vol ce gentil petit Esteban…
— Vous avez tout de même quelque chose à m’expliquer ?
continua-t-il avec douceur.
Pendant la première partie de l’entretien, Esteban avait parlé
comme un homme. A compter de ce moment, et sans transition, il fit
sa confession d’une voix enfantine…
— La jeune fille que vous avez vue tout à l’heure, Concepcion,
est très amoureuse de moi…
— Ah ! vraiment ! fit Robert en souriant.
— Moi, vous savez, je ne l’aime pas beaucoup. C’est à dire que
je l’aime des fois. On s’était connu, elle et moi, au Brésil, une saison
que l’on avait passée avec nos parents aux environs de Rio. C’était il
y a deux ans. Voilà que cette année on s’est retrouvé à Dinard. Elle
était devenue une grande fille. Elle a maintenant seize ans. C’est
cette année qu’elle m’a demandé de venir la voir pendant que son
papa n’y était pas. La première fois que je suis arrivé dans sa
chambre, elle a commencé à m’embrasser en me disant qu’elle
m’aimait et qu’elle voulait m’épouser. Chaque fois que je vais la voir,
elle m’embrasse tout le temps. Moi, presque jamais. Je ne peux pas
me forcer à embrasser les gens quand je ne les aime pas. Il y a des
fois, je ne dis pas, où je l’aime un peu, Concepcion. Mais c’est assez
rare.
Robert regardait Esteban, et se demandait : Est-il aussi ingénu
qu’il en a l’air ? Mais, s’il n’est pas ingénu, qu’est-ce que c’est que ce
petit démon ? Robert n’avait pas assez d’expérience de la vie pour
savoir que l’on n’est pas forcément un « roublard » quand on cesse
d’être un ingénu. La vérité, c’est que les gens sont toujours moins
ingénus et moins roublards qu’on le croit.
Mais les étonnements de Robert n’étaient pas finis encore…
— Un jour, continuait Esteban, Concepcion m’a donné de
l’argent…
Et, ce disant, jamais le visage du petit Orega n’eut un tel air
d’innocence…
— Par cent et deux cents francs, elle m’a déjà donné près de
deux mille francs. Je les ai mis de côté. Je voudrais faire jouer pour
moi au baccara, car je vois bien qu’à la boule il n’y a pas moyen de
gagner. Quand j’aurai une belle somme, je raconterai à papa que je
l’ai économisée depuis cinq ans, et je m’achèterai un side-car…
— Mais, dit Robert, comment vous donne-t-elle tout cet argent ?
Est-ce que vous lui en demandez ?
— Jamais, dit Esteban. C’est elle qui en a eu l’idée pour la
première fois. Et, je vous dirai que maintenant, quand j’ai envie
qu’elle m’en donne, je ne lui en demande pas. Mais je sais bien
prendre un air ennuyé jusqu’à ce qu’elle aille en chercher dans son
armoire…
— Oui, oui… fit Robert.
— Alors, ces derniers temps, comme il ne lui en restait plus, elle
s’est arrangée avec sa miss pour faire vendre des bijoux, qui sont
d’ailleurs à elle. Elle a vendu la semaine dernière ses boucles
d’oreilles, et elle a dit à son papa qu’elle les avait perdues. Elle vient
encore de recommencer avec sa broche.
— Ah ! très bien !… fit Robert.
— Mais je crois, dit Esteban avec un bon et franc petit rire, qu’elle
fera bien de ne pas recommencer, car j’ai idée que ça ne prendrait
plus…
La confession était terminée, et le confesseur était assez
embarrassé pour trouver les termes du commentaire sévère qu’il
aurait fallu. Pourtant, la matière à discours ne manquait pas. Avec ce
phénomène comme Esteban, pour un éducateur d’âme, il y avait,
comme on dit, de quoi faire.
Heureusement pour Robert, qui ne voyait pas tout de suite la
forme de son homélie, M. et Mme Orega rentraient de leur
promenade. Ils étaient assez calmes l’un et l’autre : ils venaient de
se promener en compagnie d’autres personnes, à qui il était décent
d’offrir l’image d’un ménage parfaitement uni. Il arriva qu’ils s’étaient
laissé prendre eux-mêmes à cette comédie. Leur hostilité était
momentanément calmée. Elle ne se rallumerait qu’après quelques
instants de tête à tête ou devant des êtres inexistants, tels que leur
fils et son précepteur.
Ce soir-là, d’ailleurs, M. Orega avait d’autres préoccupations. Ils
venaient de recevoir une dépêche d’amis à eux, qui leur proposaient
de venir les rejoindre au Havre. Ils se préparaient donc à quitter
Dinard le lendemain, car ces braves nomades n’avaient jamais de
fortes attaches avec les lieux où ils séjournaient, au cours de leur vie
de perpétuelle villégiature.
M. Orega demanda à Robert de partir le soir même pour Caen,
où ils avaient projeté de s’arrêter un jour ou deux. Le jeune
Nordement devait faire l’office de fourrier, se rendre compte de ce
qu’il y avait de plus confortable dans les hôtels, et en référer par
téléphone à M. Orega, qui n’attendait que ce signal pour quitter
Dinard en auto.
Robert arriva le lendemain matin vers dix heures dans la ville
normande, grâce à une savante combinaison de trains, que l’on
finissait par découvrir en compulsant trois ou quatre pages de
l’indicateur, après s’être reporté à des notes à peu près introuvables,
où vous renvoyaient d’invisibles minuscules, que distinguaient à la
loupe quelques rares initiés.
Pendant ses insomnies, entretenues par des changements de
trains et de froids stationnements dans des gares abandonnées de
Dieu et des hommes, Robert s’était appliqué à songer aux
remontrances qu’il ferait au petit Orega, et en avait soigneusement
ordonné le plan.
Une fois à Caen, il se fit conduire dans l’hôtel le plus en vue, où il
trouva pour ses patrons un appartement suffisamment somptueux.
Toutefois, avant de le retenir définitivement, il demanda la
communication avec Dinard, et se dit avec satisfaction qu’en
attendant le moment de l’avoir obtenue, il aurait tout le loisir de
savourer tranquillement son petit déjeuner du matin. Mais le dieu
sournois du téléphone n’aime pas que l’on veuille pénétrer ses
voies. Et Robert était à peine installé devant son chocolat, que le
portier ouvrait la porte du restaurant, et annonçait que Dinard était à
l’appareil.
— C’est M. Orega ? dit Robert dans la cabine.
— Oui, c’est moi.
— Ici M. Nordement… Je vous téléphone de Caen, de l’hôtel. J’ai
trouvé ce qu’il vous faut comme appartement.
— Oui… Hé bien… Hé bien, ne le retenez pas… Oui… Madame
et moi… nous n’avons plus le même avis… Nous demeurons encore
à Dinard…
— Ah !… Que dois-je faire alors ?
… Hésitation…
— Allô !… fit Robert.
— Je suis là, fit M. Orega… Je suis là… Écoutez, monsieur
Nordement, dites-moi à quelle adresse je puis faire parvenir une
somme… une somme de mille francs, ou un peu davantage, si vous
pensez que je vous dois plus… Madame et moi nous avons pris
cette décision… que l’enfant devait abandonner ses leçons… qu’il
valait mieux du repos pour la santé de ce petit…
Robert, étonné, resta sans répondre. Ce fut le tour de M. Orega
de faire : Allô ! allô !
— Vous êtes là, monsieur Nordement ?
— Oui, Monsieur. Mais permettez-moi de vous dire que si vous
êtes maître de faire ce que bon vous semble pour l’éducation de
votre fils… je ne puis pas, moi, me séparer de vous sur cette simple
raison. Il me faut d’autres explications que celle que vous me
donnez. Vous reconnaîtrez vous-même qu’elle n’est pas suffisante.
Silence absolu dans l’appareil.
— Allô !… fit sévèrement Robert.
— Je suis toujours là, monsieur Nordement. Alors, je dois vous
dire… je dois vous dire… le vrai… Un monsieur… que je connais…
un ami, me dit que hier, pendant que nous étions, madame et moi, à
la promenade, vous êtes allé à la boule avec l’enfant… et que là
vous avez joué… C’est votre droit, monsieur Nordement… Toutefois,
madame et moi, nous pensons que l’exemple n’est pas bon pour ce
jeune garçon…
— Ah ! ne put s’empêcher de dire Robert, ce n’est pas
exactement comme ça que ça s’est passé…
— Comment cela s’est-il passé ?
Robert, son premier mot de protestation lâché, s’était repris… Il
s’était dit qu’il ne devait pas trahir son petit élève…
D’autre part, depuis quelques secondes, il avait le désir
impérieux de rompre toutes relations avec M. Orega, pour qui il
éprouvait une haine subite et définitive. Il se borna donc à ajouter,
non sans sécheresse :
— Ça va bien, monsieur, ça va bien…
— Vous me comprenez un peu, monsieur Nordement ?
— Oui, je vous comprends, monsieur, ça va bien.
— Où dois-je vous envoyer la somme en question ?
— Nulle part, monsieur. Je n’ai pas fait votre affaire. J’estime que
vous ne me devez plus rien.
— Ah ! je ne comprends pas cela de cette façon…
— C’est ma façon à moi de le comprendre… Vous réglerez, si
vous le voulez bien, mes frais d’hôtel pour le temps que j’ai passé à
votre service. Vous m’avez remis hier deux billets de cent francs
pour mon voyage ici. Je prélèverai là-dessus les frais que j’ai eus, et,
à la première occasion, je vous rembourserai le reste. Ou plutôt je
vous le renverrai par la poste. Car il se peut bien que l’on ne se
revoie pas tout de suite…
— Pourtant, monsieur Nordement, je ne puis admettre…
— Je l’admets parfaitement, monsieur… Au revoir, monsieur…
Et il raccrocha le récepteur. Il le décrocha ensuite pour dire :
« Faites bien mes amitiés à Esteban… » Mais la communication était
déjà interrompue avec Dinard. Et la voix de M. Orega était déjà
remplacée par une voix campagnarde, qui, d’on ne savait où,
demandait : « C’est la mairie de Bayeux ?… C’est la mairie de
Bayeux ?… » et répétait cette phrase éperdue dix fois, quinze fois,
dans un silence inexorable…
V

Tout compte vérifié, avec le peu d’argent qui lui restait au


moment où il avait été engagé par M. Orega, Robert se trouvait avoir
sur lui un peu plus de trois cents francs. Il n’y avait pas là de quoi
tranquilliser un homme prévoyant.
Mais il s’était passé en lui, depuis quelques jours, un phénomène
assez curieux.
Le fait de s’être détaché de sa famille avait déjà eu ce précieux
avantage de le débarrasser d’une partie de la prévoyance un peu
lourde qu’il avait acquise au foyer paternel.
Trois jours auparavant, il avait vu, pour la première fois de sa vie,
le Destin intervenir directement dans ses affaires en le mettant sur le
chemin de la famille Orega… Cette chance avait duré ce qu’elle
avait duré : au moins avait-il été tiré d’embarras pendant trois jours.
Depuis son enfance, il s’était borné à suivre l’Étoile familiale.
Maintenant il lui semblait qu’il avait sa petite étoile à lui…
Sans situation sociale, il éprouvait une vague allégresse. Il
s’avançait gaiement vers la brume de son avenir. C’était une brume
blanche, éclairée d’une confiance juvénile.
Sa rupture avec la famille Orega le satisfaisait. Certes, il s’était
senti un petit attachement d’amitié pour le jeune Orega. Tout de
même, il ne déplorait pas qu’un brusque coup du sort l’eût séparé de
ce personnage un peu trouble.
Évidemment c’eût été une tâche intéressante que d’essayer de le
moraliser. Mais que d’aléa dans cette entreprise !
L’aventure de Concepcion, acceptée par Esteban avec tant
d’innocence, n’eût sans doute pas trouvé, une fois divulguée, des
appréciations très indulgentes dans l’opinion publique.
On aurait su que le précepteur était au courant de l’histoire…
Somme toute, il valait mieux avoir semé tous ces gens-là, et
chercher dans le vaste monde des compagnons de vie moins
compromettants.
Voilà ce qu’il se disait en mangeant son chocolat refroidi. Et son
bien-être moral eût été complet sans le petit ennui d’être obligé de
donner contre-ordre à l’hôtel, et de prévenir la gérance que
décidément il ne prenait pas pour le soir l’appartement qu’il avait à
peu près retenu. Il se crut obligé, au bureau de la réception, de faire
tout un récit, de raconter que « ses amis » n’étaient pas bien
portants, et n’avaient pu quitter Dinard comme ils avaient cru. « Il est
possible, dit-il, qu’ils m’envoient tout à l’heure une dépêche pour me
dire qu’ils vont mieux, qu’ils se ravisent et qu’ils viennent tout de
même… Mais n’immobilisez pas l’appartement… » Il partit ensuite,
sa valise à la main, la tête très haute, après avoir remis au portier un
pourboire tout à fait en disproportion avec les ressources d’un
précepteur jeté brusquement sur le pavé.
Qu’allait-il faire ?
Rester à Caen ?
Pourquoi pas, après tout ?
Il valait mieux ne pas grever son budget du prix d’un nouveau
billet pour se transporter en chemin de fer dans une autre ville, où
ses chances de trouver une position n’eussent pas été plus
nombreuses que dans « l’Athènes normande ».
Caen, avec ses cinquante mille âmes, offrait à peu près autant
de ressources que la plupart des villes de France. L’enfant prodigue
s’interdisait, bien entendu, tout séjour à Paris, où son père avait sa
maison de commerce et son domicile d’hiver.

You might also like