Javascript info Ebook Part 1 The JavaScript language 1st Edition Ilya Kantor download
Javascript info Ebook Part 1 The JavaScript language 1st Edition Ilya Kantor download
https://textbookfull.com/product/javascript-info-ebook-
part-1-the-javascript-language-1st-edition-ilya-kantor/
https://textbookfull.com/product/javascript-info-ebook-
part-3-additional-articles-1st-edition-ilya-kantor/
https://textbookfull.com/product/javascript-info-ebook-
part-2-browser-document-events-interfaces-1st-edition-ilya-
kantor/
https://textbookfull.com/product/functional-programming-in-
javascript-how-to-improve-your-javascript-programs-using-
functional-techniques-1-edition-edition-luis-atencio/
JavaScript Design Patterns 1 / converted Edition Hugo
Di Francesco
https://textbookfull.com/product/javascript-design-
patterns-1-converted-edition-hugo-di-francesco/
https://textbookfull.com/product/the-joy-of-javascript-1st-
edition-atencio/
https://textbookfull.com/product/practical-modern-javascript-
dive-into-es6-and-the-future-of-javascript-nicolas-bevacqua/
https://textbookfull.com/product/beginning-functional-javascript-
functional-programming-with-javascript-using-ecmascript-6-1st-
edition-anto-aravinth/
https://textbookfull.com/product/simplifying-javascript-writing-
modern-javascript-with-es5-es6-and-beyond-1st-edition-joe-morgan/
Part 1
The JavaScript
language
Ilya Kantor
Built at July 10, 2019
The last version of the tutorial is at https://javascript.info.
We constantly work to improve the tutorial. If you find any mistakes, please write at our github.
● An introduction
●
An Introduction to JavaScript
●
Manuals and specifications
● Code editors
●
Developer console
● JavaScript Fundamentals
● Hello, world!
● Code structure
●
The modern mode, "use strict"
● Variables
●
Data types
● Type Conversions
●
Operators
● Comparisons
●
Interaction: alert, prompt, confirm
●
Conditional operators: if, '?'
●
Logical operators
●
Loops: while and for
●
The "switch" statement
●
Functions
● Function expressions and arrows
● JavaScript specials
● Code quality
● Debugging in Chrome
● Coding Style
● Comments
●
Ninja code
● Automated testing with mocha
● Polyfills
●
Objects: the basics
●
Objects
● Garbage collection
● Symbol type
●
Object methods, "this"
● Object to primitive conversion
● Constructor, operator "new"
●
Data types
● Methods of primitives
● Numbers
● Strings
●
Arrays
● Array methods
● Iterables
●
Map, Set, WeakMap and WeakSet
●
Object.keys, values, entries
● Destructuring assignment
● Date and time
●
JSON methods, toJSON
● Advanced working with functions
● Recursion and stack
● Rest parameters and spread operator
● Closure
● The old "var"
● Global object
● Function object, NFE
● The "new Function" syntax
● Scheduling: setTimeout and setInterval
●
Decorators and forwarding, call/apply
● Function binding
● Currying and partials
●
Arrow functions revisited
● Object properties configuration
● Property flags and descriptors
●
Property getters and setters
● Prototypes, inheritance
● Prototypal inheritance
● F.prototype
● Native prototypes
● Prototype methods, objects without __proto__
● Classes
● Class basic syntax
● Class inheritance
● Static properties and methods
● Private and protected properties and methods
● Extending built-in classes
●
Class checking: "instanceof"
● Mixins
● Error handling
●
Error handling, "try..catch"
● Custom errors, extending Error
● Promises, async/await
● Introduction: callbacks
● Promise
● Promises chaining
● Error handling with promises
● Promise API
● Promisification
● Microtasks
● Async/await
● Generators, advanced iteration
●
Generators
● Async iterators and generators
● Modules
●
Modules, introduction
● Export and Import
● Dynamic imports
●
Miscellaneous
●
Proxy and Reflect
● Eval: run a code string
Here we learn JavaScript, starting from scratch and go on to advanced concepts like OOP.
We concentrate on the language itself here, with the minimum of environment-specific notes.
An introduction
About the JavaScript language and the environment to develop with it.
An Introduction to JavaScript
Let’s see what’s so special about JavaScript, what we can achieve with it, and which other
technologies play well with it.
What is JavaScript?
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
The women didn't come back soon, and when they did Cameron
wasn't sure that the weird creature that floated into the control
compartment with Nona was Anti. He looked again and saw
shudderingly what she had done to herself. "You do need
psychotherapy," he said bitingly. "When we get back it's the first
thing I'll recommend. Can't you understand how fool-hardy you're
being?"
"Be quiet," growled Jordan. "Anti, explain what you've rigged up. I'm
not sure we can let you do it."
"Any kind of pressure will do as far as the outside of the body is
concerned," answered Anti, flipping back the helmet. "Mechanical
pressure is as satisfactory as air. I had Nona cut the spacesuit in
strips and wind them around me, very hard. That will keep me from
squishing out. Then I found a helmet that would cover my head
when the damaged part was cut away. It won't hold much air
pressure even taped tight to my skin. It doesn't have to as long as
it's pure oxygen."
"So far it makes sense," admitted Docchi. "But what can you do
about temperature?"
"Do you think I'm going to worry about cold?" asked Anti. "Me? Way
down below all this flesh? Mountains and mountains of it?"
"I've heard enough," said Cameron, standing in front of Anti. "Now
listen to me. Stop this nonsense and take off that childish rig. I can't
permit you to ruin my career by deliberate suicide."
"You and your stinking career," said Jordan disgustedly. "You don't
know what success is and what it means to give it up. Stay out of
this. We don't have to ask your permission to do anything." Cameron
retreated from the toaster and Jordan turned to Anti. "Do you
understand what the risk, is, Anti? You know that it may not work at
all?"
"I've thought about it," said Anti. "On the other hand I've thought
about the asteroid. I don't want to go back."
"We should have viewers outside," said Docchi. "One directly in
back, one on each side. At least we'll know what's happening."
At the control panel Jordan began flipping levers. "They're out and
working," he said at last. "Anti, go to the freight ramp. Close your
helmet and wait. I'll let the air out slowly. If everything doesn't work
perfectly let me know on the helmet radio and I'll yank you in
immediately. Once you're outside I'll give you further instructions.
You'll find the tools and equipment that opens to space."
Anti waddled away. Huge, but she wasn't any bigger than her
determination.
Once she was gone Jordan looked down at his legless body. "I hate
to do this but we've got to be realistic about it."
"It's the only way we've got a chance," answered Docchi. "Anti's the
only one who can do the job. And I think she'll survive."
Jordan adjusted a dial. "Cameron had better hope she will," he
muttered. "He'll join her if she doesn't."
Docchi glanced hastily at the screen. Anti was hanging free in space,
wrapped and strapped in strips torn from the supposedly useless
spacesuits. And she was also enclosed in more flesh than any human
had borne. The helmet was taped jauntily to her head and the
oxygen cylinder was fastened to her back. And she lived.
"How is she?" he asked anxiously, unaware that the microphone was
open.
"Fine," came the reply, faint and reedy. "The air's thin but it's pure."
"Cold?"
"Don't know. Don't feel it yet. Anyway it can't be worse than the
acid. What do I do?"
Jordan gave her directions while the others watched. It required
considerable effort to find the tools and examine the tubes for
defectives, to loosen the tubes in the sockets and pull them out,
sending them spinning into space. It was still more difficult to
replace them, though there was no gravity and Anti was held firmly
to the hull by magnetics.
Anti had never been a technician of any kind. Cameron was sure of
it. She was ignorant of the commonest terms, the simplest tool. She
shouldn't have been able to do it. And yet she managed nicely,
though she didn't know how. The explanation must be that she did
know, that somewhere in her remote past, of which he was totally
uninformed, she had had training which prepared her for this. Such
contradiction was ridiculous. But there was rhythm to her motions,
this giant shapeless creature whose bones would break with weight
if she tried to stand at half gravity.
The whale plowing through the deeps and waves has the attraction
of beauty. It can't be otherwise for any animal in an environment
which it is suited to live in. And the human race had produced,
haphazardly, one unlikely person to whom interplanetary space was
not alien. Anti was at last in her element.
"Now," said Jordan, keeping tension out of his voice though it was
trembling in his hand. "Go back to the outside tool compartment.
You'll find a lever near it. Pull. This will set the combustion cap in
place."
"Done," said Anti when it was.
"That's all. Come in now."
She went slowly over the hull to the cargo ramp and while she did
Jordan reeled in the viewers. The lock was no sooner closed to the
outside and the air hissing into the intermediate space than he was
there, waiting for the inner lock to open.
"Are you all right?" he asked gruffly.
She flipped back the helmet. There was frost on her eyebrows and
her face was bright and red. "Why shouldn't I be? My hands aren't
cold." She stripped off the heated gloves and waggled her fingers.
"I can't believe it," protested Cameron with more vehemence than
he intended. "You should be frozen through."
"Why?" said Anti with gurgling laughter. "It's merely a matter of
insulation and I have plenty of that. More than I want."
Shaking his head Cameron turned to Docchi. "When I was a boy I
saw a film of a dancer. She did a ballet. I think it was called: Free
Space-Free Life. Something like that. I can't say why but it came to
my mind when Anti was out there. I hadn't thought of it in years."
He rubbed his hand over his forehead. "It fascinated me when I first
saw it. I went to it again and again. When I grew older I found out a
tragic thing had happened to the dancer. She was on a tour of Venus
when the ship she was in was forced down. Searching parties were
sent out but they didn't find anyone except her. And she had been
struggling over a fungus plain for a week. You know what that
meant. The great ballerina was a living spore culture medium."
"Shut up," said Jordan. "Shut up."
Cameron was engrossed in the remembrance and didn't seem to
hear. "Naturally she died. I can't recall her name but I can't forget
the ballet. And that's funny because it reminded me of Anti out there
——"
"I told you to shut up!" Jordan exploded a fist in the doctor's face. If
there had been more behind the blow than shoulders and a
fragment of a body Cameron's jaw would have been broken. As it
was he floated through the air and crashed against the wall.
Angrily he got to his feet. "I gave my word I wouldn't cause trouble.
I thought the agreement worked both ways." He glanced
significantly at the weapon Jordan carried. "Better keep that around
all the time."
"I told you," said Jordan. "I told you more than once." After that he
ignored the doctor, thrusting the weapon securely into his garment.
He turned to Anti. "Very good," he said, his anger gone and his voice
courtly. "An excellent performance. One of your best, Antoinette."
"You should have seen me when I was good," said Anti. The frost
had melted from her eyebrows and was trickling down her cheek.
She left with Jordan.
Cameron remained behind. It was too bad about his ambition. He
knew now he was never going to be the spectacular success he'd
once envisioned—not after this escape from Handicap Haven. He'd
done all he could to prevent it but it wouldn't count with the
Medicouncil that he had good intentions. Still, he'd be able to
practice somewhere; doctors were always necessary. There were
worse fates—suppose he had to abandon medicine altogether?
Think of the ballerina he'd been talking about—she hadn't died as
the history tapes indicated. That much was window dressing; people
were supposed to believe it because it was preferable to the truth. It
would have been better for that woman if she hadn't lived on. By
now he had recalled her name: Antoinette.
And now it was Anti. He could have found it out by checking the
records—if Handicap Haven kept that particular information on file.
He was suddenly willing to bet that it wasn't there. He felt his jaw,
which ached throbbingly. He deserved it. He hadn't really been
convinced that they were people too.
"We'll stick to the regular lanes," decided Docchi. "I think we'll get
closer. They've no reason to suspect we're heading toward Earth.
Mars is more logical, or one of the moons of Jupiter, or another
asteroid. I'm sure they don't know what we're trying to do."
Jordan shifted uneasily. "I'm against it. They'll pick us up before we
have a chance to do anything."
"There's nothing to distinguish us from an ordinary Earth to Mars
rocket. We have a ship's registry on board. Use it. Take a ship that's
in our general class and thereafter we'll be that ship. If Traffic blips
us, and I don't think they will unless we try to land, we'll have a
recording ready. Something like this: 'ME 21 zip crackle 9 reporting.
Our communication is acting up. We can't hear you, Traffic.'
"That's quite believable in view of the age and condition of our ship.
Don't overdo the static effects but repeat it with suitable variations
and I don't think they'll bother us."
Shaking his head dubiously Jordan swung away toward the tiny
fabricating shop.
"You seem worried," said Anti as she came in.
Docchi didn't turn around. "Yeah."
"What's the matter, won't it work?"
"Sure. There are too many ships. They can't pick us out among so
many. Anyway they're not looking for us around Earth. They don't
really know why we took the rocket and escaped."
"Then why so much concern? Once we're near Earth we won't need
much time."
His face was taut and tired. "I thought so too, in the beginning.
Things have changed. The entire Solar Police force has been alerted
for us."
"So the Solar Police really want us? But I still don't understand why
that changes a thing."
"Look, Anti. We planned to bypass the Medicouncil and take our case
directly to the Solar Government. But if they want us as badly as the
radio indicates they're not going to be sympathetic. Not at all.
"And if they're not, if the Solar Government doesn't support us all
the way, we'll never get another chance. Hereafter there'll be guards
everywhere on the asteroid. They'll watch us even when we sleep."
"Well?" said Anti. She seemed trimmer and more vigorous. "We
considered it might turn out this way, didn't we? Let's take the last
step first."
Docchi raised his head. "Go to the ultimate authority? The Solar
Government won't like it."
"They won't, but there's nothing they can do about it."
"Don't be sure. They can shoot us down. When we stole the ship we
automatically became criminals."
"I know, but they'll be careful, especially after we make contact.
How would it look if we were blown to bits in front of their eyes, in a
billion homes?"
Docchi chuckled grimly. "Very shrewd. All right, they'll be careful. But
is it worth it to us?"
"It is to me."
"Then it is to me," said Docchi. "I suggest we start getting ready."
Anti scrutinized him carefully. "Maybe we ought to fix you up."
"With fake arms and a cosmetikit? No. They'll have to take us as we
are, unpretty, even repulsive."
"That's a better idea. I hadn't thought of the sympathy angle."
"Not sympathy—reality. It means too much to us. I don't want them
to approve of us as handsome unfortunates and then have them
change their minds when they discover what we're really like."
Sitting in silence, Docchi watched her go. She at least would benefit.
Dr. Cameron apparently hadn't noticed that the exposure to extreme
cold had done more to inhibit her unceasing growth than the acid
bath. She probably would never get back to her former size but
some day, if the cold treatment were properly investigated, she
might be able to stand at normal gravity. For her there was hope.
The rest of them had to keep on pretending that there was.
He examined the telecom. They were getting closer. No longer a
point of light, Earth was a perceptible disc. He could see the outline
of oceans, the shapes of land and the shadows of mountains, the
flat ripple where prairies and plains were; he could imagine people.
This was home—once.
Jordan came in. "The radio tape is rigged up. I haven't had to use it
yet. But we have a friend trailing along behind us, an official friend."
"Has he blipped at us?"
"When I left he hadn't. He keeps hanging on."
"Is he overtaking us?"
"He'd like to."
"Don't let him."
"With this bag of bolts?"
"Shake it apart if you have to," said Docchi impatiently. "How soon
can you slide into a broadcast orbit?"
Jordan furrowed his forehead. "I didn't think we'd planned on that
this time. It was supposed to be our last resort."
"Anti and I have talked it over. We agree that this is our last chance.
Now's the time to speak up if you've got any objections."
"I've been listening to the police calls," said Jordan thoughtfully. "No,
I guess I haven't got any objection. Not with a heavy cruiser behind
us. None at all."
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.
textbookfull.com