100% found this document useful (3 votes)
117 views

Full Download Javascript Info Ebook Part 1 The JavaScript Language 1st Edition Ilya Kantor PDF

Kantor

Uploaded by

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

Full Download Javascript Info Ebook Part 1 The JavaScript Language 1st Edition Ilya Kantor PDF

Kantor

Uploaded by

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

Download the full version of the textbook now at textbookfull.

com

Javascript info Ebook Part 1 The JavaScript


language 1st Edition Ilya Kantor

https://textbookfull.com/product/javascript-info-
ebook-part-1-the-javascript-language-1st-edition-
ilya-kantor/

Explore and download more textbook at https://textbookfull.com


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

Javascript info Ebook Part 3 Additional articles 1st


Edition Ilya Kantor

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

textbookfull.com

Javascript info Ebook Part 2 Browser Document Events


Interfaces 1st Edition Ilya Kantor

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

textbookfull.com

JavaScript Learn JavaScript in 24 Hours or Less A Beginner


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

Knowledge Management Arts and Humanities Interdisciplinary


Approaches and the Benefits of Collaboration Meliha
Handzic
https://textbookfull.com/product/knowledge-management-arts-and-
humanities-interdisciplinary-approaches-and-the-benefits-of-
collaboration-meliha-handzic/
textbookfull.com
Programming Windows Store Apps with HTML CSS and
JavaScript Second Edition Kraig Brockschmidt

https://textbookfull.com/product/programming-windows-store-apps-with-
html-css-and-javascript-second-edition-kraig-brockschmidt/

textbookfull.com

50 Years of Urban Planning in Singapore Chye Kiang Heng

https://textbookfull.com/product/50-years-of-urban-planning-in-
singapore-chye-kiang-heng/

textbookfull.com

Fundamentals of Pathology Medical Course and Step 1 Review


2017 Edition Husain A. Sattar

https://textbookfull.com/product/fundamentals-of-pathology-medical-
course-and-step-1-review-2017-edition-husain-a-sattar/

textbookfull.com

Nate and Skye Fortis Security 7 5 1st Edition Maddie Wade

https://textbookfull.com/product/nate-and-skye-fortis-
security-7-5-1st-edition-maddie-wade/

textbookfull.com

Global Magic: Technologies of Appropriation from Ancient


Rome to Wall Street 1st Edition Alf Hornborg (Auth.)

https://textbookfull.com/product/global-magic-technologies-of-
appropriation-from-ancient-rome-to-wall-street-1st-edition-alf-
hornborg-auth/
textbookfull.com
Tease Me Dragons Love Curves 02 0 Sassy Ever After
Universe 49 0 1st Edition Aidy Award

https://textbookfull.com/product/tease-me-dragons-love-
curves-02-0-sassy-ever-after-universe-49-0-1st-edition-aidy-award/

textbookfull.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.
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
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.
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
⚠ 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
Random documents with unrelated
content Scribd suggests to you:
shadows parted and light came back to his intelligence, 15
he darted his blazing eyes cityward with restless vehemence,
and looked back from his car to the wide-stretching
town. Lo! there was a cone of fire spreading from story
to story and flaring to heaven: the flame was devouring
the turret which he had built himself of planks welded 20
together, put wheels beneath it, and furnished it with
lofty bridges. “Fate is too strong for me, sister, too
strong: hold me back no longer: we needs must follow
where Heaven and cruel Fortune are calling us. Yes, I
will meet Æneas: I will endure the full bitterness of 25
death: no more, my love, shall you see me disgraced:
suffer me first to have my hour of madness.” He said,
and in a moment leapt to the ground, rushes on through
foes, through javelins, leaves his sister to her sorrow, and
dashes at full speed through the intervening ranks. Even 30
as from a mountain’s top down comes a rock headlong,
torn off by the wind, or washed down by vehement rain,
or loosened by the lapse of creeping years; down the steep
it crashes with giant impulse, that reckless stone, bounding
over the ground and rolling along with it trees, herds, 35
and men: so, dashing the ranks apart, rushes Turnus to
the city walls, where the earth is wet with plashy blood,
and the gale hurtles with spears: he beckons with his
hand, and cries with a mighty voice: “Have done, ye
Rutulians! ye Latians, hold back your darts! whatever
Fortune brings she brings to me: ’tis juster far that I in
your stead should singly expiate the treaty’s breach and
try the issue of the steel.” All at the word part from the 5
midst, and leave him a clear space.

But father Æneas, hearing Turnus’ name, quits his


hold on the walls and the battlements that crown them,
flings delay to the winds and breaks off the work of war,
steps high in triumph, and makes his arms peal dread 10
thunder: vast as Athos, vast as Eryx, vast as father
Apennine himself, when he roars with his quivering holms[286]
and lifts his snowy crest exultingly to the sky. All turn
their eyes with eager contention. Rutulians, Trojans, and
Italians, those alike who were manning the towers and 15
those whose battering-rams were assailing the foundations.
All unbrace their armour. Latinus himself stands amazed
to see two men so mighty, born in climes so distant each
from each, thus met together to try the steel’s issue. At
once, when a space is cleared on the plain, first hurling 20
their spears, they advance with swift onset, and dash into
the combat with shield and ringing harness. Earth groans
beneath them; their swords hail blow on blow: chance
and valour mingle pell-mell. As when on mighty Sila or
Taburnus’ summit two bulls, lowering their brows for 25
combat, engage fiercely: the herdsmen retreat in dread:
the cattle all stand dumb with terror, the heifers wait in
suspense who is to be the monarch of the woodland,
whom the herds are to follow henceforth: they each in
turn give furious blows, push and lodge their horns, and 30
bathe neck and shoulders with streams of blood: the
sound makes the forest bellow again: with no less fury
Æneas the Trojan, and the Daunian chief clash shield on
shield: the enormous din fills the firmament. Jupiter
himself holds aloft his scales poised and level, and lays 35
therein the destinies of the two, to see whom the struggle
dooms, and whose the weight that death bears down.
Forth darts Turnus, deeming it safe, rises with his whole
frame on the uplifted sword, and strikes, Trojans and
eager Latians shout aloud: both armies gaze expectant.
But the faithless sword snaps in twain and fails its fiery
lord midway in the stroke, unless flight should come to
his aid. Off he flies swifter than the wind, seeing an unknown 5
hilt in his defenceless hand. Men say that in his
headlong haste, when first he was mounting the car harnessed
for battle, he left behind his father’s falchion and
snatched up the steel of Metiscus, his charioteer: so long
as the Teucrians fled straggling before him, the weapon 10
did good service; soon as it came to the divine Vulcanian
armour, the mortal blade, like brittle ice, flew asunder at
the stroke: the fragments sparkle on the yellow sand.
So now in his distraction Turnus flies here and there
over the plain, weaving vague circles in this place and in 15
that: for the Trojans have closed in circle about him,
and here is a spreading marsh, there lofty ramparts to
bar the way.

Nor is Æneas wanting, though at times the arrow


wound slackens his knees and robs them of their power 20
to run: no, he follows on, and presses upon the flier foot
for foot: as when a hound has got a stag pent in by a
river, or hedged about by the terror of crimson plumage,
and chases him running and barking: the stag, frighted
by the snare and the steep bank, doubles a thousand times: 25
the keen Umbrian clings open-mouthed to his skirts, all
but seizes him, and as though in act to seize, snaps his
teeth, and is baffled to find nothing in their gripe. Then,
if ever, uprises a shout, echoing along bank and marsh,
and heaven rings again with the noise. Turnus, even as 30
he flies, calls fiercely on the Rutulians, addressing by
name, and clamors for his well-known sword. Æneas,
for his part, threatens death and instant destruction,
should any come near, and terrifies his trembling foes,
swearing that he will raze their city to the ground, and 35
presses on in spite of his wound. Five times they circle
round, five times they retrace the circle: for no trivial
prize is at stake, no guerdon of a game: the contest is
for Turnus’ life, for his very heart’s blood. It chanced
that there had stood there a wild olive with its bitter
leaves, sacred to Faunus, a tree in old days reverenced by
seamen, where when saved from ocean they used to fasten
their offerings to the Laurentian god and hang up their 5
votive garments: but the unrespecting Trojans had lately
lopped the hallowed trunk, that the lists might be clear
for combat. There was lodged Æneas’ spear: thither its
force had carried it, and was now holding it fast in the
unyielding root. The Dardan chief bent over it, fain to 10
wrench forth the steel that his weapon may catch whom
his foot cannot overtake. Then cried Turnus in the
moment of frenzied agony: “Have mercy, I conjure thee,
good Faunus, and thou, most gracious earth, hold fast
the steel if I have ever reverenced your sanctities, which 15
Æneas’ crew for their part have caused battle to desecrate.”
He said, nor were his vows unanswered by heavenly aid.
Hard as he struggled, long as he lingered over the stubborn
stock, by no force could Æneas make the wood unclose
its fangs. While he strains with keen insistence, the 20
Daunian goddess, resuming the guise of charioteer Metiscus,
runs forward and restores to her brother his sword.
Then Venus, resenting the freedom taken by the presumptuous
Nymph, came nigh, and plucks the weapon
from the depth of the root. And now towering high, 25
with restored weapons and recruited force, this in strong
reliance on his sword, that fiercely waving his spear tall
as he, the two stand front to front in the breath-draining
conflict of war.

Meanwhile the king of almighty Olympus accosts Juno, 30


as from a golden cloud she gazes on the battle: “Where
is this to end, fair spouse? what last stroke have you in
store? you know yourself, by your own confession, that
Æneas has his place assured in heaven among Italia’s
native gods, that destiny is making him a ladder to the 35
stars. What plan you now? what hope keeps you seated
on those chilly clouds? was it right that mortal wound
should harm a god, or that Turnus—for what power
could Juturna have apart from you?—should receive
back his lost sword and the vanquished should feel new
forces? At length have done, and let my prayers bow
your will. Let this mighty sorrow cease to devour you
in silence: let me hear sounds of sullen disquiet less often 5
from your lovely lips. The barrier has been reached.
To toss the Trojans over land and sea, to kindle an unhallowed
war, to plunge a home in mourning, to blend a
dirge with the bridal song, this it has been yours to do:
all further action I forbid.” So spake Jupiter: and so in 10
return Saturn’s daughter with downcast look: “Even
because I knew, great Jove, that such was your pleasure,
have I withdrawn against my will from Turnus and from
earth: else you would not see me now in the solitude of
my airy throne, exposed to all that comes, meet or unmeet: 15
armed with firebrands, I should stand in the very
line of battle, and force the Teucrians into the hands of
their foes. As for Juturna, I counselled her, I own, to
succour her wretched brother, and warranted an unusual
venture where life was at stake: but nought was said of 20
aiming the shaft or bending the bow: I swear by the inexpiable
fountain-head of Styx, the one sanction that
binds us powers above. And now I yield indeed, and
quit this odious struggle. Yet there is a boon I would
ask, a boon which destiny forefends not. I ask it for 25
the sake of Latium, for the dignity of your own people:
when at last peace shall be ratified with a happy bridal,
for happy let it be: when bonds of treaty shall be knit
at last, let it not be thy will that the native Latians
should change their ancient name, become Trojans or 30
take the Teucrian style: let not them alter their language
or their garb. Let there be Latium still: let there be
centuries of Alban kings: let there be a Roman stock,
strong with the strength of Italian manhood: but let
Troy be fallen as she is, name and nation alike.” The 35
Father of men and nature answered with a smile: “Aye,
you are Jove’s own sister, the other branch of Saturn’s
line; such billows of passion surge in your bosom! but
come,—let this ineffectual frenzy give way: I grant your
wish, and submit myself in willing obedience. The
Ausonians shall keep their native tongue, their native
customs: the name shall remain as it is: the Teucrians
shall merge in the nation they join—that and no more: 5
their rites and worship shall be my gift: all shall be Latians
and speak the Latian tongue. The race that shall arise
from this admixture of Ausonian blood shall transcend in
piety earth and heaven itself, nor shall any nation pay
you such honours as they.” Juno nodded assent, and 10
turned her sullenness to pleasure; meanwhile she departs
from the sky, and quits the cloud where she sat.

This done, the sire meditates a further resolve, and


prepares to part Juturna from her brother’s side. There
are two fiends known as the Furies, whom with Tartarean 25
Megæra dismal Night brought forth at one and the same
birth, wreathing them alike with coiling serpents, and
equipping them with wings that fan the air. They are
seen beside Jove’s throne, at the threshold of his angry
sovereignty, goading frail mortality with stings of terror, 20
oft as the monarch of the gods girds himself to send forth
disease and frightful death, or appals guilty towns with
war. One of these Jove sped with haste from heaven’s
summit, and bade her confront Juturna in token of his
will. Forth she flies, borne earthward on the blast of a 25
whirlwind. Swift as the arrow from the string cleaves
the cloud, sent forth by Parthian—Parthian or Cydonian—tipped
with fell poison’s gall, the dealer of a wound
incurable, and skims the flying vapours hurtling and unforeseen,
so went the Daughter of Night and made her 30
way to earth. Soon as she sees the forces of Troy and
the army of Turnus, she huddles herself suddenly into the
shape of a puny bird, which oft on tombstone or lonely
roof sitting by night screams restlessly through the gloom;
in this disguise the fiend again and again flies flapping in 35
Turnus’ face, and beats with her wings on his shield. A
strange chilly terror unknits his frame, his hair stands
shudderingly erect, and his utterance cleaves to his jaws.
But when Juturna knew from far the rustling of those
Fury pinions, she rends, hapless maid, her dishevelled
tresses, marring, in all a sister’s agony, her face with her
nails, her breast with her clenched hands: “What now,
my Turnus, can your sister avail? what more remains for 5
an obdurate wretch like me? by what expedient can I
lengthen your span? can I face a portent like this? At
last, at last I quit the field. Cease to appal my fluttering
soul, ye birds of ill omen: I know the flapping of your
wings and its deathful noise; nor fail I to read great 10
Jove’s tyrannic will. Is this his recompense for lost virginity?
why gave he me life to last for ever? why was
the law of death annulled? else might I end this moment
the tale of my sorrows, and travel to the shades hand in
hand with my poor brother. Can immortality, can aught 15
that I have to boast give me joy without him? Oh, that
earth would but yawn deep enough, and send me down,
goddess though I be, to the powers of the grave!” So
saying, she shrouded her head in her azure robe, with many
a groan, and vanished beneath the river of her deity. 20

Æneas presses on, front to front, shaking his massy,


tree-like spear, and thus speaks in the fierceness of his
spirit: “What is to be the next delay? why does Turnus
still hang back? ours is no contest of speed, but of stern
soldiership, hand to hand. Take all disguises you can; 25
muster all your powers of courage or of skill: mount on
wing, if you list, to the stars aloft, or hide in the cavernous
depth of earth.” Shaking his head, he replied: “I quail
not at your fiery words, insulting foe: it is Heaven that
makes me quail, and Jove my enemy.” No more he 30
spoke: but, sweeping his eyes round, espies a huge stone,
a stone ancient and huge, which chanced to be lying on
the plain, set as some field’s boundary, to forefend disputes
of ownership: scarce could twelve picked men lift
it on their shoulders, such puny frames as earth produces 35
now-a-days: he caught it up with hurried grasp and
flung it at his foe, rising as he threw, and running rapidly,
as hero might. And yet all the while he knows not that
he is running or moving, lifting up or stirring the enormous
stone: his knees totter under him, and his blood
chills and freezes: and so the mass from the warrior’s
hand, whirled through the empty void, passed not through
all the space between nor carried home the blow. Even 5
as in dreams, at night, when heavy slumber has weighed
down the eyes, we seem vainly wishing to make eager
progress forward and midway in the effort fail helplessly;
our tongue has no power, our wonted strength stands not
our frames in stead, nor do words or utterance come at 10
our call: so it is with Turnus: whatever means his valour
tries, the fell fiend bars them of their issue. And now
confused images whirl through his brain: he looks to his
Rutulians and to the city, and falters with dread, and
quails at the threatening spear: how to escape he knows 15
not, nor how to front the foe, nor sees he anywhere his
car or the sister who drives it.

Full in that shrinking face Æneas shakes his fatal


weapon, taking aim with his eye, and with an effort of
his whole frame hurls it forth. Never stone flung from 20
engine of siege roars so loud, never peal so rending follows
the thunderbolt. On flies the spear like dark whirlwind
with fell destruction on its wing, pierces the edge of the
corslet, and the outermost circle of the seven-fold shield,
and with a rush cleaves through the thigh. Down with 25
his knee doubled under him comes Turnus to earth, all
his length prostrated by the blow. Up start the Rutulians,
groaning as one man: the whole mountain round
rebellows, and the depths of the forest send back the
sound far and wide. He in lowly suppliance lifts up eye 30
and entreating hand: “It is my due,” he cries, “and I
ask not to be spared it: take what fortune gives you.
Yet, if you can feel for a parent’s misery—your father,
Anchises was once in like plight—have mercy on Daunus’
hoary hairs, and let me, or if you choose my breathless 35
body, be restored to my kin. You are conqueror: the
Ausonians have seen my conquered hands outstretched:
the royal bride is yours: let hatred be pressed no further.”
Æneas stood still, a fiery warrior, his eyes rolling, and
checked his hand: and those suppliant words were working
more and more on his faltering purpose, when, alas!
the ill-starred belt was seen high on the shoulder, and
light flashed from the well-known studs—the belt of 5
young Pallas, whom Turnus conquered and struck down
to earth, and bore on his breast the badge of triumphant
enmity. Soon as his eyes caught the spoil and drank in
the recollection of that cruel grief, kindled into madness
and terrible in his wrath: “What, with my friend’s 10
trophies upon you, would you escape my hand? It is
Pallas, Pallas, who with this blow makes you his victim,
and gluts his vengeance with your accursed blood.”
With these words, fierce as flame, he plunged the steel into
the breast that lay before him. That other’s frame grows 15
chill and motionless, and the soul,[287] resenting its lot, flies
groaningly to the shades.
FOOTNOTES
[A] “Like footsteps upon wool.”—Tennyson, Œnone.
[B] Mr. Conington has missed a line, which may be rendered
thus: “who knowest the divine will of Apollo—his tripods and his
laurels.”—[E. S. S.]
[C] Another line omitted in the translation:—“huge as Greek
shield or sun-god’s torch.”—[E. S. S.]
[D] A caret in the Ms. notes the omission of Urbis opus: “A city
in itself.”—[E. S. S.]
[E] Three lines omitted in the Ms.: “Then on Mount Eryx,
towering to the stars, is reared a temple to Idalian Venus, and for
Anchises’ tomb a priest appointed, with dedication of broad-acred
grove.”—[E. S. S.]
[F] For the omitted lines Conington’s verses are inserted.—[E.
S. S.]
NOTES
BOOK I
1:1. Arms and the man I sing. Compare the following opening
lines of great epics:—
“O goddess, sing the wrath of Peleus’ son,
Achilles; sing the deadly wrath that brought
Woes numberless upon the Greeks.”

—Iliad, Bryant’s Trans.

“Tell me, O muse, of that sagacious man


Who, having overthrown the sacred town
Of Ilium, wandered far and visited
The capitals of many nations, learned
The customs of their dwellers, and endured
Great sufferings on the deep.”

—Homer, Odyssey.

“Of love and ladies, knights and arms, I sing,


Of courtesies and many a daring feat.”

—Ariosto, Orlando Furioso.

“I sing the pious arms and chief, who freed


The Sepulchre of Christ from thrall profane;
Much did he toil in thought and much in deed,
Much in the glorious enterprise sustain.”

—Tasso, Jerusalem Delivered.

“Of man’s first disobedience, and the fruit


Of that forbidden tree, whose mortal taste
Brought death into the world, and all our woe,
...
Sing, heavenly muse.”
—Milton, Paradise Lost.

“I, who erewhile the happy garden sung,


By one man’s disobedience lost, now sing
Recovered Paradise to all mankind,
By one man’s firm obedience.”

—Milton, Paradise Regained.

1:1. Troy. A city in northwest Asia Minor where the famous Trojan
war took place.
1:3. Latian. The broad plain near the mouth of the Tiber, in Italy.
1:5. Juno. Queen of the gods; wife and sister of Jupiter.
1:5. Much.
“Much there he suffered,
And many perilles past in forreine landes,
To save his people sad from victours vengefull handes,”

—Spenser, Faerie Queene.

1:8. Alba. Alba Longa, a long ridge some fifteen miles southeast
of Rome. The successors of Æneas reigned there until the founding
of Rome.
1:10. Muse. One of the nine Muses. Greek and Latin poets often
profess to be merely the mouthpiece of the Muses.
1:14. Hate.
“And in soft bosoms dwell such mighty rage?”

—Pope, Rape of the Lock.

“In heavenly spirits could such perverseness dwell?”

—Milton, Paradise Lost.

1:17. Tyre. Carthage was sprung from Tyre, an old and


prosperous city on the coast of Phœnicia. The founders of Carthage
and their descendants are termed indifferently by Virgil Phœnicians,
Sidonians, Pœni, or Tyrians.
1:19. War’s.
“An old and haughty nation proud in arms.”

—Milton, Comus.

1:21. Samos. A large island off the west coast of Asia Minor. Here
were the most ancient temple and worship of Juno, here she was
nurtured, and here she was married to Jupiter.
1:28. Libya. North Africa.
2:1. Fate’s.
“Those three fatall Sisters, whose sad hands
Doo weave the direful threads of destinie
And in their wrath brake off the vitall bands.”

—Spenser, Daphnaïda.

“Comes the blind Fury with the abhorred shears


And slits the thin-spun life.”

—Milton, Lycidas.

“Sad Clotho held the rocke [distaff], the whiles the thrid
By griesly Lachesis was spun with paine,
That cruell Atropos eftsoones undid,
With cursed knife cutting the twist in twaine.”

—Spenser, Faerie Queene.

2:1. Saturn. An ancient Italian god of agriculture, identified later


with the Greek god Cronos.
2:3. Argos. A city of Argolis in the Peloponnesus. One of Juno’s
favorite cities. Juno’s love for Argos played the same part in the
Trojan war as her regard for Carthage plays in the Æneid. It is used
here poetically for the name of the people, i.e. = Greeks.
2:6. Paris. A son of Priam, king of Troy, who eloped with Helen
and caused the Trojan war. The judgment was the award of the
golden apple, prize of beauty, to Venus as against Juno and Minerva.
“Here eke that famous golden apple grew,
The which emongest the gods, false Ate threw;
For which th’ Idæan Ladies disagreed,
Till partiall Paris dempt it Venus dew,
And had of her fayre Helen for his meed.”

—Spenser, Faerie Queene.

In Tennyson’s Œnone, Juno offers—


“from all neighbor crowns
Alliance and allegiance till thy hand
Fail from the sceptre-staff.”

And Minerva—
“Self-reverence, self-knowledge, self-control.”

But Venus—
“I promise thee
The fairest and most loving wife in Greece.”

2:9. Ganymede. A Trojan prince; was carried off to Olympus by


Jupiter’s eagle. He was made cup-bearer to the gods in place of
Hebe, daughter of Juno.
“And godlike Ganymede, most beautiful
Of men; the gods beheld and caught him up
To heaven, so beautiful was he, to pour
The wine to Jove, and ever dwell with them.”

—Homer, Iliad.

“flushed Ganymede, his rosy thigh


Half-buried in the Eagle’s down,
Sole as a flying star shot thro’ the sky
Above the pillar’d town.”
—Tennyson, Palace of Art.
2:10. Danaan. Greek. Danaus, an ancient city of Argos.
Conington transliterates various proper names, such as Argives,
Achæans, Pelasgians, all meaning Greeks. Vergil uses the originals
now to secure variety, now to meet the metrical requirement.
2:11. Achilles. Son of Peleus, king of Thessaly, and Thetis, a sea
nymph, chief champion of the Greeks before Troy.
2:22. Teucrians. Teucer, an ancient king of Troy; he came to Troy
from Crete. He was father-in-law of Dardanus, and is often called
founder of the Trojans.
2:23. Pallas. Epithet of the Greek goddess Athena. Sometimes
identified with the Latin goddess of wisdom, Minerva.
2:26. Ajax. Oïleus’ son. Had, on the night Troy was taken,
assaulted Priam’s daughter Cassandra, who had taken refuge in
Minerva’s temple.
2:27. Jove. Jupiter, chief of the Olympian gods. Son of Cronos or
Saturnus. He is father omnipotent, father of gods, and king of men.
The lightning and the thunderbolt, fashioned for him by Vulcan, are
his weapons. The eagle is his messenger. Apparently Jupiter, the
Sky-father, is the personification of the sky. Cicero quotes Ennius as
follows: “This shining vault on high which all men call upon in prayer
as Jupiter.”
2:30. Rock’s.
“caught in a fierce tempest shall be hurled
Each on his rock transfixed, the sport and prey
Of rocking whirlwinds.”

—Milton, Paradise Lost.

2:38. Æolia. Home of the winds,—Lipara. One of the Æolian


islands north of Sicily.
2:38. Cavern.
“In a cavern under is fettered the thunder,
It struggles and howls by fits.”

—Shelley, The Cloud.

2:38. Æolus. King of the winds.


3:2. Bond.
“And wild winds bound within their cell.”

—Tennyson, Mariana.

3:19. Tyrrhene sea. Also Tuscan sea; the part of the


Mediterranean which extended from Liguria to Sicily.
3:19. Ilion. Troy.
3:30. Bidding.
“Father eternal, thine is to decree;
Mine, both in heaven and earth, to do thy will.”

—Milton, Paradise Lost.

3:36. Rush forth.


“Nor slept the winds
Within their stormy caves, but rushed abroad
From the four hinges of the world, and fell
On the vexed wilderness.”

—Milton, Paradise Lost.

“With howling sound, high carnival to keep,


And in wild uproar all embroil both land and deep.”

—Tasso, Jerusalem Delivered.

“Then forth it breakes, and with his furious blast


Confounds both land and seas, and skyes doth overcast.”

—Spenser, Faerie Queene.

3:38. Fall.
“The winds, as at their hour of birth,
Leaning upon the ridged sea.”

—Tennyson.

4:5. Daylight.
“And tosse the deepes, and teare the firmament,
And all the world confound with wide uprore.”

—Spenser, Faerie Queene.

“The clouds their gloomy veil above them strain,


Nor suffer sun or star to cheer the view.
...
While aye descending night, with deeper shade,
The vext and fearful billows overlayed.”

—Ariosto, Orlando Furioso.

4:9. Æneas. Son of Venus and Anchises, hero of the Æneid.


4:9. Chilled.
“His bold Æneas on like billows tossed
In a tall ship, and all his country lost
Dissolves with fear; and, both his hands upheld,
Proclaims them happy when the Greeks had quelled
In honorable fight.”

—Waller, Of the Dangers his Majesty Escaped.

4:12. Thrice.
“Thrice happy, four times happy, they who fell
On Troy’s wide field warring for Atreus’ sons:
O, had I met my fate and perished there.”

—Homer, Odyssey.

4:14. Tydeus’ son. Diomedes, with whom Æneas had fought in


single combat and been saved by direct intervention of Venus.
4:16. Hector. Son of Priam, king of Troy, and Hecuba. Hector was
the bravest champion of Troy, and was slain by Achilles.
4:17. Æacides. A descendant of Æacus (king of Ægina and father
of Peleus). Virgil applies the name to (1) Achilles, (2) Pyrrhus, son of
Achilles, (3) Perseus, king of Macedonia.
4:18. Sarpedon. Son of Jupiter, and king of the Lycians; an ally of
Troy slain by Patroclus, friend of Achilles.
4:18. Simois. The famous river that flows by Troy.
“And Simoïs, in whose bed lay many shields
And helms and bodies of slain demigods.”

—Homer, Iliad.

4:23. Stars. Hyperbole; cf.—


“The chidden billow seems to pelt the clouds;
The wind-shaked surge, with high and monstrous mane,
Seems to cast water on the burning Bear
And quench the guards of the ever-fixed pole.”

—Shakespeare, Othello.

4:26. Crest.
“Now quivering o’er the topmost waves she rides
While deep beneath the enormous gulf divides:
Now launching headlong down the horrid vale,
Becalmed she hears no more the howling gale.”

—Falconer, Shipwreck.

4:33. Syrtes. Two shallow bays on the north coast of Africa


distinguished as Major and Minor,—dangerous to navigation.
5:8. Side-jointings.
“The chinks suck destruction. The heavy dead hulk
On the living sea rolls an inanimate bulk.”

—Shelley, Vision of the Sea.


“The sides convulsive shook on groaning beams,
And, rent with labour, yawn’d their pitchy seams.”

—Falconer, Shipwreck.

5:11. Neptune. God of the sea,—brother of Juno.


5:22. Confound.
“I heard the wrack,
As earth and sky would mingle.”

—Milton, Paradise Lost.

“While oft in whirls the mad tornado flies,


Mingling the ravaged landscape with the skies.”

—Goldsmith, Deserted Village.

5:29. Eurus. The east wind. It is the poet’s way to single out one
wind and use it as general word for winds. One example of the use
of the specific for the generic.
5:33. Routs.
“Thou frownest, and old Æolus thy foe
Skulks to his cavern, ’mid the gruff complaint
Of all his rebel tempests. Dark clouds faint
When, from thy diadem, a silver gleam
Slants over blue dominion.”

—Keats, Endymion.

5:34. Cymothoë and Triton. Lesser sea deities.


“From thy dead lips a clearer note is born
Than ever Triton blew from wreathèd horn.”

—Holmes, Chambered Nautilus.

5:37. Trident.
“It seem’d as there the British Neptune stood,
With all his hosts of waters at command,
Beneath them to submit th’ officious flood;
And with his trident shov’d them off the sand.”

—Dryden, Annus Mirabilis.


6:4. Weapon.
“Rage prompted them at length, and found them arms
Against such hellish mischief fit to oppose.”

—Milton, Paradise Lost.

6:15. Haven.
“It was a still
And calmy bay, on the one side sheltered
With the brode shadow of an hoarie hill;
On th’ other side an high rock towred still,
That twixt them both a pleasaunt port they made,
And did like an halfe theatre fulfill.”

—Spenser, Faerie Queene.

“And overhead upgrew


Insuperable height of loftiest shade,
Cedar, and pine, and fir, and branching palm,
A sylvan scene, and as the ranks ascend
Shade above shade, a woody theatre
Of stateliest view.”

—Milton, Paradise Lost.

“Its uplands sloping deck the mountain’s side,


Woods over woods in gay theatric pride.”

—Goldsmith, Traveller.

“In one they find a lone sequestered place,


Where, to a crescent curved, the shore extends
Two moony horns, that in their sweep embrace
A spacious bay,—a rock the port defends;
Inward it fronts, and broad to ocean bends
Its back, whereon each dashing billow dies,
When the wind rises and the storm descends;
While here and there two lofty crags arise,
Whose towers, far out at sea, salute the sailor’s eyes.
Safe sleep the silent seas beneath; above,
Black arching woods o’ershade the circled scene:
Within, a grotto opens, in the grove,
Pleasant with flowers, with moss, with ivies green,
And waters warbling in the depths unseen;
Needed nor twisted rope nor anchor there
For weary ships.”

—Tasso, Jerusalem Delivered.


6:25. Cable.
“And there is a safe haven where no need
Of cable is; no anchor there is cast,
Nor hawsers fastened to the strand.”

—Homer, Odyssey.

7:3. Biremes. Ships having two tiers of oars.


7:23. Scylla. A sea-monster, residing in a cave in certain rocks,
also called Scylla, between Italy and Sicily. The upper part of this
monster resembled a lovely woman. About the waist was a circle of
dogs or wolves; below was the tail of a dolphin. The wolves reach
out and seize passing ships and drag them on the rocks. Virgil’s
Scylla is adopted by Milton as a description of one of the monsters
guarding the gates of Hell.
7:25. Cyclops. Certain giants of cannibal nature who dwelt in
Sicily near Ætna. They had a single large round eye in the middle of
the forehead.
7:27. Remembered.
“A time will come, not distantly descried,
When to remember ev’ry past dismay
Will be no less a pleasure than a pride;
Hold then courageous on, and keep, I pray,
Your noble hearts in cheer for that victorious day.”

—Tasso, Jerusalem Delivered.


7:33. Heart-sick.
“So spoke the apostate angel, though in pain,
Vaunting aloud, but racked with deep despair.”

—Milton, Paradise Lost.

8:15. Ether.
“Now had the Almighty Father from above,
From the pure empyrean where he sits
High throned above all highth, bent down his eye,
His own works and their works at once to view.”

—Milton, Paradise Lost.

8:26. Barred.
“In vain—for rude adversity’s command
Still, on the margin, of each famous land,
With unrelenting ire his steps opposed,
And every gate of hope against him closed.”

—Falconer, Shipwreck.

8:37. Antenor. Nephew of Priam. After the capture of Troy, he


sailed up the Adriatic Sea, established a new people called the
Veneti, and founded Patavium (Padua).
9:8. Arms.
“And in thy tempul I wol my banur hong,
And all the armes of my companye.”

—Chaucer, Knight’s Tale.

“In my heart’s temple I suspend to thee


These votive wreaths of withered memory.”

—Shelley, Epipsychidion.

9:13. Piety.
“False Jupiter, rewardst thou virtue so?
What, is not piety exempt from woe?”

—Marlowe and Nash, Dido.


9:18. Cythera. An island south of Laconia, near which, the
tradition is, Venus rose from the foam of the sea.
9:20. Lavinium. A city of Latium, represented as founded by
Æneas and named by him for his wife Lavinia, daughter of King
Latinus. It was Latinus’ promise of Lavinia to Æneas that caused the
wars of the last six books of the Æneid.
9:29. Rutulians. A Volscian people whose chief city was Antium.
They with their King Turnus were the chief antagonists of Æneas
when he was trying to settle in Italy.
9:30. Ascanius. Son of Æneas.
9:36. Hector’s.
“There in stout Hector’s race three hundred years
The Roman sceptre royal shall remain.”

—Marlowe and Nash, Dido.

10:11. Assaracus. A Trojan king of Phrygia; he was grandfather


of Anchises, hence the expression “house of Assaracus” means the
descendants of Æneas. And as the Julian clan was thought to be
derived from Iulus, Æneas’ son, this included Julius Cæsar and his
adopted son Augustus.
10:11. Phthia. A city and district in Thessaly, Greece, over which,
it is said, Achilles ruled.
10:12. Mycenæ. A famous city ruled by Agamemnon, in the
Morea (southern Greece).
10:12. Argos. A city of Argolis, in the Peloponnesus. One of
Juno’s favorite cities. So fate wills that the descendants of the
Trojans shall take vengeance for the destruction of Troy on the
descendants of the great Greek leaders.
10:15. Stars.
“He shall ascend
The throne hereditary, and bound his reign
With Earth’s wide bounds, his glory with the heavens.”

—Milton, Paradise Lost.

10:19. War.
“All loved virtue, no man was affray’d
Of force, ne fraud in wight was to be found:
No warre was known, no dreadfull trompets sound;
Peace universall rayn’d mongst men and beasts.”

—Spenser, Faerie Queene.

“No war, or battle’s sound


Was heard the world around;
The idle spear and shield were high up hung;
The hookèd chariot stood,
Unstained with hostile blood;
The trumpet spake not to the armèd throng,
And kings sat still with awful eye,
As if they surely knew their sovran Lord was by.”

—Milton, Hymn on Nativity.

10:20. Vesta. Goddess of the hearth.


10:20. Quirinus. Name given to Romulus after he was translated
from earth to heaven. Romulus, the legendary founder of Rome.
Cicero tells us that after his translation, Romulus appeared on the
Quirinal Hill and stated that his name as god was Quirinus, and gave
instructions that a temple should be erected to him on that hill—
hence the name of the hill and the palace, once home of the popes,
now of the monarchs of Italy.
10:26. Son of Maia. Mercury, swift-winged messenger of the
gods.
“The Sonne of Maia, soone as he receiv’d
That word, streight with his azure wings he cleav’d
The liquid clowdes, and lucid firmament;
Ne staid, till that he came with steep descent
Unto the place where his prescript did showe.”

—Spenser, Mother Hubbard’s Tale.


10:28. Dido. Daughter of Belus, king of Tyre; widow of Sychæus.
According to story, she led the Phœnician colony to Carthage.
10:33. Punic. Carthaginian. So the three Punic wars of Rome
against Carthage.
11:17. Ho.
“Ho, young men! saw you, as you came,
Any of all my sisters wandering here,
Having a quiver girded to her side,
And clothed in a spotted leopard’s skin?”

—Marlowe and Nash, Dido.

11:26. Goddess.
“Most sure, the goddess
On whom these airs attend! Vouchsafe my prayer
May know if you remain upon this island.”

—Shakespeare, Tempest.

11:27. Phœbus’ sister. Diana, sister of Phœbus Apollo.


12:1. Agenor. Twin brother of Belus and founder of Sidon, from
whom Dido was descended.
12:18. Hope.
“Poor girl! put on thy stifling widow’s weed,
And ’scape at once from Hope’s accursed bands,
To-day thou wilt not see him, nor to-morrow,
And the next day will be a day of sorrow.”

—Keats, Isabella.

12:33. Woman. “Dux femina facti,”—motto on the medal in 1588,


in honor of Elizabeth’s victories over the Spanish Armada. Cf.
Kingsley’s Westward Ho!
12:36. Byrsa. A word which in the Carthaginian language meant
citadel, but sounded like a Greek word meaning bull’s hide. From this
confusion, apparently, arose the story that Dido cut a bull’s hide into
very thin strings and so encompassed much ground for her new city.
13:24. Breath of life.
“So drew mankind in vain the vital air,
Unformed, unfriended by those kindly cares,
That health and vigor to the soul impart.”

—Gray, Education and Government.

13:31. Jove.
“The bird of Jove, stooped from his airy tour.
Two birds of gayest plume before him drove.”

—Milton, Paradise Lost.

13:36. Wings.
“Around, around in ceaseless circles wheeling
With clang of wings and scream, the eagle sailed.”

—Shelley, The Revolt of Islam.

“Whilst with their clang the air resounds.”

—Wordsworth, Excursion.

14:6. Walk.
“In gliding state she wins her easy way.”

—Gray, Progress of Poesy.

14:18. Paphos. A city in Cyprus.


14:20. Sabæan incense. Arabian frankincense.
“Sabean odoures, from the spicy shore
Of Arabie the blest.”
—Milton, Paradise Lost.
14:37. Bees.
“All hands employ’d the royal work grows warm:
Like labouring bees on a long summer’s day.
Some sound the trumpet for the rest to swarm,
And some on bells of tasted lilies play;
With glewy wax some new foundation lay
Of virgin combs, which from the roof are hung;
Some arm’d within doors upon duty stay,
Or tend the sick, or educate the young.”

—Dryden, Annus Mirabilis.

15:18. Sidon. Tyre and Sidon were the chief cities of Phœnicia.
Adjectives formed from them are used interchangeably with
Phœnician and Carthaginian for the sake of variety or to meet
metrical requirements.
15:37. Tears.
“Yet tears to human suffering are due;
And mortal hopes defeated and o’erthrown
Are mourned by man.”

—Wordsworth, Laodamia.

“The Virgilian cry,


The sense of tears in mortal things.”

—Matthew Arnold, Geist’s Grave.

“Thou majestic in thy sadness at the doubtful doom of human kind.”

—Tennyson.

16:4. Pergamus. Troy.


16:12. Xanthus. A river near Troy.
16:13. Troilus. Shakespeare’s Troilus draws plot from Chaucer.
16:19. Pallas. Minerva, goddess of wisdom, friend of the Greeks.
16:32. Memnon. Leader of the Æthiopian allies of Troy. Was son
of Tithonus and Aurora.
16:33. Penthesilea. Queen of the Amazons who fought for Troy.
Achilles slew both Memnon and Penthesilea.
17:6. Diana.
“Such as Diana by the sandy shore
Of swift Eurotas, or on Cynthus greene,
Where all the nymphs have her unwares forlore [left],
Wandreth alone with bow and arrowes keene,
To seeke her game.”

—Spenser, Faerie Queene.

17:9. Latona. Mother of Apollo and Diana. The type of perfect


mother love.
18:10. Orion. A hunter famous in ancient myth, armed with belt
and sword, translated to the heavens as a constellation, thought to
bring storms.
19:36. Shone.
“When sea-born Venus guided o’er
Her warrior to the Punic shore,
Around that radiant head she threw
In deep’ning clouds ambrosial dew:
But when the Tyrian queen drew near,
The light pour’d round him fresh and clear.”

—Landor.

“Not great Æneas stood in plainer day,


When, the dark mantling mist dissolved away,
He to the Tyrians showed his sudden face,
Shining with all his goddess mother’s grace:
For she herself had made his countenance bright,
Breathed honor on his eyes, and her own purple light.”

—Dryden, Britannia Rediviva.

20:4. Enchased.
“Like to a golden border did appeare,
Framed in goldsmithes forge with cunning hand.”

—Spenser, Faerie Queene.

21:9. Learning.
“Who by the art of known and feeling sorrows,
Are pregnant to good pity.”

—Shakespeare, King Lear.

“What sorrow wast thou had’st her know,


And from her own she learned to melt at others’ woe.”

—Gray, Hymn to Adversity.

21:30. Acanthus. A plant now called bear’s-foot, or bear’s-


breech; grows in southern Europe, Asia Minor, and India. Its leaf was
a common form in embroidery and sculpture, and is well known from
its use in the Corinthian capital.
21:31. Helen. Most beautiful of women, daughter of Jupiter and
Leda, was wife of Menelaus of Sparta. She was carried off by Paris
as Venus’ reward to him for his decision in her favor in the question
of the Golden Apple. This breach of hospitality by Paris was the
cause of the Trojan war.
22:1. Cupid. Son of Venus; god of love.
22:10. Typhœan. Thunderbolts of Jove, called Typhœan because
they slew the giant Typhœus at the time of the great fight for the
throne of heaven between Jupiter and the Olympian gods and “the
earth-born Titan brood.”
“Phœbus resigns his darts, and Jove
His thunder to the god of love.”

—Denham, Friendship.

22:38. Poison.
“Through her bones the false instilled fire
Did spred it selfe and venime close inspire.”

—Spenser, Faerie Queene.


23:4. Slumber.
“She sent the gentle sleep from Heaven
That slid into my soul.”

—Coleridge, Ancient Mariner.

23:29. Gazing.
“And her eyes on all my motions with a mute observance hung.”

—Tennyson, Locksley Hall.

23:35. Lap.
“But both Dione honored they and Cupid,
That as her mother, this one as her son,
And said that he had sat in Dido’s lap.”

—Dante, Paradiso.

24:6. Lamps.
“As heaven with stars, the roof with jewels glows,
And ever-living lamps depend in rows.”

—Pope, Temple of Fame.

24:15. Bacchus. Son of Jupiter and Semele, god of wine, and, by


metonymy, used to mean wine. (Name of god for his realm, as
Vulcan for fire, etc.).
“Nor the coy maid, half willing to be prest,
Shall kiss the cup to pass it to the rest.”

—Goldsmith, Deserted Village.

24:25. Atlas. A king of Mauretania; father of the Pleiades; he


supported the heavens on his shoulders. He was skilled in
astronomy. Personification of Mount Atlas.

You might also like