(Ebook) Javascript.info Ebook Part 1 The JavaScript language by Ilya Kantor, javascript.info download pdf
(Ebook) Javascript.info Ebook Part 1 The JavaScript language by Ilya Kantor, javascript.info download pdf
com
https://ebooknice.com/product/javascript-info-ebook-
part-1-the-javascript-language-10437690
DOWLOAD EBOOK
https://ebooknice.com/product/javascript-info-ebook-part-3-additional-
articles-10437696
ebooknice.com
https://ebooknice.com/product/javascript-info-ebook-part-2-browser-
document-events-interfaces-10437692
ebooknice.com
ebooknice.com
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
ebooknice.com
https://ebooknice.com/product/play-1-b3-the-nimzo-larsen-attack-a-
friend-for-life-1759514
ebooknice.com
https://ebooknice.com/product/how-to-draw-comics-by-ilya-48681814
ebooknice.com
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?
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”.
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.
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.
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.
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.
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.
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.
Modern tools make the transpilation very fast and transparent, actually allowing developers to
code in another language and auto-converting it “under the hood”.
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.
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.
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.
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
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.
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.
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 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
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 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.
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.
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" .
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>
<script>
alert( 'Hello, world!' );
</script>
</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:
<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
<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.
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.2.0/lodash.js"></script>
<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.
A single <script> tag can’t have both the src attribute and code inside.
<script src="file.js">
alert(1); // the content is ignored, because src is set
</script>
<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
Do it in a sandbox, or on your hard drive, doesn’t matter, just ensure that it works.
To solution
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.
To solution
Code structure
The first thing we’ll study is the building blocks of code.
Statements
We can have as many statements in our code as we want. Statements can be separated with a
semicolon.
alert('Hello'); alert('World');
Usually, statements are written on separate lines to make the code more readable:
alert('Hello');
alert('World');
Semicolons
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:
[1, 2].forEach(alert)
Now if we run the code, only the first alert is shown and then we have an error!
[1, 2].forEach(alert)
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:
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.
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:
Multiline comments start with a forward slash and an asterisk /* and end with an
asterisk and a forward slash */ .
Like this:
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 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.
“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";
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.
alert("some code");
// "use strict" below is ignored--it must be at the top
"use strict";
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:
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...
})()
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.
A variable
A variable is a “named storage” for data. We can use variables to store goodies, visitors, and
other data.
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;
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!
That might seem shorter, but we don’t recommend it. For the sake of better readability, please
use a single line per variable.
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 :
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:
let message;
message = 'Hello!';
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;
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
1. The name must contain only letters, digits, or the symbols $ and _ .
2. The first character must not be a digit.
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.
alert($ + _); // 3
Examples of incorrect variable names:
Case matters
Variables named apple and AppLE are two different variables.
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.
alert(num); // 5
"use strict";
Constants
Variables declared using const are called “constants”. They cannot be changed. An attempt
to do so would cause an error:
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.
For instance, let’s make constants for colors in so-called “web” (hexadecimal) format:
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:
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.
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.
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.
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
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.
ebooknice.com