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

Get How JavaScript Works: Master the Basics of JavaScript and Modern Web App Development 1st Edition Jonathon Simpson free all chapters

Simpson

Uploaded by

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

Get How JavaScript Works: Master the Basics of JavaScript and Modern Web App Development 1st Edition Jonathon Simpson free all chapters

Simpson

Uploaded by

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

Full download ebooks at ebookmeta.

com

How JavaScript Works: Master the Basics of


JavaScript and Modern Web App Development 1st
Edition Jonathon Simpson

https://ebookmeta.com/product/how-javascript-works-master-
the-basics-of-javascript-and-modern-web-app-development-1st-
edition-jonathon-simpson-2/

OR CLICK BUTTON

DOWLOAD NOW

Download more ebook from https://ebookmeta.com


More products digital (pdf, epub, mobi) instant
download maybe you interests ...

How JavaScript Works: Master the Basics of JavaScript


and Modern Web App Development 1st Edition Jonathon
Simpson

https://ebookmeta.com/product/how-javascript-works-master-the-
basics-of-javascript-and-modern-web-app-development-1st-edition-
jonathon-simpson/

The Modern Web Multi Device Web Development with HTML5


CSS3 and JavaScript 1st Edition Gasston Peter

https://ebookmeta.com/product/the-modern-web-multi-device-web-
development-with-html5-css3-and-javascript-1st-edition-gasston-
peter/

JavaScript for Modern Web Development Building a Web


Application Using HTML CSS and Javascript 1st Edition
Alok Ranjan Abhilasha Sinha Ranjit Battewad

https://ebookmeta.com/product/javascript-for-modern-web-
development-building-a-web-application-using-html-css-and-
javascript-1st-edition-alok-ranjan-abhilasha-sinha-ranjit-
battewad/

JavaScript Frameworks for Modern Web Development, 2nd


Edition Sufyan Bin Uzayr

https://ebookmeta.com/product/javascript-frameworks-for-modern-
web-development-2nd-edition-sufyan-bin-uzayr/
JavaScript for Web Developers: Understanding the Basics
1st Edition Mark Simon

https://ebookmeta.com/product/javascript-for-web-developers-
understanding-the-basics-1st-edition-mark-simon/

Building Web Applications with .NET Core 2.1 and


JavaScript: Leveraging Modern JavaScript Frameworks -
Second Edition Philip Japikse

https://ebookmeta.com/product/building-web-applications-with-net-
core-2-1-and-javascript-leveraging-modern-javascript-frameworks-
second-edition-philip-japikse/

Modern Web Development with Deno Develop Modern


JavaScript and TypeScript Code with Svelte React and
GraphQL 1st Edition Mayur Borse

https://ebookmeta.com/product/modern-web-development-with-deno-
develop-modern-javascript-and-typescript-code-with-svelte-react-
and-graphql-1st-edition-mayur-borse/

Connecting Arduino to the Web: Front End Development


Using JavaScript Indira Knight

https://ebookmeta.com/product/connecting-arduino-to-the-web-
front-end-development-using-javascript-indira-knight/

JavaScript Frameworks for Modern Web Dev 1st Edition


Tim Ambler Nicholas Cloud

https://ebookmeta.com/product/javascript-frameworks-for-modern-
web-dev-1st-edition-tim-ambler-nicholas-cloud/
Jonathon Simpson

How JavaScript Works


Master the Basics of JavaScript and Modern
Web App Development
Jonathon Simpson
Belfast, Antrim, UK

ISBN 978-1-4842-9737-7 e-ISBN 978-1-4842-9738-4


https://doi.org/10.1007/978-1-4842-9738-4

© Jonathon Simpson 2023

This work is subject to copyright. All rights are solely and exclusively
licensed by the Publisher, whether the whole or part of the material is
concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in
any other physical way, and transmission or information storage and
retrieval, electronic adaptation, computer software, or by similar or
dissimilar methodology now known or hereafter developed.

The use of general descriptive names, registered names, trademarks,


service marks, etc. in this publication does not imply, even in the
absence of a specific statement, that such names are exempt from the
relevant protective laws and regulations and therefore free for general
use.

The publisher, the authors, and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, expressed or implied, with respect to the
material contained herein or for any errors or omissions that may have
been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.

This Apress imprint is published by the registered company APress


Media, LLC, part of Springer Nature.
The registered company address is: 1 New York Plaza, New York, NY
10004, U.S.A.
Introduction
JavaScript is one of the most used programming languages in the world.
When JavaScript was first created, it was a useful tool for adding
interactivity to web pages. Since then, it has evolved to power back-end
servers, massive front-end web applications, and even iPhone and
Android applications via tools like Electron and Tauri.
While JavaScript has matured as a language its complexity seems to
have increased. What started as simple scripts inside HTML tags now
seems to involve compile steps via TypeScript and frameworks like
React, Vue.js, or Svelte. For those getting started in JavaScript, it can be
overwhelming, even though these tools are just an additional level of
abstraction which ultimately compiles down into vanilla JavaScript.
In this book, we’ll learn how JavaScript works from the bottom up,
which will prepare you for everything web development and JavaScript-
led app development can throw at you. We’ll also explain some of the
quirks you’ll find in JavaScript and how many of them have come to be
due to JavaScript’s long and varied history.
After that, we’ll cover JavaScript’s unique approach to inheritance
before moving into more complicated topics like memory management,
classes, APIs, and web workers. We’ll explore how the weakly typed
system JavaScript employs has both benefits and downsides.
As a fundamental part of the web stack, and with more people using
it every day, there has never been a better time to learn JavaScript. This
book will guide you through everything you need to know, so that you
can master modern web app development.
Table of Contents
Chapter 1:​Introduction to JavaScript
JavaScript Fundamentals
JavaScript’s Type Classification
What Is JavaScript Used For?​
Writing JavaScript
Summary
Chapter 2:​Code Structure and Logical Statements
Getting Started
Common Code Conventions
Semicolons
Spacing
Variable and Function Naming
JavaScript Variables
Setting Variables with let
Setting Variables with var
Setting Variables with const
Defining Variables Without Values
Assignment Operators
Variable Concatenation
JavaScript Comments
Logical Statements
If…else Statements
Switch Statements
Block Scoping with Logical Statements
Conditional Operator in Variables
Logical Statement Comparison Operators
Logical Statement Logical Operators
Summary
Chapter 3:​Introduction to Objects, Arrays
Arrays
Getting the Length of an Array
Getting the Last Element of an Array
Array Manipulation Methods
Push and Unshift
Pop and Shift
Splice
Objects
Accessing Object Data
Object Mutability
Spread Syntax or the “Three Dots”
Prototype-Based Programming
Prototypical Inheritance
[[Prototype]] vs.​prototype (and _​_​proto_​_​)
Object Shallow and Deep Copies
Summary
Chapter 4:​Loops and Iterables
Loops
Break and Continue in Loops
Loop Labels
Iteration
Iterables and For Loops
Array forEach methods
String Iteration
Iteration Protocol
Objects Are Not Iterable by Default
Summary
Chapter 5:​References, Values, and Memory Management
Introduction
Stacks
The Event Loop
The Heap
Object and Reference Equality
Summary
Chapter 6:​Functions and Classes
Introduction to Functions
Running Arguments with the “Three Dots”
Alternative Ways to Call Functions
Unnamed Function Expressions
Anonymous Functions
Functions with Arrow Notation
Functions and the “this” Keyword
Sloppy Mode
Arrow Notation Functionality with this
Calling Functions with Context
Constructor Functions in JavaScript
Additional Function Methods
Getters and Setters
Generator Functions
Classes
Classes and Constructor Functions
Class Methods
Class Method Types
Class Inheritance via Extends
Summary
Chapter 7:​Types
Primitive Types
Primitive Wrappers
Using Wrappers to Create Types
The Number Type and NaN
Number Type Mathematics
Mathematical Methods
The Date Type
The Symbol Type
Truthy and Falsy Types
Truthy and Falsy Operators
Logical AND Operator
Logical OR Operator
Nullish Coalescing
Optionality
Summary
Chapter 8:​Manipulating and Interacting with HTML
Window and Document Objects
The Window Object
The Document Object Model
Selecting HTML Elements
The Order of HTML
NodeLists and HTMLCollections
Manipulating HTML After Selection
Adding Events to HTML Elements
Creating a Modal Window
Creating a Counter
Event Types
Drag and Drop
The e variable
Creating New Elements with JavaScript
Manipulating CSS with JavaScript
HTMLElements and Changing Styles in JavaScript
Adding New Style Sheets to HTML Pages
Setting CSS Variables
Getting CSS Properties and HTML Dimensions
Summary
Chapter 9:​Maps and Sets
Sets
Modifying Sets
Checking Set Membership
Checking Set Size
Merging Sets
Set Iteration and Values
Maps
Retrieving Map Properties
Checking for Key Existence on a Map
Telling How Big a Javascript Map Is
Iterating, Merging, and Accessing Maps
Keys and Values in Maps
Serialization of Maps in JavaScript
Summary
Chapter 10:​Fetching Data, APIs, and Promises
What Are APIs?​
Understanding HTTP
RESTful Design
Understanding APIs Through a Node.​JS Web Server
Testing Endpoints with Postman
The Benefits of APIs
Sending Data to APIs with JSON
The fetch Function
A Deep Dive into Fetch Options
Asynchronicity and Promises
Promise Methods:​then, finally, and catch
The await Keyword
Useful Promise Methods
Summary
Chapter 11:​Introduction to Web APIs
Web APIs
Frequently Used Web APIs
URL API
Web Storage API
Web Notifications API
History API
Summary
Chapter 12:​Errors and the Console
The Console Object
Console Errors, Debugs, Warnings, and Info
Console Timing
Console Counting
Other Useful Console Methods
Console Grouping
Console Tables
Errors and Exceptions
try…catch
Generating Errors
Handling Specific Errors
Summary
Chapter 13:​The Canvas
Introduction
Drawing and Images
Drawing Rectangles
Drawing Circles
Drawing Triangles
Drawing Images
Drawing Text
Interactivity and Creating a Drawing Application
Animations
Summary
Chapter 14:​Web Workers and Multithreading
Introduction
Using Web Workers
Sending Messages to and from Web Workers
Restrictions on Web Workers
Conclusion
Index
About the Author
Jonathon Simpson
studied at UCL and currently works in product development at Revolut,
a global neobank and financial technology company that offers banking
services. He has over 15 years of web development experience working
on a wide range of products and services. Jonathon also owns and
operates a popular software engineering blog focusing on JavaScript
and web development.
About the Technical Reviewer
Russ Ferguson
is a web application developer living in Brooklyn, New York. He has
worked on projects for organizations such as Ann Taylor, MTV, DC
Comics, and LG. Currently, he is the Vice President at Bank of America
managing a team of Angular developers, building internal applications.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2023
J. Simpson, How JavaScript Works
https://doi.org/10.1007/978-1-4842-9738-4_1

1. Introduction to JavaScript
Jonathon Simpson1
(1) Belfast, Antrim, UK

JavaScript is a programming language that first appeared in 1995 as the


scripting language for the Netscape browser. Since then, it has evolved
into one of the most used programming languages in the world. While
its initial goal was to add interactivity to websites, it has since come to
do just about everything, including creating desktop apps and back-end
APIs.
JavaScript is everywhere, and over the years, many frameworks
have been built on top of it, such as jQuery, React, Vue.js, and Svelte. All
of this can make learning JavaScript intimidating, as there are often
many different ways to achieve the same thing.
In this book, we’ll be covering how JavaScript works at a
fundamental level. That will then make it is easier to understand how
frameworks like React and Vue.js work. We’ll discuss why things work
the way they do in JavaScript and the various quirks that come with
years of ongoing development on the language.
JavaScript today broadly falls into two major categories:
Client-side code, which we’ll refer to as “the front end,” which is
included via HTML files and adds interactivity to websites. Client-
side code is loaded and processed directly on someone’s web
browser or device. In practice, this means writing a .js file or HTML
file containing JavaScript and loading it directly into your
web browser.
Server-side code, which we’ll refer to as “the back end,” which is
used for writing web servers. This kind of code is written on web
servers and can be used to create things like APIs which the end user
never directly sees. It uses a runtime to execute the code on web
servers. The most common runtime used for this is called Node.js.
Server side code is loaded and processed on a server that is separate
from the user’s device.
Everything we discuss in this book will be applicable to both front
end and back end, but our focus will be on front-end JavaScript since
that’s where JavaScript started. We’ll sometimes touch on back-end
JavaScript where necessary so that certain concepts can be more easily
understood.

JavaScript Fundamentals
JavaScript is based on a language standard called ECMAScript. How
JavaScript should exactly work is documented in a specific standard
called ECMA-262. Since ECMAScript does not provide any tools to
compile JavaScript, every implementation of JavaScript creates its own
version of JavaScript. That includes your browser and back-end
compilers like Node.js.
For the most part, these implementations follow ECMA-262, but
since each implementation is done by different teams, there can be
some minor discrepancies or different feature sets depending on the
browser or implementation.
In this chapter, we will be covering how you can set yourself up to
start using JavaScript, including how to set up JavaScript projects when
using Node.js. In future chapters, we will explore how to write
JavaScript code.

JavaScript’s Type Classification


How a language is typed usually gives us a broad idea of how it works.
Like most other languages, JavaScript lets you define “variables” to
store data, and these variables have types. “Type” refers to the kind of
data being used. For example, a number is of type Number, and a
mixture of characters and/or numbers is referred to as having a type
called String.
If you have used other languages, JavaScript may seem different
since it is weakly typed. That means that while other languages
require you to explicitly mention in the code what type of data different
variables are, JavaScript does not. JavaScript is also often referred to as
dynamically typed, meaning it will dynamically interpret what type of
data is based on the context it finds it in.
To understand this better, let’s look at how variables are defined in
JavaScript. Usually, we define them like this:

let x = "Some String"


let y = 5
let z = false

You’ll see that no types are defined here. For example, we did not
have to mention that "Some String" was a String. JavaScript
determines types based on context – so it will take x to be a String
simply because we put its value in quotation marks. Similarly, it will
dynamically interpret y as being of type Number since it lacks
quotation marks and z as being of type Boolean since it has no
quotation marks and uses the keyword false.
This makes JavaScript quite easy to pick up, but quite hard to
master. The lack of strong typing can mean that you unknowingly create
bugs in your software since JavaScript will not always throw errors if
unexpected types show up, and even worse, JavaScript may dynamically
interpret types incorrectly in some cases.
For more complex applications with lots of test cases, developers
often reach for TypeScript instead of JavaScript for this reason.
TypeScript is JavaScript, but extended. It’s strongly typed, meaning
types must be mentioned in your code.

What Is JavaScript Used For?


As we mentioned in the introduction, JavaScript can be compiled and
used in two major ways. The first is to create front-end interactive
experiences, right in your browser. The second is as back-end server
code. Front-end JavaScript is rendered by the browser inside of web
pages, while back-end server code requires a runtime like Node.js,
which compiles the code you write to run it directly on the server.
When inside the browser, some of the major things JavaScript can
do are
Adding, changing, or deleting CSS/HTML when a user interacts with
something.
Creating new HTML tags programmatically.
Tracking user action and producing feedback to the user (such as
showing a pop-up when a user clicks on something).
Storing data for the user locally via local storage or cookies.
Creating single-page user experiences where no page refreshing is
needed.
On the back end, the main use cases are
Creating routes/URL endpoints on a server and dictate what happens
if a user navigates there.
Creating routes/URL endpoints for APIs (application programming
interfaces), so we can send and receive data to and from the server.
Building WebSocket servers, which users can interact with from their
front-end experience. These can be used for making things like chat
rooms.
Compressing pre-rendered web pages for a faster web experience.
Manipulating data sent to the server (sometimes via WebSocket or
API) and store it in a back-end database.

Writing JavaScript
JavaScript on the front end is found inside HTML on web pages. As such,
familiarity with HTML is quite important when we work with
JavaScript. To create your first file containing JavaScript, you can start
by making a .html file. We usually call the home page of a website
index.html when building websites, so for this example, I created a
new HTML file called index.html.
.html files can be opened by any web browser, such as Google
Chrome. You can edit your HTML file by opening it up in a text or code
editor (Notepad included), and puting in this standard “boilerplate”
HTML:

<!DOCTYPE html>
<html>
<head>
<title>My First JavaScript</title>
</head>
<body>
<p>Hello World</p>
<script type=”text/javascript”>
// This is JavaScript!
</script>
</body>
</html>

Note You can use any text editor (like Notepad) to create HTML
and even JavaScript. While that works fine, it’s better to use a
professional code editor instead. One of the most popular code
editors used in the software development community is VS Code.
You can download it via https://code.visualstudio.com/.
This will color code your JavaScript and give you a lot of other useful
features.

In the preceding example, we inserted a <script> tag within our


HTML body. The <script> tag is where our JavaScript goes:

<script type="text/javascript">
// This is JavaScript!
</script>

Since JavaScript applications can get quite long, you may see this
<script> tag substituted out for a file instead. This can be useful
since it lets us separate our HTML and JavaScript into different files.
For example, if we had a separate JavaScript file called
myScript.js stored in the same folder as index.html file, we
could load that into our HTML document by using the src attribute on
the script tag:

<script src="myScript.js"></script>
You may also see JavaScript embedded into HTML via the attributes
of HTML tags. For example, JavaScript can be put inside a button to
cause something to happen when a user clicks that button:

<button onclick="//JavaScript here"></button>

Setting Up a Code Editor


Throughout this book, I will be writing code using Visual Studio Code or
VS Code. If you do not have a preferred code editor, I would strongly
recommend using VS Code, which you can download via the official
website (https://code.visualstudio.com).
Although it is possible to build a software career through Notepad,
it’s not recommended. Modern code editors like VS Code give you a ton
of useful features, including code highlighting which makes it easier to
read what you’re writing. They also come with more advanced features
like built-in terminals, for when you need those things.
If you download VS Code, you’ll be greeted with a screen that looks
like the one shown in Figure 1-1. From there, you’ll be able to make
new files and folders for storing your projects in.
Figure 1-1 After you install VS Code, open the application. By going to File ➤ Open Folder… or
clicking “Open Folder” in VS Code and finding your “My JavaScript” folder

Starting Up Our Code


The fun thing about writing front-end JavaScript is that once you save
your .html file, you can load it directly in any web browser to test it
out.
Try it out by opening index.html in your web browser, either by
dragging it into the window or by opening it via File ➤ Open File….
To see your code in the browser itself, you can right-click on the
web page anywhere and choose “Inspect” in Google Chrome. If Chrome
is not your browser of choice, similar functions exist in other browsers
too. Using “Inspect” will also let you see supplementary information
about what you’ve created, as Figure 1-2 shows.
Figure 1-2 “Inspect” or “Inspect Element” lets you view more information about your code in
the web browser

“Inspect” or “Inspect Element” is a vital tool in web development.


Throughout this book, we’ll use the console tab within developer tools
to test out code and see the results of code we run. As such, it’s very
useful to familiarize yourself with this display now.

How to Get Started with Writing Back-End JavaScript


We’ve now discussed how JavaScript can be run inside a web
browser like Google Chrome. Before we go any further, let’s briefly look
at how we run back-end JavaScript too, which we’ll occasionally touch
on in this book. Back end JavaScript runs directly on your computer or a
web server instead of inside a web browser. To run JavaScript like this,
you need to use a runtime like Node.js.
Node.js can be downloaded and installed on your computer via the
official Node.js website (https://nodejs.org/en/download).
After it has been installed, you’ll be able to run JavaScript code directly
from a terminal window by executing your .js file.
You can do that by opening the terminal or command line on your
computer, which is accessible on MacOS via the terminal app or on
Windows via the “cmd” application.
Running the node command lets you compile and execute
JavaScript files. Let’s try it out – create a file called index.js in a
code editor or Notepad, and add the following JavaScript code before
saving:
console.log("Hello World!")

Then you can execute this file by using the node command in
terminal:

node index.js

This will produce an output which looks something like what is


shown in Figure 1-3.

Figure 1-3 Running a JavaScript script from the command line is as simple as using the “node”
command followed by the directory link to the file you want to run

Note If you saved your index.js file in another directory, you will
need to provide the full directory link. To navigate directories, use
the cd command. For example, if your index.js file was in
“/Users/JohnDoe/Documents/”, you would run cd
/Users/JohnDoe/Documents/ and only after that, run node
index.js.
Node.js applications like this are frequently used to create APIs,
which we will cover in much more detail later in the book.
Creating Node.js JavaScript Projects
In the above example, we executed a single file using Node.js It is more
common, though, to create a Node.js project when you start something
new in Node.js. This is also done via terminal or the cmd. The first step
is to make a new folder and navigate to it using the cd command.
In this example, I made a folder called “node-project” on my desktop
and navigated to it using the following command in Terminal:

cd ~/Desktop/node-project

After that’s done, you can use the npm init command, which is
installed along with Node.js, to initiate your project. You can see how
that looks in Figure 1-4.

Figure 1-4 When using the npm init command, you will be asked to enter some information
about your new project as shown earlier
All you have to do now is type in answers to each question and
press enter. For example, the first question asks what you want to call
your project – so type in the name of your project, and press enter.
Your folder will now contain a package.json file summarizing
the information you provided. Since you’ve initialized your Node.js
project, you’ll now be able to run other commands like npm install
now, which lets you install third party dependencies.

JavaScript Support
Traditional software is usually written by a developer and downloaded
onto a user’s computer or device. This is the case with things like video
games, apps on your phone, or big applications like Adobe Photoshop.
When writing code in JavaScript, things are very different. The
software the user installs is the browser, not your website! The browser
then loads your web page within it. Since everyone has their own
browser preference, and not everyone keeps their browsers up to date,
JavaScript that works in one browser can oftentimes not work in
another. For example, Firefox may support a new JavaScript feature, but
Chrome may not. The worst thing about this is you can’t really use a
new JavaScript feature on the front end until a majority of browsers
have implemented it.
If you are coming from other languages, then worrying about
browser support will be a foreign concept to you. In JavaScript, it is a
real thing. In recent times, since most browsers are “evergreen”
(meaning they auto-update), this has become less of a problem than it
used to be, but sometimes different browsers just disagree on what
should and shouldn’t be implemented. Promising new features may end
up implemented in just Chrome, just Safari, or just Firefox.
Throughout this book, we’ll only be looking at JavaScript with broad
browser support, meaning you don’t need to worry about if you can or
can’t use it. However, when you start exploring JavaScript in your own
time, and especially when looking at more advanced functionality, it’s
important to check if browsers support it. You can find good browser
support tables on websites like https://caniuse.com/ or
https://developer.mozilla.org/.
An example of a browser support table can be found in Figure 1-5,
for the GPU feature.
Figure 1-5 Not all browsers support every new JavaScript feature. In the preceding example,
only Chrome and Edge have support. Other browsers only have partial support or none at all.
That means if you tried to implement this on a website, only some users could use it!

Summary
In this chapter, we’ve looked at how to set up your workspace to begin
writing code with JavaScript. We’ve discussed what JavaScript is
typically used for and some of the pitfalls or differences between it and
other languages. Now that we’ve covered the basics let’s look at how to
write JavaScript code.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2023
J. Simpson, How JavaScript Works
https://doi.org/10.1007/978-1-4842-9738-4_2

2. Code Structure and Logical


Statements
Jonathon Simpson1
(1) Belfast, Antrim, UK

In the previous chapter, we covered the fundamental definitions of


JavaScript and where we write it. Now that we’ve discussed the basics,
let’s start learning about how we write JavaScript code. In this
chapter, we’ll cover the fundamentals, which includes code structure,
logical statements, and variables. Mastering these concepts is a
requirement to writing useful JavaScript code. Where relevant, we’ll
also be diving deeper into how these basic concepts actually work, so
that you have a deeper understanding of the code you are writing.

Getting Started
As we go through this chapter, it will be good to have a work space
where you can write and test your JavaScript. For these purposes, I’ve
created a folder called “javascript-project” in my documents
folder. Within that, I have created two files – index.html and
index.js.
Since our focus will be writing JavaScript, your HTML file can be
relatively simple:

<!DOCTYPE html>
<html>
<head>
<title>My First JavaScript</title>
</head>
<body>
<p>Hello World</p>
<script src="index.js"></script>
</body>
</html>

Any JavaScript code you want to try out can be put in index.js.
For now, I’ve only put a simple console.log method:

console.log("Hello World!")

The console.log method is really useful. It’s used extensively for


debugging, and we’ll be using it throughout this book. When it’s run, it
logs a message to your browser’s console, so that you can see the
output of your code easily. You can find the console by right-clicking
anywhere on your web page and selecting “Inspect.” Console logs can
then be viewed under the “Console” tab, as shown in Figure 2-1.

Figure 2-1 Right-clicking in the web browser and selecting “Inspect” in Google Chrome (or
other browsers) allows you to access the console log. If you do this with the index.html file we
defined before, you’ll see “Hello World!” written here. The console is a powerful tool used for
debugging. When we use the console.log method, it shows up here!

Common Code Conventions


Before we start writing real code, let’s first consider some basic code
conventions. As is the case in most programming, developers of
JavaScript try to follow some common conventions when writing code.
This section is largely opinionated, but it does provide you with
guidelines on how you should go about writing JavaScript. It will also
let you know how we will go about writing code throughout the book.

Semicolons
For readability, JavaScript is sometimes written with a semicolon at the
end of each line. For example:

console.log("Hello World!");
console.log("Goodbye World!");

However, this is not necessary, and it’s also just as common to see
the same code written without semicolons:

console.log("Hello World!")
console.log("Goodbye World!")

We can do this because JavaScript will intuitively “figure out” where


semicolons should go. It even works if you do an accidental line break
where an expression seems incomplete. For example, if a line ends with
a + symbol, JavaScript will assume that the expression must continue
onto the next line, meaning the code will still work as expected:

console.log(5 +
6)

For the code in this book, we will be omitting the semicolon unless
it is really needed.

Spacing
One of the most vigorously fought over code conventions is whether to
use tabs or spaces for indenting. While there is essentially no right or
wrong answer to this, it is important to be consistent. If you use tabs,
then always use tabs for indents and likewise for spaces.
Unlike Python, indents play no functional role in JavaScript, but they
do serve to make your code more readable when others look at it.
While it is certainly fine to use tabs, spaces are going to cause you less
of a headache. That’s because different ecosystems and operating
systems can be configured to handle tabs differently, whereas spaces
are consistently sized across all systems.
In this book, we will indent with four spaces. Here is an example of
how that will look:

let myVariable = 5

if(myVariable === 5) {
console.log("The variable is 5!")
}

Note If you use the tab key instead of spaces in VS Code to indent
your code, you can configure VS Code to automatically convert these
to spaces if you want it to. The configuration option is found by
opening any file and selecting the “Spaces/Tab Size” option in the
bottom right-hand corner.

Variable and Function Naming


When it comes to naming functions and variables, you’ll come across
three different paradigms: camel case, pascal case, and underscores:
Camel case refers to naming a variable where every word after the
first has a capital letter, for example, thisIsCamelCase.
Pascal case is the same, except the first letter is capitalized too. For
example, ThisIsPasalCase.
Underscoring refers to separating words with underscores. For
example, these_are_underscored.
When naming variables and functions, all of these are fine to use,
but again, it is important to be consistent. If you decide to use camel
case, then make sure you use it everywhere. For the purposes of this
book, we will be using camel case.

JavaScript Variables
As we begin writing JavaScript, the first thing you’re going to need to
learn about are variables. Variables are a way to assign a fixed name to
a data value. There are three ways to create a variable in JavaScript,
using three different keywords:
var
let
const
All JavaScript variables are case-sensitive, so myVariable is
different from MYVARIABLE. In JavaScript nomenclature, we
usually say that we “declare” variables.

Setting Variables with let


Most variables in JavaScript are set with let. A variable set with let
starts with the keyword let, followed by the variable name and an
equals sign, and then the value of your variable. In the following
example, we create a variable called myVariable, and console log it so
that it appears in the browser’s console:

let myVariable = 5
console.log(myVariable)

Note It may seem like we are putting data into the variable, but a
better way to think about it is we are making data and then pointing
the keyword “myVariable” at the data we just made.

It’s not possible to assign a variable with let twice. If you think of your
variable as pointing to some data, it’s easy to see why – the same
variable can’t point to two different pieces of data. For example, the
following code will produce the error, which is shown in Figure 2-2.

let myVariable = 5
let myVariable = 10
console.log(myVariable)

Figure 2-2 Variables defined with let cannot be defined multiple times. If you try to, it will
produce an error like the preceding one

So variables defined with let cannot be redefined again. They can,


however, be reassigned to a new piece of data by mentioning them
again without the let keyword. You can see that in the following
example, which console logs “10,” since we changed the value of
myVariable:

let myVariable = 5
myVariable = 10
console.log(myVariable)

It may seem like the data has changed (or “mutated”), but actually
we’ve just made new data somewhere and pointed our variable to that
instead. The data “5” still exists somewhere. It just has no variable
pointing to it anymore. When a piece of data is no longer referenced in
our code, JavaScript may remove it from memory using something
called “garbage collection.” This allows JavaScript to free up memory
when data is no longer used.

Block Scoping with Variables


In the previous example we saw that it is not possible to define the
same variable, but there are exceptions to this. That’s because variables
defined with let are block-scoped. Scope confines functionality,
variable names, and values to certain sections of our code.
Block scopes are created with curly brackets {}. In most scenarios,
we create block scopes by defining new functions or logical statements.
Since standalone curly brackets also create a new block scope, a
variable can be set twice simply by defining it again inside { } curly
brackets:

let myVariable = 5

{
let myVariable = 10
console.log(myVariable)
}

console.log(myVariable)

Even though we created the same variable twice, no error is thrown,


and that’s because one is assigned to a new block scope. The first
variable is assigned to the “global” scope of our program, while the
second is assigned only to the “curly bracket” scope. The outcome of
this can be seen in Figure 2-3.

Figure 2-3 While using let, our console produces two different lines, 5 and 10. This is
because let is assigned to its current scope – so setting myVariable to 10 in a separate scope
does not affect the original variable. If we used var instead, both lines would say 10 since
scope is ignored
Setting Variables with var
Most variables are set with let, but you may also see the keyword var
being used to set variables sometimes. Using var is the original way to
set variables in JavaScript. It is valuable to know this exists, but it is
generally not recommended that you use it over let.
Setting a variable with var looks a lot like what we did with let.
For example, here is a variable called myVariable, with a value of 5:

var myVariable = 5

The reason why we use let rather than var is because var has a
few quirks that let does not. For example, you can define a variable
twice with var, and no errors will be thrown:

var myVariable = 5
var myVariable = 10
console.log(myVariable)

Variables defined with var are also not block-scoped, meaning your
code can produce some odd results when redefining variables in block
scopes with var.
You may be wondering, “Why does JavaScript have two ways of
defining variables when let is a more controlled version of var?” The
answer to that is pretty simple, and it’s because var used to be the only
way to define variables in JavaScript, and a lot of legacy code uses it.
Later on, JavaScript created a better way to define variables using let,
but var couldn’t be removed since it would break many older code
bases.

Setting Variables with const


The final variable type we will cover is const. When we defined
variables with let, we talked about how a variable can be reassigned
to another value:

let myVariable = 5
myVariable = 10
console.log(myVariable)

Remember, we don’t actually change or “mutate” the data here – we


just create new data and “re-point” our variable to that new data
source.
While this works for let, it will not work for const. Variables
defined with const are constants and cannot be reassigned:

const myConst = 5
console.log(myConst)

If you try to reassign the value of a const variable, you’ll get an


error instead.

const myConst = 5
myConst = 10
console.log(myConst)

Using const to define variables is better when you’re able to use it.
To understand why, you can think about the example we
discussed earlier where we used let to reassign a variable from “5” to
“10”. We talked about how the value “5” still exists in memory unless it
gets garbage collected. Since const variables cannot be changed,
garbage collection never has to run. That means less cleanup is
required, resulting in more efficient memory utilisation.

Mutation of const Variables


Variables cannot be reassigned with const, but they can be mutated.
That’s because reassignment and mutation are not the same thing.
When we reassign a variable, no data changes – but it is possible to
change underlying data in JavaScript using mutation instead. In
JavaScript, mutation of primitive values like numbers, strings, and
booleans is not possible, but objects can be mutated.
We will cover how arrays and objects work in more depth in the
next chapter. For now, all you need to understand is that arrays and
objects are containers of data. An array can be defined as shown in the
following example:
const myArray = [ "some", "set", "of", "content" ]
console.log(myArray)

Arrays can contain a lot of data, and we can push new data to an
array using a special method called push:

const myArray = [ "some", "set", "of", "content" ]


myArray.push("new data!")
console.log(myArray)

By using push we can mutate our array, meaning the underlying


data changes and the data continues to be referenced and stored in the
same place. In other words, we did not create new data and point our
variable somewhere else, but instead mutated the original data.
This is confusing to beginners since the array was pointed to by a
const variable, so it would therefore be assumed that since the const
variable is a constant, the data inside must always remain constant.
This is not the case in JavaScript. So, in summary, while reassignment
must remain constant in a const variable, data mutation is fine.

Defining Variables Without Values


It is also possible to define variables that point to nowhere. If you try to
console log a variable with no value assigned, you will get undefined
as a result:

let myVariable
console.log(myVariable)

This is sometimes done when a variable does not have a value when
you declare it but may be assigned a value later on in the code. When
many variables need to be declared without values, they can be
separated by commas. In the following example, we define three
variables with the let keyword:

let myVariable, myOtherVariable, myFinalVariable


Although comma notation like this is more commonly used with
variables that have no value, you can declare variables with values this
way too:

let myVariable = 5, myOtherVariable = 4,


myFinalVariable = 3

Assignment Operators
Now that we’ve covered the basics of setting variables, let’s look at
assignment operators. These allow us to modify an existing variable, by
changing its value. For example, consider this variable:

let x = 5

Suppose we wanted to multiply x by 5. One way is to reassign x to 5


* 5, but a better way is to use an assignment operation. The reason it’s
better is because x may not always be 5, so this is particularly useful if
we want to change the value of variables based on conditions (which
we will cover in more detail in the following).
To multiply x by 5, we use the *= assignment operator:

let x = 5
x *= 5
console.log(x) // Console logs 25 (5 multiplied by
5 = 25)

There are many other assignment operators. They are shown in the
following example:

let x = 5
x *= 5
console.log(x) // Console logs 25 (5 multiplied by
5 = 25)

x += 5
console.log(x) // Console logs 30 (25 plus 5 = 30)
x /= 5
console.log(x) // Console logs 6 (30 divided by 5
= 6)

x -= 1
console.log(x) // Console logs 5 (6 minus 1 = 5)

x %= 4
console.log(x)
/*
Console logs 1 (if you divide 5 by 4, the
remainder is 1.
% is the remainder operator
*/

Variable Concatenation
When we have variables that consist of at least one string, using the +
operator causes the strings to become concatenated. To understand
this, take a look at the following example, where we concatenate two
strings into a new variable:

let myVariable = "hello"


let myOtherVariable = "world"
let combine = myVariable + myOtherVariable //
"helloworld"

If we need a space too – we can add that with another +:

let myVariable = "hello"


let myOtherVariable = "world"

// "hello world"
let combine = myVariable + " " + myOtherVariable

Just be careful, since if you try to use a + with numbers, it will add
them up instead!

let myVariable = 5
let myOtherVariable = 5

let combine = myVariable + myOtherVariable // 10

This brings us to a new quirk caused by JavaScript’s dynamic typing.


If a number is in quotation marks, it is assumed to be a string. Adding a
number and string results in a new concatenated string instead of a
calculation:

let myVariable = "5"


let myOtherVariable = 5

let combine = myVariable + myOtherVariable // "55"

Another way to combine string variables is with a special method


called concat. This is a method that exists on all strings, which will
add to the end of a string any number of new things that we separate
with commas:

let myVariable = "hello"


myVariable.concat(" ", "world", "!") // hello
world!

Different types of data have different built-in methods, which we’ll


look at in much more detail in future chapters.

Template Literals
Another final way to concatenate more elegantly is through a type of
functionality called template literals. Template literals are still strings,
but they use the backtick "`" to transform any content into a template
literal. Template literals have the added benefit of allowing line breaks
– something that numbers and quotation marks do not. They also allow
for substitution. Here is an example of a particularly messy template
literal with line breaks throughout:

let myVariable = `hello world


!!
how are you?`
Template literals like the preceding one will be taken with line
breaks and white space included – which means you’ll avoid loss of this
content when using them. They also allow for substitution. Adding a
variable in ${} will substitute it into a template literal:

let someWord = "world"


let myVariable = `hello ${someWord}!` // hello
world!

JavaScript Comments
You may have already noticed that in the preceding code, I used double
slashes to leave some comments on what the code does. As our code
gets more complicated, it’s useful to leave messages to yourself or other
developers about what is going on. For this purpose, comments are
used.
A comment in JavaScript can take one of two forms. The first looks
like this:

// I am a comment!

And the second looks like this, where the comment is enclosed in /*
and */:

/* I am a comment! */

Both work the same, but the second allows for multiline comments.
Comments have no bearing on the functionality of your code and
instead can provide useful information on what’s going on. For
example, we could comment our previous code like so:

// This code will console log myConst


const myConst = 5
console.log(myConst)

Logical Statements
Now that we’ve covered variables, you’ll probably be wondering how
we can use them. Logical statements are one of the ways we can start to
put our variables to good use.
Logical statements are used when we want to check if something is
true or false and then run a particular action based on that outcome. If
a logical statement is found to be true, everything within its “block
scope” is executed. Likewise, if a logical statement is false, then the
block scope will never run at all. In other words, logical statements
allow us to build conditionality into our programs.

If…else Statements
if...else are perhaps one of the most commonly used logical
statements around. All they do is check if a statement is true. If it is,
they run some code, else, they run some other code. In the following
example, we check if myVariable is set to 5. If it is, we show “The
variable is 5!” in the console. If it’s not, then we show alternative text.
You can view this code running in Figure 2-4, where I run it directly
from the console in my web browser. You could also try this out by
updating your index.js file from earlier:

// We have set myVariable to 5


let myVariable = 5

if(myVariable === 5) {
console.log("The variable is 5!")
}
else {
console.log("The variable is not 5.")
}
Figure 2-4 Since myVariable is 5, the statement myVariable === 5 is always true. So the
block of code within the first if statement is executed, and the else statement never fires

We can add more conditions to our code by using else if after an


if statement. In the following example, we check for a third condition,
where myVariable could be 6:

// We have set myVariable to 5


let myVariable = 5

if(myVariable === 5) {
console.log("The variable is 5!")
}
else if(myVariable === 6) {
myVariable = 7
console.log("The variable is 6, but I set it
to 7!")
}
else {
console.log("The variable is not 5.")
}

As you can see in the else if condition, any code can be written
in the block scope created by a logical statement. In else if, we
reassigned myVariable to have a value of 7.
If the output of an if statement is one line of code, you can omit the
curly brackets and write it all on one line of code as shown in the
following example. This also applies to else if and else:

// We have set myVariable to 5


let myVariable = 5

if(myVariable === 5) console.log("The variable is


5!")

Our examples so far have dealt with strict equality – meaning we


are using the triple equals sign. There are more ways we can check
variable values, though! We’ll cover them all in this chapter.

Switch Statements
Another common way to create conditionality in your JavaScript is
through switch statements. They take a single variable and check if it
equals certain values using the case keyword to define the value it
might equal and a break to declare the end of that clause. For
example:

// Let's set x to 5
let x = 5

switch(x) {
case 5:
console.log("hello")
break
case 6:
console.log("goodbye")
break
}

In the previous example, we have two clauses: one where x equals


5, in which case we console log “hello,” and another where it equals 6,
where we console log “goodbye.” It is important to have a break after
each case clause since if you don’t, all cases will run after the one that is
correct! For example, the following code will console log both “hello”
and “goodbye” – which is quite confusing:

// Let's set x to 5
let x = 5

switch(x) {
case 4:
console.log("4!")
case 5:
console.log("hello")
case 6:
console.log("goodbye")
}
Another Random Document on
Scribd Without Any Related Topics
The Project Gutenberg eBook of Trouble
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.

Title: Trouble

Author: George O. Smith

Illustrator: Swenson

Release date: June 9, 2022 [eBook #68272]

Language: English

Original publication: United States: Street & Smith Publications,


Incorporated, 1946

Credits: Greg Weeks, Mary Meehan and the Online Distributed


Proofreading Team at http://www.pgdp.net.

*** START OF THE PROJECT GUTENBERG EBOOK TROUBLE ***


Trouble
By GEORGE O. SMITH

[Transcriber's Note: This etext was produced from


Astounding Science-Fiction, July 1946.
Extensive research did not uncover any evidence that
the U.S. copyright on this publication was renewed.]
Tom Lionel, Consulting Engineer, awoke with a shake of his head. At
once, he was out of bed. He consulted first the calendar and then the
clock. The thought struck him funny. He hadn't been drinking, but the
idea of looking at a calendar upon awakening might be construed as
an admission that he didn't know what time of what day it was.
Or mayhap what month.
"Ding it," he grunted. "I've been away again."
He dressed by stages. At the trousers department, Tom wandered out
into the living room and stood over a chessboard, studying the set-up.
The opponent had moved the queen to the rook's fourth, menacing
his bishop. Tom smiled and moved his knight to his knight's sixth and
checked the opponent's king on the rook's first, and the queen
simultaneously. He slid the drawer below the table open and removed
a little standing sign that said, in red, block letters:

CHECK!
"Let him try that one, will he?" laughed Tom. The move was basic; in
checking the king and menacing the queen simultaneously, Tom had
—or would upon the next move—collect himself his opponent's queen
with no great loss.
At the shirt and necktie stage, Tom Lionel stood teetering on his heels
before the bookcase on the right of the fireplace. He took from the
case a slim volume and read the title with considerable distaste:
"Theory of Monomolecular Films in Fission-Reaction"
By A. G. Rodan, Ph.D., M.M., LL.D.
"Yipe!" exploded Tom as he opened the book and glanced at the
price: $9.50. With ease he prorated the price against the thickness of
the volume and came to the estimate that the book had cost
approximately nineteen dollars per inch excluding covers. He riffled
through the pages and paused here and there to read, but the pages
themselves were a good average of four lines of text to the rest of the
page full of nuclear equations.
Tom Lionel snorted. He ran down through one of the arguments and
followed it to conclusion.
"Why can't he get something worth reading?" he yawned, putting the
book back in its place. "Darned impractical stuff." As usual with a man
who spends much time in his own company, Tom Lionel talked aloud
to himself—and occasionally was known to answer himself back.
"The whole trouble with the entire tribe of physicists per se is the fact
that once, someone told one of them that he was a theorist, an
idealist, and a dealer in the abstract. Now the bunch of them are
afraid to do anything practical because they're afraid if they do,
people won't know they're physicists. Physicists are a sort of
necessary, end-product evil."

During the breakfast section of Tom's morning duties, Tom read the
latest copy of the "Proceedings of the I.R.E." with some relish. A
paper on the "Crystallographic Generation of Microwaves" complete
with plainly manipulated differential calculus and engineering data
occupied most of his time. The rest of the time through coffee he was
making marks on the tablecloth with the egg-laden end of his fork and
trying to fit the crystallographic generation of microwaves into a
problem that made the article most timely; the solution for which he
had been seeking for a week.
The mail arrived. Three household bills were filed in the desk to await
the first of the month. Two advertisements were filed into the
wastebasket. One thick letter addressed to Thomas Lionel, Ph.D.,
M.M., was taken carefully between thumb and forefinger and
deposited in a letter file.
Tom then inspected the other letter file and found two letters
addressed to Tom Lionel, Consulting Engineer, which he opened and
read. One was from a concern in Cedar Rapids that wanted some
information on a method of induction heating glued joints selectively
without waiting for the normal drying time. The other was a letter from
a medium-sized town in Illinois pertaining to some difficulty they were
having with police-radio coverage of that area.
Both letters meant money, and Tom Lionel set the first aside while he
started to work on the second. From the engineering data supplied by
the local engineer, Tom decided that a change in antenna height and
a conversion from quarter-wave current fed to a one and one quarter-
wave current fed antenna would give the desired coverage. He
concluded his letter with four pages of calc, seven diagrams, and as a
last measure dropped a photograph of a similar installation in the
envelope.
He gloated. That would net him a pretty penny. The guy who hung
that antenna on top of the water tank thought he was smart, getting
all that height. But the roof was metal, and therefore the radiation
angle took off from the rooftop as a basis rather than the true ground
a hundred feet below.
The tank top was greater than three wave lengths in diameter, and
conical to boot. Tom grinned at the maze of mathematics that solved
it—and as far as he was concerned it was solved, for Tom Lionel was
a top-flight engineer.
He checked on his calendar. Metal for the sonic job was not due for a
week yet; a minute casting was still being held up for the foundry's
pleasure; and the life-test of the bearing-jewel for the Watson
Instrument Corporation was still on. Good jewel that. No sign of
freeze-up or wear-out after twenty-seven million cycles.
"Theory of Monomolecular Films be hanged," he snorted. "He's the
kind of a guy that would try to analyze the brew that MacBeth's three
witches were cooking up. And don't ask why!"
What he objected to most was the other's unconcern at spending
money. Nine bucks and fifty cents for a book of the most questionable
theory—and nine fifty that the other didn't really earn. It was getting
worse. The other was really beginning to obtrude. He hadn't minded,
particularly, except for the mental anguish. He'd become reconciled to
it by sheer rationalization. Way, way down deep in his heart he knew
that he'd have enjoyed being a physicist himself. But physicists were
not particularly practical, and money was made with practical things.
He knew, and recognized, that his retreat from being a physicist
himself had given him a dislike for the breed, especially when he
knew that solution of a problem was theirs, but reduction to practice
was his. He was continuously being forced to take some physicist's
wild-haired scheme and making it cook meat, open cans, or dig post
holes. The physicist had all the fun of standing on the threshold and
delving into phenomena that abounded just over the line. And then
instead of working on the suggestion that the physicist had located in
the wilderness, the physicist just tossed it over his shoulder into
Lionel's lap and went on digging.
Obviously it must be fun to dig in the unknown, but why in the name
of sense—
"Theory of Monomolecular Films in Fission-Reaction," scowled Tom
Lionel. "A hypothesis on a theory for an idea, based upon a practical
impossibility, and directed at a problem solvable only by concentrated
masses. He should be working in a negative universe where
nonmatter repels nonmatter disproportionately to the nonmass and
inversely disproportional to the not-square of the not-distance
between. Holy Entropy."

Tom Lionel went out of the house, mentally tinkering with the glue-
joint heating problem. That shouldn't be hard, he thought, high-
frequency heating was no trick, though the furniture company
probably had no one in the place that knew what high frequency
really meant.
He'd take a chair, rip it apart at the joints, and start tinkering with the
big radio-frequency heater in the lab. Another fat consulting fee—
eminently practical and satisfying—from the simple engineering of a
means to accelerate the drying of glue by electronics.
Eminently practi—hell!
Lionel stared. The door closed slowly behind him as he walked ever
so slowly across the floor of the lab. There was his radio-frequency
heater, all right. But it was not in its usual place. It was across the
room nuzzling up against another piece of equipment—the latter new,
shining, and absolutely alien to the lab.
Tom went over to the set-up and inspected it with critical derision.
The alien piece of equipment had been a standard model of mass
spectrograph. Its sleek sides were gaping open, and the high-
frequency heater was permanently wired—piped—into the very heart
of the spectrograph. Peering into the maze of one-inch copper tubing
that led from the output of the high-frequency heater to the insides of
the spectrograph, Lionel saw at once what the reason was.
The spectrograph had been overhauled by the physicist. It now
contained a pair of "D" chambers.
Operating on the cyclotron principle, the spectrograph was using the
output of the high-frequency heater to energize the D chambers.
Lionel nodded. The frequency was about right; could be adjusted to
the proper value without any trouble at all. He felt an infinitesimally
short twitch of admiration for the idea before he started to roar in
anguish.
His first impulse was to rip the gadget apart so that he could go to
work on something practical. But the engineer's admiration for the
idea stopped him.
But this was getting thick.
It had been getting thicker for a long time. It was getting intolerable.
He didn't mind too much having volumes of utterly cock-eyed theory
about the place, but when the physicist starts to appropriate
equipment for his screwball ideas, it was time to call a halt.
Lionel left the laboratory, returned to his house, and called a
psychiatrist.
An hour later he was in Dr. Hamilton's office.
"Why are you here?" asked Hamilton pleasantly.
"I want to get rid of a physicist."
"Tell him to go away."
"Can't. Impossible."
"Nothing is impossible."
"Look, doctor, have you ever tried to light a safety match on a wet bar
of soap?"
"Suppose you tell me about it, then."

Tom Lionel was more than talkative for a half hour.


"A clear-cut case of split-personality. A most remarkable cleavage."
Lionel muttered something.
"What did you say?"
"I'd rather not repeat it," said Tom.
"Please—it may have a bearing on your case."
"I was merely thinking of an hypothetical case. Says the doctor to his
associate: 'Doctor, look at this magnificent tumor,' and his buddy
answers: 'Lovely, but you should see my case of angina; it's positively
beautiful.'"
"Oh?"
"So I'm a most remarkable case, huh?"
"You are. There seems to be a deep-seated liking for one another
that has been barred psychologically by certain factors in your youth.
You play chess. You respect one another's property—"
"That's what you say. The other bird just screwed up my dielectric
heater to fiddle up a cyclotronic spectrograph."
"Might try putting it to work," observed Hamilton.
"Oh, I will. After all, he can't get ahead of me."
"Then why the outcry?"
"Because who knows what he'll do next."
"He's appropriated things before?"
"Only to the extent of buying books."
"What manner of books?"
"The last one he purchased was entitled 'The Theory of
Monomolecular Films in Fission-Reaction.'"
"Mind explaining that? It sounds like Greek to me."
Lionel smiled tolerantly. "If you have a flat table and a pile of kid's toy
blocks, you can either build a structure or lay 'em on the table in a
single layer. Since molecules are often called the building-blocks of
the universe, the analogy is quite clear. The blocks in a single layer
form a monomolecular layer. Fission reaction is a self-sustaining
nuclear reaction."
"Sounds quite erudite."
"In the first place, no one with any sense would try to make use of it.
It is the type of volume that a physicist would write in the hope that he
will get letters pro and con on the subject which will be useful in
forming a later theory."
"Then it is not a complete waste of time."
"Any time I lay out nine bucks for a half-inch of paper—"
"Expensive, isn't it?" asked the doctor.
"Sure. Those things are not best sellers, usually. The publisher puts it
out in the name of science and must at least get his printing cost out
of the very limited edition."
"I see. And you want to get rid of this physicist?"
"Who wouldn't? After all, I had this body first. He's an interloper."
"Seems that way."
"It is—and it's annoying."
"We may be able to do something about it," said the psychiatrist.
"Permit me to think about this for a few days. We'll have another
consultation in a week. We may require another one before I make a
decision. But it seems to me that you are both intelligent, useful
citizens. Neither of you is irresponsible or dangerous. You have
enough money to afford schizophrenia for a while. Especially if the
personality B dreams up things that personality A makes practical,
financially advantageous use of. Ergo you need fear nothing for a few
weeks."
"Ugh. Means I'll have to go out and buy another high-frequency
heater. O.K., doctor. I'll lay low."

Thomas Lionel, Ph.D., M.M., awoke with a shake of his head. At


once, he was out of bed. He consulted first the calendar and then the
clock. The thought struck him funny. He hadn't been drinking, but the
idea of looking at a calendar upon awakening might be construed as
an admission that he didn't know what time of what day it was.
Or mayhap what month.
"I've been away again," he grunted.
He dressed by stages. At the trousers department, Thomas
wandered out into the living room and stood over the chessboard,
studying the set-up.
He removed the little sign that said:

CHECK!
and dropped it into the drawer again. He moved his king aside with a
contemplative smile. His queen was gone on the next move, he knew.
So he had lost a major piece. So that other bird thought that losing a
major piece was bad, huh? Well, winning battles does not count—it is
a matter of who wins the last one.
He found the volume on the theory of monomolecular films and
started to read with relish. Over coffee, at breakfast, Thomas made
notations on the margin of the book with a pencil; checked some of
the equations and though he found them balanced properly, the
author was amiss in not considering the lattice-effect in his
presumptions. No monomolecular film could follow that type of
reaction simply because—well, it could follow it, but since the thing
was to take place in a monomolecular film, the fission-reaction and
the radiation byproducts that cause the self-sustaining nature could
only be effective in a plane of molecular thickness. That meant a
.999999% loss, since the radiation went off spherically. Fission-
reaction might take place, but it would be most ineffective. Besides,
the equations should have taken that into account.
He stopped by the desk and wrote for a half hour, filling seventeen
pages full of text and mathematics, explaining the error in the author's
presumption.
He sealed it up and mailed it with some relish. No doubt that letter
would start a fight.
He found his letter in the letter file and read it. It was a request to
indulge in some basic research at a fancy figure, but Thomas was not
particularly interested. He was thinking of another particular line of
endeavor. He dropped the letter into the wastebasket.
He went into the lab and took a look at his cyclotronic spectrograph.
There was a letter hung on the front. Thomas opened it and read:
Dear Isaac Newton:
I don't particularly mind your laying out thirty-five hundred bucks for a
mass spectrograph.
Appropriating my high-frequency generator didn't bother me too
much.
Nor did your unsymmetrical wiring and haywire peregrinations in and
about the two of them annoy (too acutely) my sense of mechanical
and electrical precision.
But the idea of your using the ##&&%!! spectrograph only once—just
for pre-change calibration—makes me madder than mad!
Sincerely,
Tom Lionel,
Consulting Engineer
Thomas grinned boyishly and picked up the notebook on top of the
high-frequency heater. It was Tom's, and the physicist riffled through it
to the last-used pages. He found considerable in the way of notes
and sketches on the cyclotronic spectrograph. Cut in size by about
one quarter, the thing would be not only a research instrument of
value, but would be of a price low enough to make it available to
schools, small laboratories, and perhaps production-lines—if Tom
Lionel could find a use for a mass spectrograph on a production line.
Thomas grinned again. If it were possible, Tom would certainly have it
included on some production line, somewhere.
He looked the spectrograph over and decided that it was a fine piece
of apparatus. So it wasn't the shining piece of commercial panel and
gleaming meters. The high-frequency plumbing in it had the touch of
a one-thumbed plumber's apprentice after ten days' drinking and the
D plates were soldered together with a heavy hand. But it did work—
and that's all he cared. The knobs and dials he had added were
sticking out at all angles, but they functioned.
And the line-voltage ripple present in the high-frequency generator
made a particular mess out of the spectrograph separation. But
electronic heaters do not normally come luxuriously equipped with
rectifiers and filters so that the generator tubes were served with pure
direct current—the circuit was self-rectified which would give a
raucous signal if used as a radio transmitter. That generated a ripple-
varied signal for the D plates and it screwed up the dispersion. The
omission of refinement satisfied Thomas. So it wasn't perfect. It would
be by the time Tom Lionel got through with it.
And for the time being, Thomas would leave it alone. No use trying to
make it work until Tom made an engineering model out of the
physicist's experiment.
Smiling to himself, Thomas went to work in the laboratory. He ignored
Tom's experiments and started a few of his own accord.
Some hours later, the doorbell rang and Thomas went to the door to
find a letter, addressed to Thomas Lionel, Ph.D. It was from an Arthur
Hamilton, M.D.
"Hm-m-m," said Thomas. "Is there something the matter with me?"
He slit the envelope and removed a bill for consultation.
"Consultation? Consultation? What in the name of all that's unholy is
he consulting a doctor about? Or is the doctor consulting—no, the bill
is rendered in the wrong direction. I know my consulting engineer."
The physicist put on his hat and headed forth. It was not much later
that he was sitting again in the same chair, facing Hamilton.
"You're back."
"Nope," smiled Thomas. "I'm here, not back."
"But you were here last week."
"That was another fellow. Look, Hamilton, I think I require your
assistance. I have an engineer that is no end of bother."
"Want to get rid of him, huh?" answered Hamilton. The suppressed
smile fought valiantly and won, and the doctor's face beamed and
then he broke into laughter. "What am I, anyway? Man, I can't take
money from both sides. That's ... that's ... barratry, or something."
"I'm the same man."
"Nope. You are not."
"Well, by and large, I thought it might be of interest to you to hear
both sides. It might be that I am a useful citizen in spite of what the
engineer says."
"The engineer's opinion is that no physicist is worth an unprintable."
"The physicist's opinion is that all engineers are frustrated physicists."
"Might challenge him to a fight."
"Have. But chess isn't too satisfying. I want blood."
"It's your blood."
"That's the annoying part of it all. He seems entirely a different
fellow."
"The cleavage is perfect. You would think him a separate entity."
Hamilton paused, "But neither of you refer to the other by name. That
indicates a psychological block that may be important evidence."
"O.K., what do we do?"
"I must discover the reason for the split personality."
"I can give you that reason. The engineer was forced into being a
practical man because money lies in that direction. Upon getting out
of college, there was a heavy debt. It was paid off by hard work—a
habit formed and never broken. Bad habits, you know, are hard to
break."
"Interesting."
"Well, the desire to delve into the physicist's realm stayed with the
engineer, but people who had heavy purses were not interested in
new ways to measure the ether-drift or the effect of cosmic radiation
on the physical properties of carbon. Money wants more perfect
pencil sharpeners, ways of automatically shelling peas, and efficient
methods of de-gassing oil. All these things are merely applications in
practice of phenomena that some physicist has uncovered and
revealed and put on record so that some engineer can use the effect
to serve his ends.
"At any rate, the desire to be a physicist is strong, strong enough to
cause schizophrenia. I, Dr. Hamilton, am a living, breathing, talking
example that an engineer is but a frustrated physicist. He is the
troubled one—I am the stable personality. I am happy, well-adjusted,
and healthy."
"I see. Yet he has his point. You, like other physicists, are not
interested in making money. How, then, do you propose to live?"
"A physicist—or an engineer—can always make out well. The bank
account at the last sitting was something like ninety-four thousand,
six hundred seventeen dollars and thirty-four cents."
"That's quite a lot of money."
"The engineer considers it a business backlog," said Thomas.
"Equipment is costly. Ergo—see?"
"I see. Seems you laid out a large sum of money for a mass
spectrograph."
"I did."
"And what did he do?"
"He made notes on it and is going to peddle it as a commercial
product. He'll probably make fifty thousand dollars out of it."
"I suggested that," admitted the psychiatrist.
"That's all right. I don't mind. It sort of tickles me, basically. I do things
constantly that make him roar with anguish. And then his only rebuttal
is to take it and make something practical out of it."
"I see."
"That, you understand, is the game that has been going on for some
time between all physicists and engineers."
"If you'd leave one another alone, you'd all be better off," said
Hamilton. "From what I've heard, the trouble lies in the fact that
physicists are not too interested in the practical details, whilst the
engineer resents the physicist's insistance upon getting that last point
zero two percent of performance."
"Are you willing to give me my answer?"
"What answer?"
"How do I get rid of the engineer? One of us has got to go, and being
the stable, happy one, I feel that all in all I am the best adjusted and
therefore the most likely to succeed. After all, I am the ideal
personality according to the other one. He'd like to be me. That's why
he is, from time to time."
"Sort of a figment of your own imagination."
"That's me."
"Then I wonder—Yet, I did accept his case, not yours."

You might also like