100% found this document useful (11 votes)
83 views

(Ebook) Javascript.info Ebook Part 1 The JavaScript language by Ilya Kantor, javascript.info download pdf

The document provides an overview of JavaScript, detailing its evolution from a browser-only language to a versatile programming language used in various environments. It highlights the language's integration with HTML/CSS, its unique features, and mentions several languages that transpile to JavaScript. Additionally, it offers resources for further learning, including manuals and specifications for in-depth understanding of the language.

Uploaded by

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

(Ebook) Javascript.info Ebook Part 1 The JavaScript language by Ilya Kantor, javascript.info download pdf

The document provides an overview of JavaScript, detailing its evolution from a browser-only language to a versatile programming language used in various environments. It highlights the language's integration with HTML/CSS, its unique features, and mentions several languages that transpile to JavaScript. Additionally, it offers resources for further learning, including manuals and specifications for in-depth understanding of the language.

Uploaded by

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

Download Full Version ebook - Visit ebooknice.

com

(Ebook) Javascript.info Ebook Part 1 The


JavaScript language by Ilya Kantor,
javascript.info

https://ebooknice.com/product/javascript-info-ebook-
part-1-the-javascript-language-10437690

Click the button below to download

DOWLOAD EBOOK

Discover More Ebook - Explore Now at ebooknice.com


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) Javascript.info Ebook Part 3 Additional articles


by Ilya Kantor, javascript.info

https://ebooknice.com/product/javascript-info-ebook-part-3-additional-
articles-10437696

ebooknice.com

(Ebook) Javascript.info Ebook Part 2 Browser: Document,


Events, Interfaces by Ilya Kantor, javascript.info

https://ebooknice.com/product/javascript-info-ebook-part-2-browser-
document-events-interfaces-10437692

ebooknice.com

(Ebook) Modern nonlinear optics. Part 1 by Myron W. Evans


(editor), Ilya Prigogine, Stuart A. Rice (series editors)
ISBN 9780471231479, 9780471389309, 9780471466130,
0471231479, 0471389307, 0471466131
https://ebooknice.com/product/modern-nonlinear-optics-part-1-921234

ebooknice.com

(Ebook) Koren Talmud Bavli Noe Edition: Volume 29:


Sanhedrin Part 1, Hebrew/English, Large, Color Edition by
Adin Steinsaltz ISBN 9789653015906, 9653015907
https://ebooknice.com/product/koren-talmud-bavli-noe-edition-
volume-29-sanhedrin-part-1-hebrew-english-large-color-edition-21975022

ebooknice.com
(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason;
Viles, James ISBN 9781459699816, 9781743365571,
9781925268492, 1459699815, 1743365578, 1925268497
https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374

ebooknice.com

(Ebook) Master SAT II Math 1c and 2c 4th ed (Arco Master


the SAT Subject Test: Math Levels 1 & 2) by Arco ISBN
9780768923049, 0768923042
https://ebooknice.com/product/master-sat-ii-math-1c-and-2c-4th-ed-
arco-master-the-sat-subject-test-math-levels-1-2-2326094

ebooknice.com

(Ebook) Play 1.b3: The Nimzo-Larsen Attack: a Friend for


Life by Ilya Odessky ISBN 9789056912567, 9056912569

https://ebooknice.com/product/play-1-b3-the-nimzo-larsen-attack-a-
friend-for-life-1759514

ebooknice.com

(Ebook) How to Draw Comics by Ilya by Ilya ISBN


9781613739037, 1613739036

https://ebooknice.com/product/how-to-draw-comics-by-ilya-48681814

ebooknice.com

(Ebook) The Greek State at War: Part 1 The Greek State at


War, Part I ISBN 9780520340961, 0520340965

https://ebooknice.com/product/the-greek-state-at-war-part-1-the-greek-
state-at-war-part-i-51821948

ebooknice.com
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”).
Exploring the Variety of Random
Documents with Different Content
CHAPTER XIII
THE AMERICAN COLLEGE AT ASYUT

At Asyut up the Nile valley about as far south of the Mediterranean


as Washington is south of Buffalo, the United Presbyterians of the
United States have established a training college for young
Egyptians which is doing a wonderful work. I came from Cairo to see
it, winding my way in and out along the great river. The valley is
narrow above Cairo, being only from three to nine miles in width, so
that from the railroad I could see the yellow sand on both sides of the
green, watered strip. We were sometimes far out in the desert, and
sometimes moving in and out of the irrigated lands. We passed mud
villages which border the river and the larger canals. The date trees
hanging over them were loaded with honey-coloured fruit. Upper
Egypt has vast numbers of dates. There are in the whole country
something like eight million of these palms, which, at a rough
estimate, bring in one dollar annually for every tree.
Asyut is the largest city in Egypt south of Cairo. It is the capital of
this part of the Nile valley and the chief centre of its commerce and
trade. Before the railroad was built, caravans from the Sudan
brought great quantities of merchandise from Central Africa to Asyut
and transferred it to other camel trains bound for Tripoli, Cairo, or
Suez. The railroad now carries this trade, and the iron tracks have
been extended southward beyond the city of Khartum. The gap in
the railroad between Shellal and Wady Halfa is filled by steamers on
the river.
Asyut itself has many good buildings. Not far from the railroad
station are brick houses of two and three stories which would be
considered fine anywhere. They are owned by Copts, who started
life poor and have become millionaires. Most of the houses of the
city are Egyptian in character, flat-roofed buildings of one, two, and
three stories, facing the street. Many of them are new and
substantially built. The bazaars are far better than when first I visited
Asyut, and the town, which has now over fifty thousand people, is
double the size it was then.
The Asyut Training College is a missionary institution, but it gives
a good general education. It is run upon broad lines and has among
its students Mohammedans, Copts, and other Christians. This is
about the only one of our Protestant denominations that is working
here, the other sects having apparently given up Egypt to it. This
Church has mission stations scattered throughout the Nile valley,
and schools not only in Lower and Upper Egypt but also in the
Sudan, and even on the borders of Abyssinia. There are more than
fifteen thousand boys now being taught in its various institutions. It is
surprising that a large part of the money that the mission is spending
upon education comes from the natives themselves. In one year
over one hundred thousand dollars was spent, of which almost
eighty thousand was subscribed by the Egyptians. Of the fifteen
thousand in the schools, more than thirteen thousand are paying for
tuition, so that the institutions are largely self-supporting. The
Egyptians of to-day have learned the value of modern school training
and are anxious to have their sons go to college. They want them
taught English and are willing to pay something in order that they
may get a good education.
I went through the college with its president, John Alexander, D.D.,
who has been in charge for almost a generation. To him it is largely
due that it is the most successful institution of its kind in northern
Africa. Dr. Alexander is by birth an Ohioan. He was educated at
Wooster University and shortly after he left there he came to Egypt.
He has lived here ever since and he knows the people and their
wants as well as any man. He says that the natives are thoroughly
alive to the advantages of modern education and that they could use
more schools and better facilities than either the government or the
mission can supply. He tells me that he has to refuse many
applications for entrance to the training school for lack of room and
that the college stands ready to erect new buildings as soon as it can
raise the money. It has already bought twenty acres of land at the
junction of the Nile and the great irrigating canal which runs from
here to the Faiyum, and it now needs only an appropriation for
additional buildings. My examination shows me that the institution is
ably and economically managed, and I know of no place where any
one of our rich men can better invest his surplus and have it pay big
dividends in a charitable way than right here.
This college is conducted on the dormitory plan. The majority of its
students live in the buildings and are continually under the eyes of
their professors. The training partakes somewhat of a military
character. The boys not only go to classrooms, but they have to
attend chapel, weekly prayer meeting, and Sunday-school. They are
also compelled to take part in college athletics. Twice a week they
must engage in football and tennis and every effort is made to
develop them as our boys are being developed. They study well and
do good work on track and football field.
I should like to show you these Egyptian boys as I saw them to-
day. There were seven hundred and thirty of them in the campus
when I went through—bright-eyed, dark-faced young fellows, ranging
in age from ten to twenty years and coming from every class of
Egyptian life. Some were Mohammedans, the fatalistic, sober
followers of the Prophet; others were Copts, having the bronze
faces, the high cheekbones, and the black eyes which mark them as
the descendants of those who oppressed the Israelites when
Pharaoh ruled. All the students wear red fezzes that extend about
eight inches above their heads and are kept on both in classroom
and chapel. They wear long gowns, often belted in at the waist, and
look more dignified than the college boy of America.
The students are of all classes and conditions. Many are working
their way through school. There are three scales of expense,
graduated according to the tables at which the boys eat. One class
has a table where all have knives and forks and the food furnished is
as good and as varied as can be found anywhere. This is for the
rich, who can pay as much as one hundred dollars a year for room
and board. The second table is filled by students who can afford to
pay only fifty dollars a year, and the third by those who cannot spare
more than thirty-five dollars a year. Of the students of the first class
only two or three live in one room, and of the second from four to
eight, while those of the third are lodged in large rooms
accommodating twenty or thirty, each of whom has his own bed,
which he furnishes himself.
The boys of the second class have simpler food than those of the
first and eat with their fingers in native style. Those of the third class
have still cheaper food, but in all cases it is as good as or better than
the boys get at home, for here they have wheat bread and meat at
least once a week.
A pupil must pay a minimum fee of one dollar a session in money,
but as far as is possible he may work out the rest of his expenses.
The average tuition is only ten dollars a year.
This big American college is doing so much good for Egypt that it
is commended by the government and by every tourist who learns
anything of Egyptian affairs. It was founded in 1865 and its first work
was done in a donkey stable with five students. Dr. Hogg, a Scotch
missionary, then constituted the entire faculty. It has now seven large
buildings, which cover two acres, built around a campus shaded by
date palms, and among its professors are graduates from the best of
our colleges, including men from Princeton and Yale. It has not far
from one thousand students, who come from all parts of Egypt and
even from the Sudan and the other countries of northern Africa.
These youths represent more than one hundred towns throughout
the Nile valley and the graduates are scattered all over Egypt. Many
of them are influential business men; some are lawyers, doctors, and
teachers, and others are government officials. The graduates of the
school are anxiously sought by the government as clerks. Their
training is considered better than that of the Mohammedan colleges,
where little except the Koranic law is taught, and they are found to
be trustworthy and of high moral character.
From Asyut come the famous metal shawls of silver or gold on black or white.
The bazaar is over a mile long, and before the days of railroads was the trading
place of caravan merchants from the south and buyers from the north.
The Egyptian complained that under British rule not enough of his tax money
was spent on native schools. Only twelve per cent of the men and less than two
per cent of the women can read and write.
CHAPTER XIV
THE CHRISTIAN COPTS

Many of the students of the Asyut Training College are Copts.


They belong to that class of natives who are said to be the only
direct descendants of the ancient Egyptians. The Copts are more
intelligent than the Mohammedans. They take naturally to education,
and about four Copts go to school to every one Moslem. They are
also shrewd clerks and, many of them being educated men, they
have a large number of the minor government appointments. The
British, however, tried to be partial to the Mohammedans because
they form the great majority of the population, and to give them
offices in preference to the Copts. During Lord Cromer’s
administration, a committee of Copts objected to his crowding out
these native Christians and giving their places to the followers of the
Prophet. Applicants for any government posts or for training schools
have to give their names, and the Copts can thus be easily
distinguished from the Mohammedans. The Christian boys get their
names from the characters of the Bible, while the names of the
Mohammedan boys come from the Koran. When the examination
papers were turned in, the judges were said to have been instructed
to mark down all those bearing such names as Moses and Jacob,
Peter and Paul, and to recommend for appointment the
Mohammeds, the Alis, and the Hassans. The British governing class
considered that the Copt and the Mussulman, being alike natives,
were generally not capable of holding any responsible position. And
now it is said also that it would be bad policy to put the Christian
Egyptian over the Moslem.
The Copts are the sharpest business men of Egypt. It is a
common saying here that no Jew can compete with them and they
have driven the Jews out of the upper part of the Nile valley. In Asyut
there are a number of rich Copts who have become Protestant
Christians, and some of these men are very charitable. One, for
instance, built a Protestant native church, after a visit to England,
where he was much impressed by Westminster Abbey. Upon his
return he said he was going to build a church for Asyut on the plan of
Westminster. The missionaries advised him to make his building
rectangular instead. But no! it must be Westminster Abbey or
nothing; and the result is a great T-shaped structure of wood with a
long hall in the centre and wings at the end. The church cost about
twenty thousand dollars and will seat one thousand five hundred
people. I attended it last Sunday and found the main hall filled with
dark-faced men in gowns and fezzes. The wings were shut off by
curtains, but I was seated in front and so near one side that I could
look through the cracks. Each wing was filled with women clad in
black balloon-like garments and veiled so as to conceal all but their
eyes. Yet a few women wore European clothes and French hats,
showing how the new civilization is coming in.
Another rich Copt established two large primary schools at Asyut,
one for boys and the other for girls. In the boys’ school there are five
hundred and fifty pupils, and in that for the girls more than two
hundred. These schools are taught by native Protestants, and not
one cent of American money is spent upon them.
I am much interested in the Copts. There are about eight hundred
and fifty thousand of them in the country. They look very much like
the Egyptians and dress in about the same fashion. The women veil
their faces, both in public and private, and until about a generation
ago the unmarried women wore white veils.
These people believe in the ancient form of Christianity. They are
indeed the same Christians that Egypt had in Roman times. They
claim St. Mark as their first patriarch and say that he preached the
Gospel at Alexandria and started the sect there. They have a
patriarch to-day, with twelve bishops and a large number of priests
and deacons under him. They have their monks and nuns, who lead
rigorous lives; they fast and pray, wear shirts of rough wool, and live
upon vegetables.
The Copts believe in God the Father, and in the Lord Jesus Christ
as his Son. They believe in prayer, and like the Mohammedans, pray
five or six times a day. They begin their devotions at daybreak and
are supposed to make five separate petitions before dark and to
close with a final prayer at midnight. As they pray they recite a Psalm
or chapter from the Gospel, and some have rosaries of beads on
which they count forty-one times, saying the words:
“Oh! my Lord, have mercy.”
After this they end with a short petition. They wash before praying,
and worship with their faces turned toward the east. They believe in
baptism and think that an unbaptized child will be blind in the next
life. They have fixed times for baptism, a boy baby being baptized at
forty days and a girl baby at eighty days after birth.
There are Coptic churches all over Egypt, and I find several here
at Asyut. The church usually consists of four or five buildings
surrounding a court, and includes a chapel, a hall of worship, the
residence of the bishop, and other rooms. The sanctuary proper
contains an altar separated from the rest of the rooms by a screen,
covered by a curtain with a cross worked upon it. Before this curtain
stand the priest, the choir, and the more influential members of the
congregation. Beyond them is a lattice work, on the other side of
which are the less important men, with the women in the rear.
Everyone is expected to take off his shoes when he comes in, and in
many of the halls of worship, as there are no seats, the people lean
upon sticks while the sermon is preached. The service begins at
daybreak and often lasts four or five hours, so that it is no wonder
that some of the members of the congregation fall to chatting during
the preaching, and discuss business and social matters.
I am told that the Copts do not trust their wives any too much.
Each has but one, but he does not make her his confidante, never
tells her his business secrets, and pays her much less respect than
the native Protestant Christians show their wives. He seldom sees
his wife until he is married and is forbidden by his religion to marry
any one but a Copt. As among the Mohammedans, marriages are
usually a matter of business, with a dowry bargained for beforehand.
The favourite wedding time is Saturday night, and the marriage
feasts last through the following week. When the marriage contract is
made all the parties to it say the Lord’s Prayer three times. Before
the ceremonies are completed the bride and the bridegroom go
separately to church where the Eucharist is administered to them.
Just before her marriage, the bride is given a steam bath, and her
finger nails and toe nails are stained red with henna. Immediately
before the ceremony she sends the groom a suit of clothing, and a
woman from her house goes to him to see that it is delivered
properly and that he is taken to the bath. This provision ensures that
both start the married life comparatively clean.
CHAPTER XV
OLD THEBES AND THE VALLEY OF THE KINGS

All day long I have been wandering about through the tombs of the
kings who ruled Egypt three or four thousand years ago. I have gone
into the subterranean chambers which the Pharaohs dug out of the
solid rocks for their burial vaults, and I have visited the tombs of
kings older than they. The last resting places of more than fifty of
these monarchs of early Egypt have been discovered, and the work
is still going on. Some of the best work of excavation all along the
Nile valley is being done by Americans. While at Cairo I found the
money of Harvard College and the Boston Museum uncovering the
cemeteries of the nabobs and paupers who were buried at the time
of King Cheops under the shadow of the Great Pyramid of Gizeh.
The Egyptian Exploration Fund, which is supported by Great Britain,
Canada, and the United States, has a small army of workmen
operating near Luxor, the University of Pennsylvania has made
important discoveries, and a large part of the uncovering of the
valley in which these royal tombs lie has been done by the
Americans.
The Egyptologists of the Metropolitan Museum in New York and
Lord Carnarvon of England are responsible for some of the most
remarkable finds of this generation. During my trip of to-day I met a
young archæologist, in charge of the American operations, who
showed me through the tombs of the kings and explained the
symbols and pictures on the walls. I went to that part of the valley
where the excavation is now going on and took pictures of a gang of
one hundred and fifty Egyptian men and boys who are working there.
Let me describe the place that the ancient Egyptian monarchs
selected for their burials, the Valley of the Kings. They wanted to
hide their remains so that posterity could never find them, and to
cover them so that future generations would have no idea that they
and their treasures lay beneath. Our cemeteries are chosen for the
beauty of their surroundings. We like to turn up our toes to the
daisies and to have leafy trees whisper a requiem over our heads.
The old Egyptian kings wanted to lie under the sterile desert waste
and chose a region about as far up the Nile valley as Cleveland is
inland from the Atlantic, and fully six miles back from the fertile strip
on which their people lived. I can imagine no place more dreary. At
this point the Nile is walled on the west by limestone mountains. As
far as the moisture reaches, the valley is the greenest of green, but
beyond lies a desert as brown as any part of the Sahara. There is
not a blade of grass, nor a sprig of vegetation of any kind. There is
nothing but sand and arid mountains, the latter almost as ragged in
outline as the wildest parts of the Rockies. Some of their stony sides
are built up in great precipices while in other places there are fort-like
bluffs and similar convulsions of nature.
Rameses II, the greatest egoist of Egyptian history, covered his dominions with
his monuments and inscriptions. Standing against the colossal leg of this statue is
the figure of his sister, Nefertari, who was also his favourite wife.
Hatshepsut, the Queen Elizabeth of Egypt, reserved for herself the best space in
the splendid temple-tomb at Deir-el-Bahari, tucking away in small quarters the
bodies of her male relatives. A brother later retaliated by removing her name from
the inscriptions.

Every great temple in ancient Egypt had its sacred lake, where the worshippers
performed their ablutions and the religious processions of boats took place. The
banks of this lake at Karnak were originally lined with smooth-cut stone.

To visit this valley one first comes to Luxor, which is very nearly on
the site of Old Thebes, the capital of Egypt in the days of its most
brilliant past. The ancient city lay on both sides of the Nile, but Luxor
is on the east bank. Crossing the river in a ferry boat, I rode for an
hour or more through the desert before I came into the Valley of the
Kings. My donkey boy was a good one and his donkeys were young.
His name was Joseph, and the brute I bestrode was called
“Gingerbread.”
We traversed green fields, winding in and out along the canals,
until we came to the desert and entered a gorge walled with rocks of
yellow limestone and a conglomerate mixture of flint and limestone
of curious formation. The gorge shows evidences of having been cut
out by some mighty stream of the past. There are masses of débris
along the sides, and the way is rough except on the road which has
been made by the explorers.
Looking at the valley from the Nile one would not suppose it to be
anything other than a desert ravine, so I did not at first realize that it
was a cemetery. There are neither gravestones nor monuments, for
the kings obliterated every sign that might indicate their burial
places. They dug out great chambers under the bed of this dried-up
river and built cisterns for their proper drainage, but when they had
finished they did all they could to make the spot look as it was in
nature. For this reason their tombs remained for ages untouched and
unknown.
From time to time, however, one or another was discovered.
Strabo, the Greek geographer, who was alive when Christ was born,
speaks of forty of them as being worthy of a visit, and others are
mentioned by subsequent writers. Later they were again lost, and
not until in our generation when some Arabs began to sell curious
antiquities was it learned that the tombs had been rediscovered and
were being rifled by these vandals. The archæologists then went to
work on their explorations which resulted in the opening up of tomb
after tomb, until we now have what might almost be called a
subterranean city of the dead in the heart of the desert.
The tombs are nothing like our burial vaults. They are large rooms
cut out of the solid rock, with walls straight and smooth. They are
reached by many steps, going down inclined planes until they bring
one far below the surface of the valley and deep under the
mountains. Each king had his own tomb, which he decorated with
sketches and paintings representing the life of his time and the
achievements of his reign. The ceilings are beautiful. From some of
them the figures of gods and goddesses look down upon us. Others
are decorated with geometric designs in beautiful colours. In some,
men and women are carved in bas-relief out of the solid rock and
then coloured. Many of the scenes are religious, so that from them
the Egyptologist is able to learn what the people of that day believed.
The carvings show, too, how they lived when our remotest ancestors
were savages in the wilds of Europe and Asia.
The Americans have had remarkably good luck in their finds. One
of them was the tomb of the parents of Queen Tiy in which all the
objects were in as good condition as if they had been in a house just
closed for the summer. There were armchairs beautifully carved and
decorated with gold. The cushion on one of them was stuffed with
down and covered with linen perfectly preserved. In another part of
the chamber were two beds decorated with gold, while a light chariot
stood in a corner. But most wonderful of all was the discovery in this
tomb of a jar of honey, still liquid and still fragrant after thirty-three
hundred years.
In some of the tombs I saw the massive stone boxes in which lay
the mummies of the dead kings. I measured one ten feet long, six
feet wide, and eight feet high. It was hollowed out of a block of
granite, and would weigh many tons. That mighty burial casket was
cut out of the quarries of Aswan far above here, on the banks of the
Nile. It must have been brought down the river on a barge and
carried to this place. When it was finally on the ground it had to be
lowered into the vault. All these feats were done without modern
machinery. As I went through the tombs I saw several such caskets,
and the archæologist who guided me showed me the holes in the
stone walls of the entrance ways where beams had been put across
in order that ropes might be used to prevent these stone masses
from sliding too far when let down. It is a difficult job for us to handle
safes. One of these stone boxes would weigh as much as several
safes, yet the old Egyptians moved them about as they pleased.
Indeed, I venture to say that the civil engineers of the Pharaohs
could teach us much. All through this region there are enormous
monuments which it would puzzle the engineers of to-day to handle.
For instance, there are the Colossi of Memnon, the two mammoth
stone statues that sit upon pedestals in the Nile valley within a few
miles of where I am writing. Each is as high as a six-story building,
and the stone pedestals rise thirteen feet above the ground. As I
rode by them on my way home from the Valley of the Kings I climbed
up and ran a tape measure over their legs. Each leg is nineteen feet
from sole to knee. The feet are each over three yards in length, so
long that one would fill the box of a farm wagon from end to end, and
so wide that it could hardly be fitted within it. Each arm from finger
tips to elbow measures five yards, and the middle finger of each
hand is a yard and a half long. As I stood beside the pedestal, with
my feet on Gingerbread’s saddle, I could not reach the top.
These two colossal figures sit side by side on the edge of the Nile
valley with the desert mountains at their backs. They were set up in
honour of an Egyptian king who lived more than thirty-five centuries
ago. The temple he constructed behind them has now entirely
disappeared. The statues overlook green fields, and as I gazed at
the giant shapes I thought how they had watched the people sowing
and reaping through all these centuries.
Not far from these monuments are the ruins of the temple of
Rameses II, according to some authorities the Pharaoh who “would
not let the people go.” Among them I saw the remains of a statue of
that old king, once part of a structure at least sixty feet high. There is
no granite nearer here than in the quarries of Aswan, so this mighty
monument must have been cut there and brought down the Nile to
Thebes, a distance of one hundred and thirty-five miles.
Consider the obelisks which the Egyptians made at those quarries
and carried down the Nile to Thebes, to Cairo, and to Alexandria.
There are two of them still at this place. You may see them in the
great Temple of Karnak, which is not more than a twenty-minute walk
from Luxor. They weigh something like four hundred tons each, and
if they were broken up and loaded upon wagons it would take one
thousand six hundred horses to haul them. Each is a single block of
granite, and each was carried in that shape to this place. There are
inscriptions on the Deir-el-Bahari Temple here which show that these
two shafts were dug out of the quarries, covered with hieroglyphic
carvings, brought here, and put up all in the space of seven months.
I doubt whether our engineers could do such a job as quickly or as
well.
We thought it a wonderful work to bring the Alexandria obelisk
from Egypt to New York in the hold of a steamer. To load it a hole
had to be cut in the bow of the vessel and the pillar dragged through.
The Egyptian obelisk at Paris was carried across the Mediterranean
on a barge, while that which now stands in London was taken there
in an iron watertight cylinder which was shipped to Alexandria in
pieces and built around the column as it lay upon the shore. When
the great stone was thoroughly encased, the whole was rolled into
the sea and thus towed to London. After the huge monoliths were
landed, the modern engineers had great trouble to get them where
they wanted them. The New York obelisk was rolled along upon iron
balls running in iron grooves laid down for the purpose, while that of
London was hauled over greased ways to the place where it now
stands on the banks of the Thames.
The oldest temple of Egypt by five hundred years was unearthed
here by the agents of the Egyptian Exploration Fund. This lies near
the famous temple of Deir-el-Bahari, and in a valley which is a
branch of that of the tombs of the kings. When I visited it to-day the
excavators were at work, and the men in charge told me they had
great hopes of making valuable discoveries. It was with the
American representative of the Exploration Fund, that I went over the
temple. I met him at the little one-story house which forms the
laboratory and home of the foreign explorers, and had a chat with
the other members as to the progress of the work. A number of
specialists from Canada, England, and the United States, supported
by the fund, are superintending the Egyptians, who do the hard
labour. They have quite an army of men at work and have been
successful. Of what they find one half goes to the museum at Cairo
and the rest to the countries which subscribe to the fund in
proportion to the amount of their subscriptions. The chief money
from America has come from Boston, New York, Baltimore, and
Washington, so that our share of what is now being unearthed will go
to the museums of those cities.
More famous than this ancient temple itself is its shrine of the cow
goddess, Hathor, from which the noted statue was excavated by the
Egyptian Exploration Fund and taken to Cairo. I saw the place
whence it came and talked to the men who dug it out of the earth.
The statue, which is life-sized, is a perfect likeness of a beautiful cow
carved out of stone. It is reddish-brown in colour, with spots shaped
like a four-leaved clover. Traces still remain of the gold that once
covered the head, neck, and horns. The head is crowned with lotus
flowers and lotus stalks hang down each side the neck almost to the
ground. Beneath the head stands the dead king whom Hathor
protects, while the living king, whom she nourishes, kneels beneath
her form. That image was probably worshipped at the time the
Israelites were working in the valley of the Nile, and it may have
been after one like her that they modelled their calf of gold.
Near the site of this oldest temple are the ruins of the great temple
of Hatshepsut, the Queen Elizabeth of Egypt, who ruled fifteen
hundred years before Christ was born. Her epitaph says that “Egypt
was made to labour with bowed head for her.” The temple is really a
tomb-chapel in memory of the royalties buried there—her father, her
two brothers, and herself. Hatshepsut took most of the space,
however, and put the bodies of her male relatives into as small
quarters as she could. She called her temple “most splendid of all”
and covered its walls with engravings and paintings showing her
principal acts. Hers is a long record of kingly deeds. She discarded
the dress of a woman, wore the crown, attached an artificial beard to
her chin, and let it be known that she liked to be addressed as His
Majesty by her courtiers and subjects. The New Woman is
apparently as old as civilization itself!
It was the work of Americans, again, that unearthed here the tomb
of the first great pacifist, Pharaoh Akhnaton, who reigned from 1375
to 1358 b.c. When he came to the throne Egypt, in the height of her
power, was mistress of the chief parts of the civilized world. But the
country was then ridden by the priesthood of Amon with its hosts of
gods and its degraded worship. According to the inscriptions which
have been deciphered young Akhnaton defied the priests of Amon
and declared his belief in one God, a “tender and merciful Father
and Mother of all that He had made,” the “Lord of Love,” the
“Comforter of them that weep.” It is thought that he was the Pharaoh
in Egypt when the Children of Israel came into the land and that the
One Hundred and Fourth Psalm in our Bible was written by him. He
did not believe that warfare or military conquests were consistent
with his creed and when revolts broke out in his Syrian provinces he
refused to fight, though his soldiers tried desperately hard to hold the
different people of his empire faithful to their king.
Breaking entirely with the priests, Akhnaton left Thebes and set up
his capital at Aton, one hundred and sixty miles south of Cairo on the
eastern bank of the Nile. He died at the age of twenty-eight, leaving
only daughters to succeed him. They reëstablished the court at
Thebes, the city of Aton was abandoned, and its temples and
palaces were left to crumble and decay.
I had thought of the Pharaoh who forced the Israelites to make
bricks without straw as living at Memphis, near where Cairo now
stands. The truth is, he had a great city there, but his capital and
favourite home was at Thebes, over four hundred and fifty miles
farther up the Nile valley. Thebes was one of the greatest cities of
antiquity. It covered almost as much ground as Paris does now and
is said to have had more than a million people. The metropolis had
walls so thick that chariots drawn by half-a-dozen horses abreast
could easily pass as they galloped along them. It had one hundred
gates, and temples and residences which were the wonder of the
world. Some of the houses were five stories high, the skyscrapers of
those days. The riches of Thebes were increased by the successful
wars which the kings waged with other nations. The monarchs of
that day had mighty armies of infantry and cavalry. Some of the
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

You might also like