100% found this document useful (2 votes)
8 views

[FREE PDF sample] (Ebook) How JavaScript Works: Master the Basics of JavaScript and Modern Web App Development by Jonathon Simpson ISBN 9781484297377, 1484297377 ebooks

The document promotes various eBooks related to JavaScript and modern web development, including titles by Jonathon Simpson and others. It provides links to download these eBooks in multiple formats such as PDF, ePub, and MOBI. Additionally, it outlines the content structure of Jonathon Simpson's book, 'How JavaScript Works,' which covers fundamental concepts and practical applications of JavaScript.

Uploaded by

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

[FREE PDF sample] (Ebook) How JavaScript Works: Master the Basics of JavaScript and Modern Web App Development by Jonathon Simpson ISBN 9781484297377, 1484297377 ebooks

The document promotes various eBooks related to JavaScript and modern web development, including titles by Jonathon Simpson and others. It provides links to download these eBooks in multiple formats such as PDF, ePub, and MOBI. Additionally, it outlines the content structure of Jonathon Simpson's book, 'How JavaScript Works,' which covers fundamental concepts and practical applications of JavaScript.

Uploaded by

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

Download the Full Ebook and Access More Features - ebooknice.

com

(Ebook) How JavaScript Works: Master the Basics of


JavaScript and Modern Web App Development by
Jonathon Simpson ISBN 9781484297377, 1484297377

https://ebooknice.com/product/how-javascript-works-master-
the-basics-of-javascript-and-modern-web-app-
development-54544624

OR CLICK HERE

DOWLOAD EBOOK

Download more ebook instantly today at https://ebooknice.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

(Ebook) How JavaScript Works: Master the Basics of


JavaScript and Modern Web App Development by Jonathon
Simpson ISBN 9781484297384, 1484297385
https://ebooknice.com/product/how-javascript-works-master-the-basics-
of-javascript-and-modern-web-app-development-54604020

ebooknice.com

(Ebook) JavaScript for Modern Web Development: Building a


Web Application Using HTML, CSS, and Javascript by ALOK
RANJAN, ABHILASHA SINHA, RANJIT BATTEWAD
https://ebooknice.com/product/javascript-for-modern-web-development-
building-a-web-application-using-html-css-and-javascript-49177184

ebooknice.com

(Ebook) The Modern Web: Multi-Device Web Development with


HTML5, CSS3, and JavaScript by Gasston, Peter ISBN
9781593274870, 1593274874
https://ebooknice.com/product/the-modern-web-multi-device-web-
development-with-html5-css3-and-javascript-55377770

ebooknice.com

(Ebook) The Modern Web: Multi-Device Web Development with


HTML5, CSS3, and JavaScript by Peter Gasston ISBN
9781593274870, 1593274874
https://ebooknice.com/product/the-modern-web-multi-device-web-
development-with-html5-css3-and-javascript-4167470

ebooknice.com
(Ebook) JavaScript for Web Developers: Understanding the
Basics by Mark Simon ISBN 9781484297735, 1484297733

https://ebooknice.com/product/javascript-for-web-developers-
understanding-the-basics-53488768

ebooknice.com

(Ebook) Modern Web Development with Deno: Develop Modern


JavaScript and TypeScript Code with Svelte, React, and
GraphQL by Mayur Borse ISBN 9789355510969, 9355510969
https://ebooknice.com/product/modern-web-development-with-deno-
develop-modern-javascript-and-typescript-code-with-svelte-react-and-
graphql-50781578
ebooknice.com

(Ebook) JavaScript Creativity: Exploring the Modern


Capabilities of JavaScript and HTML5 by Hudson, Shane ISBN
9781430259442, 1430259442
https://ebooknice.com/product/javascript-creativity-exploring-the-
modern-capabilities-of-javascript-and-html5-55920250

ebooknice.com

(Ebook) JavaScript Frameworks for Modern Web Development,


2nd Edition by Sufyan bin Uzayr , Nicholas Cloud , Tim
Ambler ISBN 9781484249956, 148424995X
https://ebooknice.com/product/javascript-frameworks-for-modern-web-
development-2nd-edition-50195408

ebooknice.com

(Ebook) Practical Modern JavaScript: Dive into ES6 and the


Future of JavaScript by Nicolás Bevacqua ISBN
9781491943533, 149194353X
https://ebooknice.com/product/practical-modern-javascript-dive-into-
es6-and-the-future-of-javascript-10481740

ebooknice.com
How JavaScript
Works
Master the Basics of JavaScript and
Modern Web App Development

Jonathon Simpson
How JavaScript Works
Master the Basics of JavaScript
and Modern Web App
Development

Jonathon Simpson
How JavaScript Works: Master the Basics of JavaScript and Modern Web
App Development

Jonathon Simpson
Belfast, Antrim, UK

ISBN-13 (pbk): 978-1-4842-9737-7 ISBN-13 (electronic): 978-1-4842-9738-4


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

Copyright © 2023 by Jonathon Simpson


This work is subject to copyright. All rights are reserved 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.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark
symbol with every occurrence of a trademarked name, logo, or image we use the names, logos,
and images only in an editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of opinion as to whether or not
they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the authors nor the editors nor the publisher can accept any legal
responsibility for any errors or omissions that may be made. The publisher makes no warranty,
express or implied, with respect to the material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: James Robinson-Prior
Development Editor: James Markham
Editorial Assistant: Gryffin Winkler
Cover designed by eStudioCalamar
Cover image designed by onlyyouqj on freepik
Distributed to the book trade worldwide by Springer Science+Business Media New York, 1
New York Plaza, Suite 4600, New York, NY 10004-1562, USA. Phone 1-800-SPRINGER, fax (201)
348-4505, e-mail [email protected], or visit www.springeronline.com. Apress Media,
LLC is a California LLC and the sole member (owner) is Springer Science + Business Media
Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail [email protected]; for reprint,
paperback, or audio rights, please e-mail [email protected].
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook
versions and licenses are also available for most titles. For more information, reference our Print
and eBook Bulk Sales web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available
to readers on GitHub. For more detailed information, please visit https://www.apress.com/gp/
services/source-code.
Paper in this product is recyclable
Table of Contents
About the Author���������������������������������������������������������������������������������xi

About the Technical Reviewer�����������������������������������������������������������xiii

Introduction����������������������������������������������������������������������������������������xv

Chapter 1: Introduction to JavaScript��������������������������������������������������1


JavaScript Fundamentals�������������������������������������������������������������������������������������2
JavaScript’s Type Classification����������������������������������������������������������������������3
What Is JavaScript Used For?��������������������������������������������������������������������������4
Writing JavaScript�������������������������������������������������������������������������������������������5
Summary������������������������������������������������������������������������������������������������������������14

Chapter 2: Code Structure and Logical Statements����������������������������15


Getting Started����������������������������������������������������������������������������������������������������15
Common Code Conventions��������������������������������������������������������������������������������17
Semicolons����������������������������������������������������������������������������������������������������17
Spacing����������������������������������������������������������������������������������������������������������18
Variable and Function Naming����������������������������������������������������������������������19
JavaScript Variables��������������������������������������������������������������������������������������������19
Setting Variables with let�������������������������������������������������������������������������������20
Setting Variables with var������������������������������������������������������������������������������22
Setting Variables with const��������������������������������������������������������������������������23
Defining Variables Without Values�����������������������������������������������������������������25

iii
Table of Contents

Assignment Operators����������������������������������������������������������������������������������������26
Variable Concatenation����������������������������������������������������������������������������������27
JavaScript Comments�����������������������������������������������������������������������������������������29
Logical Statements���������������������������������������������������������������������������������������������30
If…else Statements��������������������������������������������������������������������������������������30
Switch Statements����������������������������������������������������������������������������������������33
Block Scoping with Logical Statements��������������������������������������������������������36
Conditional Operator in Variables������������������������������������������������������������������38
Logical Statement Comparison Operators�����������������������������������������������������38
Logical Statement Logical Operators������������������������������������������������������������41
Summary������������������������������������������������������������������������������������������������������������42

Chapter 3: Introduction to Objects, Arrays�����������������������������������������43


Arrays������������������������������������������������������������������������������������������������������������������43
Getting the Length of an Array�����������������������������������������������������������������������44
Getting the Last Element of an Array�������������������������������������������������������������45
Array Manipulation Methods�������������������������������������������������������������������������������46
Push and Unshift�������������������������������������������������������������������������������������������47
Pop and Shift�������������������������������������������������������������������������������������������������47
Splice�������������������������������������������������������������������������������������������������������������48
Objects����������������������������������������������������������������������������������������������������������������49
Accessing Object Data�����������������������������������������������������������������������������������51
Object Mutability�������������������������������������������������������������������������������������������55
Spread Syntax or the “Three Dots”���������������������������������������������������������������58
Prototype-Based Programming���������������������������������������������������������������������������59
Prototypical Inheritance��������������������������������������������������������������������������������61
[[Prototype]] vs. prototype (and __proto__)��������������������������������������������������63
Object Shallow and Deep Copies�������������������������������������������������������������������65
Summary������������������������������������������������������������������������������������������������������������68

iv
Table of Contents

Chapter 4: Loops and Iterables�����������������������������������������������������������69


Loops������������������������������������������������������������������������������������������������������������������69
Break and Continue in Loops�������������������������������������������������������������������������73
Loop Labels���������������������������������������������������������������������������������������������������73
Iteration���������������������������������������������������������������������������������������������������������������75
Iterables and For Loops���������������������������������������������������������������������������������76
Array forEach methods����������������������������������������������������������������������������������78
String Iteration�����������������������������������������������������������������������������������������������78
Iteration Protocol�������������������������������������������������������������������������������������������������79
Objects Are Not Iterable by Default����������������������������������������������������������������82
Summary������������������������������������������������������������������������������������������������������������85

Chapter 5: References, Values, and Memory Management����������������87


Introduction���������������������������������������������������������������������������������������������������������87
Stacks�����������������������������������������������������������������������������������������������������������������88
The Event Loop����������������������������������������������������������������������������������������������90
The Heap�������������������������������������������������������������������������������������������������������������93
Object and Reference Equality����������������������������������������������������������������������94
Summary������������������������������������������������������������������������������������������������������������97

Chapter 6: Functions and Classes������������������������������������������������������99


Introduction to Functions������������������������������������������������������������������������������������99
Running Arguments with the “Three Dots”�������������������������������������������������102
Alternative Ways to Call Functions��������������������������������������������������������������������102
Unnamed Function Expressions������������������������������������������������������������������103
Anonymous Functions���������������������������������������������������������������������������������103
Functions with Arrow Notation��������������������������������������������������������������������104

v
Table of Contents

Functions and the “this” Keyword��������������������������������������������������������������������104


Sloppy Mode������������������������������������������������������������������������������������������������105
Arrow Notation Functionality with this��������������������������������������������������������106
Calling Functions with Context�������������������������������������������������������������������������107
Constructor Functions in JavaScript�����������������������������������������������������������������110
Additional Function Methods�����������������������������������������������������������������������113
Getters and Setters�������������������������������������������������������������������������������������������114
Generator Functions������������������������������������������������������������������������������������������115
Classes��������������������������������������������������������������������������������������������������������������117
Classes and Constructor Functions�������������������������������������������������������������117
Class Methods���������������������������������������������������������������������������������������������118
Class Method Types�������������������������������������������������������������������������������������121
Class Inheritance via Extends����������������������������������������������������������������������124
Summary����������������������������������������������������������������������������������������������������������129

Chapter 7: Types�������������������������������������������������������������������������������131
Primitive Types��������������������������������������������������������������������������������������������������131
Primitive Wrappers��������������������������������������������������������������������������������������������133
Using Wrappers to Create Types�����������������������������������������������������������������������136
The Number Type and NaN�������������������������������������������������������������������������������137
Number Type Mathematics��������������������������������������������������������������������������139
Mathematical Methods��������������������������������������������������������������������������������141
The Date Type����������������������������������������������������������������������������������������������������143
The Symbol Type�����������������������������������������������������������������������������������������������147
Truthy and Falsy Types��������������������������������������������������������������������������������������149

vi
Table of Contents

Truthy and Falsy Operators�������������������������������������������������������������������������������150


Logical AND Operator����������������������������������������������������������������������������������150
Logical OR Operator�������������������������������������������������������������������������������������151
Nullish Coalescing���������������������������������������������������������������������������������������152
Optionality���������������������������������������������������������������������������������������������������������153
Summary����������������������������������������������������������������������������������������������������������157

Chapter 8: Manipulating and Interacting with HTML������������������������159


Window and Document Objects������������������������������������������������������������������������159
The Window Object��������������������������������������������������������������������������������������160
The Document Object Model�����������������������������������������������������������������������162
Selecting HTML Elements���������������������������������������������������������������������������������163
The Order of HTML���������������������������������������������������������������������������������������165
NodeLists and HTMLCollections������������������������������������������������������������������167
Manipulating HTML After Selection�������������������������������������������������������������170
Adding Events to HTML Elements���������������������������������������������������������������������173
Creating a Modal Window����������������������������������������������������������������������������173
Creating a Counter���������������������������������������������������������������������������������������176
Event Types��������������������������������������������������������������������������������������������������177
Drag and Drop���������������������������������������������������������������������������������������������190
The e variable����������������������������������������������������������������������������������������������194
Creating New Elements with JavaScript�����������������������������������������������������������195
Manipulating CSS with JavaScript��������������������������������������������������������������������199
HTMLElements and Changing Styles in JavaScript�������������������������������������199
Adding New Style Sheets to HTML Pages���������������������������������������������������200
Setting CSS Variables����������������������������������������������������������������������������������200
Getting CSS Properties and HTML Dimensions�������������������������������������������201
Summary����������������������������������������������������������������������������������������������������������203

vii
Table of Contents

Chapter 9: Maps and Sets�����������������������������������������������������������������205


Sets�������������������������������������������������������������������������������������������������������������������205
Modifying Sets���������������������������������������������������������������������������������������������207
Checking Set Membership��������������������������������������������������������������������������208
Checking Set Size����������������������������������������������������������������������������������������208
Merging Sets�����������������������������������������������������������������������������������������������208
Set Iteration and Values�������������������������������������������������������������������������������209
Maps�����������������������������������������������������������������������������������������������������������������212
Retrieving Map Properties���������������������������������������������������������������������������215
Checking for Key Existence on a Map���������������������������������������������������������217
Telling How Big a Javascript Map Is������������������������������������������������������������217
Iterating, Merging, and Accessing Maps������������������������������������������������������218
Keys and Values in Maps�����������������������������������������������������������������������������219
Serialization of Maps in JavaScript�������������������������������������������������������������221
Summary����������������������������������������������������������������������������������������������������������222

Chapter 10: Fetching Data, APIs, and Promises�������������������������������223


What Are APIs?��������������������������������������������������������������������������������������������������224
Understanding HTTP�����������������������������������������������������������������������������������������226
RESTful Design��������������������������������������������������������������������������������������������228
Understanding APIs Through a Node.JS Web Server�����������������������������������230
Testing Endpoints with Postman�����������������������������������������������������������������236
The Benefits of APIs�������������������������������������������������������������������������������������236
Sending Data to APIs with JSON�����������������������������������������������������������������238
The fetch Function��������������������������������������������������������������������������������������������240
A Deep Dive into Fetch Options�������������������������������������������������������������������243

viii
Table of Contents

Asynchronicity and Promises����������������������������������������������������������������������������248


Promise Methods: then, finally, and catch���������������������������������������������������250
The await Keyword��������������������������������������������������������������������������������������252
Useful Promise Methods������������������������������������������������������������������������������253
Summary����������������������������������������������������������������������������������������������������������258

Chapter 11: Introduction to Web APIs����������������������������������������������259


Web APIs�����������������������������������������������������������������������������������������������������������259
Frequently Used Web APIs��������������������������������������������������������������������������������261
URL API��������������������������������������������������������������������������������������������������������262
Web Storage API������������������������������������������������������������������������������������������262
Web Notifications API����������������������������������������������������������������������������������265
History API���������������������������������������������������������������������������������������������������266
Summary����������������������������������������������������������������������������������������������������������267

Chapter 12: Errors and the Console�������������������������������������������������269


The Console Object�������������������������������������������������������������������������������������������269
Console Errors, Debugs, Warnings, and Info������������������������������������������������270
Console Timing��������������������������������������������������������������������������������������������������271
Console Counting�����������������������������������������������������������������������������������������273
Other Useful Console Methods��������������������������������������������������������������������������274
Console Grouping����������������������������������������������������������������������������������������274
Console Tables���������������������������������������������������������������������������������������������275
Errors and Exceptions���������������������������������������������������������������������������������������277
try…catch���������������������������������������������������������������������������������������������������278
Generating Errors����������������������������������������������������������������������������������������281
Handling Specific Errors������������������������������������������������������������������������������282
Summary����������������������������������������������������������������������������������������������������������283

ix
Table of Contents

Chapter 13: The Canvas��������������������������������������������������������������������285


Introduction�������������������������������������������������������������������������������������������������������286
Drawing and Images�����������������������������������������������������������������������������������������288
Drawing Rectangles������������������������������������������������������������������������������������288
Drawing Circles�������������������������������������������������������������������������������������������291
Drawing Triangles����������������������������������������������������������������������������������������293
Drawing Images������������������������������������������������������������������������������������������295
Drawing Text������������������������������������������������������������������������������������������������297
Interactivity and Creating a Drawing Application����������������������������������������������299
Animations��������������������������������������������������������������������������������������������������������303
Summary����������������������������������������������������������������������������������������������������������305

Chapter 14: Web Workers and Multithreading����������������������������������307


Introduction�������������������������������������������������������������������������������������������������������307
Using Web Workers�������������������������������������������������������������������������������������������309
Sending Messages to and from Web Workers��������������������������������������������������309
Restrictions on Web Workers�����������������������������������������������������������������������311
Conclusion��������������������������������������������������������������������������������������������������������313

Index�������������������������������������������������������������������������������������������������315

x
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.

xi
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.

xiii
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.

xv
CHAPTER 1

Introduction
to JavaScript
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.

© Jonathon Simpson 2023 1


J. Simpson, How JavaScript Works, https://doi.org/10.1007/978-1-4842-9738-4_1
Chapter 1 Introduction to JavaScript

• 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.

2
Chapter 1 Introduction to JavaScript

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.

3
Chapter 1 Introduction to JavaScript

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.

4
Chapter 1 Introduction to JavaScript

• 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>

5
Chapter 1 Introduction to JavaScript

<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>

6
Chapter 1 Introduction to JavaScript

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.

7
Chapter 1 Introduction to JavaScript

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.

8
Chapter 1 Introduction to JavaScript

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.

9
Chapter 1 Introduction to JavaScript

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

10
Chapter 1 Introduction to JavaScript

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.

11
Chapter 1 Introduction to JavaScript

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

12
Chapter 1 Introduction to JavaScript

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.

13
Chapter 1 Introduction to JavaScript

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.

14
CHAPTER 2

Code Structure and


Logical Statements
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>

© Jonathon Simpson 2023 15


J. Simpson, How JavaScript Works, https://doi.org/10.1007/978-1-4842-9738-4_2
Chapter 2 Code Structure and Logical Statements

      <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!

16
Chapter 2 Code Structure and Logical Statements

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.

17
Chapter 2 Code Structure and Logical Statements

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.

18
Chapter 2 Code Structure and Logical Statements

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.

19
Chapter 2 Code Structure and Logical Statements

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

20
Chapter 2 Code Structure and Logical Statements

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)

21
Chapter 2 Code Structure and Logical Statements

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

22
Chapter 2 Code Structure and Logical Statements

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.

23
Chapter 2 Code Structure and Logical Statements

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)

24
Chapter 2 Code Structure and Logical Statements

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

25
Chapter 2 Code Structure and Logical Statements

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)

26
Chapter 2 Code Structure and Logical Statements

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

27
Chapter 2 Code Structure and Logical Statements

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

28
Chapter 2 Code Structure and Logical Statements

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! */

29
Chapter 2 Code Structure and Logical Statements

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.

30
Chapter 2 Code Structure and Logical Statements

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:

31
Other documents randomly have
different content
SOBERBA

Cor de promo amontonans’as nubes


Rodan lentas as ondas d’o mar,
E zoando con son pavoroso
Ven o huracan.

¡Que cargado está o ceo e que triste,


Qu’escuro, que negro, tornandose vay!
Encendámo-l-a vela bendita
Qu’hay tempestá.

Cabalgando n’as alas d’os ánxeles,


Por mandado de Dios correrán,
As centelas qu’asombran os malos
C’o seu lostregar.

Nove follas d’olivo queimemos


Por que alexen de nos todo mal,
Que nos libren de rayo e centela
Que nos matar.

O trisaxio cantemos en coro...


Incrinaivos y á Dios adorai
Pois si trona é que quer recordarnos
Qu’é grand’e inmortal.

¡Santo, santo! din todos á un-ha


Fillos e nay...
Todos non, qu’un soberbo e sañudo
Calado está.
Mais os tronos afunden os ceos
E cega d’os lóstregos o brilo fatal
¡Ou, que noite!... que noite terrible
De tempestás.

El Señor est’airado... ¡incrinemonos!


¡Ey! malvados d’a terra tembrai,
O que salvo esta noite saire,
Que contar ha.

—Ña nay, a vaca marela


Tembra coma vos n’a corte.
¿Fixo algun pecado ela?
¿Virá un rayo á darlle morte?

—S’ela non fixo pecado,


Mal cristiano, ti o fixeche,
Qu’és pecador rematado
Mesmo dendes que naceche.

—¿Y a probe vaca marela


Paga, decí, o qu’eu pequei?
—Pagas ti, morrend’ela,
Di ¿con que te manterei?
¡A PROBIÑA, QU’ESTÁ XORDA!...

«Alá enriba d’a montaña,


Sai fume d’as chamineas...
Valor, meu corpiño vello,
Levaim’aló miñas pernas.
Paseniño, paseniño,
Aquí para, alí te sentas,
Irás chegando Xuana,
Á dond’as casas fomegan.
¡Dios diante! a virxe te valla,
Qu’hoxe, seica... seica... seica...
Has de comer sete cuncas
De bon caldo, c’o a da cea,
E mais compango de porco
Ou de sardiñas salpresas,
Qu’os montañeses son homes
Que cando dan, dan de veras.
Dempois, quentaráste á un lume
Grande com’un-ha fogueira,
E cando xa estés ben quente
¡Á dormir!... ¡e qu’amañeza!»

Y a vella vay, sube, sube


A costa d’o mar d’ovellas
C’un ollo posto n’o chan
Y outro ond’as casas fomegan.

Mentras tanto o sol d’a tarde


Tras d’os pinares se deita
Y aluma con tristes rayos
As sombrisas arboredas.
D’os Anxos o val hermoso,
Saban de verdor ostenta
Alá n’o fondo tranquilo
Que soaves brisas ourean.
Aquí fonte, alí regato,
A yaugua brila antr’as herbas,
Color d’ouro, qu’o postreiro
Rayo de sol fire n’elas.
Quieta, docisima calma
Arriba y en baixo reina,
A noite ven silensiosa,
Maina, pero sin estrelas.
Nin siquera un-ha relumbra
N’o firmamento, qu’espesa
Brétema tamen se corre
Po-las llanuras etereas.
Comenza á orballar, escuro
Tod’arrededor, apenas
S’acerta, o que o mais conoça,
Con camiño nin carreira.
Mas non importa por eso
Qu’o qu’é valente é de veras;
Y a vella vay sube, sube,
A costa d’o mar d’ovellas
C’un ollo posto no chan
Y outro ond’as casas fomegan,
Qu’alí relumbra un-ha luz
E vay direitiña á ela
Marmurando:—Arriba, Xuana,
Qu’ou m’engaño ou terás festa.

A esperencia insina á todos,


E ten a vella esperencia,
Por eso non pensa mal
Pensando que arriba hay festa.
Un carballo arde n’o lume,
Y arredor d’o lar se sentan
Rapazas d’alegres ollos,
Abós de brancas gadellas,
Vellas qu’inda rompen mangas
E tocan as castañetas,
Os afillados qu’a dona
Y o dono tên po-la aldea,
Y os amigos y os cuñados,
Os curmans y a parentela
Toda xunta, e mai-lo crego
Y o zuruxano d’as bestas.
Un cego c’a sua zanfona
En compaña d’outra cega,
Que si ben lle dá ô pandeiro
Fay falar as castañetas;
Un manco, un coxo, un-ha tola,
Y outros probes que se sentan
N’un tallo para déz posto
N’un curruncho d’a lareira,
E abofellas mais non caben
Anqu’algun mais vir quixera.
Foran chegando, chegando,
Mais de nove ulind’a festa,
Y á ningun botou d’a porta
A rica d’a montañesa;
Qu’hay para todos, o dia
Qu’alí cocen carne fresca
Por arrobas, e se fan
Papas d’arroz en caldeiras.
Matouse un carneiro, grande
Como un boy, e un-ha tenreira
Como un-ha vaca, e gordiña
Como un-ha cocha pequena.
Hay viño á Dios dar, un viño
D’o Riveiro, qu’é canela,
E par’a xente de menos
Hayno tamen d’o d’a terra,
Un pouco agriño, mais fresco
E sabroso como fresas.
Coceuse un-ha gran fornada
De millo branco qu’albea,
Con mixtura de centeo
Y un-ha pouca de manteiga.
Parece biscoito a broa,
Y un non se ve farto d’ela,
Qu’inda é muito mais sabrosa
Qu’os moletes qu’en tres cestas,
Escollidos, de Santiago
Trouxeron as panadeiras.
En fin, a comida roda
Po-los pés, y o viño alegra
As xentes tanto, que rabia
D’envidia a negra tristeza.
Os probes qu’alí viñeron
Y atoparon lume e mesa,
Contan contos que dan risa
Así âs mozas com’âs vellas;
Uns en verso, outros en prosa,
Pois falan en todas lengoas
Y apostan entr’eles todos
Á quen fay copras mais feitas.
Ma-l-o d’a zanfona gana,
Quell’apunta a compañeira,
E axudalle o viño branco
Con qu’a gorxa lle refrescan.

«¡Viv’a cega! ¡viv’o cego!...»


De cand’en cando lle berran,
Y-el di, berrando mais forte:
«¡Vivan eles!... ¡vivan elas!...
Y a mais bonita de todas
Que veña á darm’un-ha prenda.»
¡Ju-ju-ru-ju! Y aturuta
Hastra enxordecé-las pedras,
Y a cega dall’ô pandeiro
Y o cego toca n’as tecras
Y ô compás d’o zongue, zongue,
De novo bailan as nenas,
E din os probes, botando
Leña n’o lar: «¡Esta é festa!
¡Quen ch’hoxe andivera fora
C’a tripa toda valdeira!...»
Y un ollo botan sorrindo
Ôs feixes de palla fresca
Ond’han de dormir quentiños,
Coma rixons en caldeira,
Mentras fora zoa o vento
E ladran os cans n’as eiras.

Xa preto d’a media noite,


Dan encomenzo as peleas,
Os mozos loitan c’as mozas,
Medindo as forzas que teñan,
E n’andan en comprimentos
Para botarse por terra.
¡Si as vírades que valentes
S’amostran n’a loita as nenas!...
¡Fanlle ôs mozos cada magoa
C’as suas mans pequeneiras!...

—Un xa caiu... foy un home...


¡Ela venceu... venceu ela!
¡Ben po-la nena bonita!...
¡Que vivan as montañesas!
Que vivan, pois loitar saben...
—¡Si fixo trampa!...—él contesta
Avergonzado...—foy trampa,
Que sinon, nin cén com’ela.
—Que trampa nin que morcegos...
Vencinte...
—Non.
—Sí.
—¡Me venzas!...
E mentres que n’esto están
¡Plum! ¡plum! ¡plum! dan c’un-ha pedra
N’a porta.
—¿Quen é? perguntan.
—Son un-ha probiña vella
Que me perdin n’este monte...
Respond’un-ha voz que tembra.
¿Non me darán pousadiña,
Qu’está chovendo e lostrega?
—Vaya con Dios, xa ven tarde,
Non hay sitio;—lle contestan.
—¿Que dí, señora? Son xorda
Com’un canto... miña prenda.
Abram’a porta que Dios
Llo pagará...
—Probe vella...
Un pouco adiante, pretiño
Hay mais portas, chame n’elas.
—¿Que dí, señoriña? Mire
Qu’está un-ha noite moy fera,
E teño medo qu’os lobos
Me coman...
—¡Dios diante! ¡seica!
N’hay lobos aquí, ande, ande,
Vaya con Dios, qu’outra aldea
Hay preto.
—¿Que dí, señora?
—Vaya con Dios, non sea terca,
Qu’aquí xa non caben mais
Nin probes nin ricos, ¡eya!
—¿Que dí ña filla?... son xorda,
E non oyo anque me fendan.
¡Brrr... que frio, señoriña!...
Vosté qu’é tan limosneira
Deixem’entrar, e estarey
N’o cortelliño ond’as bestas.
¡Brrr... que morro c’a friaxe!
¡Quenja! ¡quenja! ¡quenja! ¡quenja!...
Que tos... Dios me valla... brrr...
¡Xa non podo mais!...
—Pois veña,
E si non ten onde pôrse
Brinque á cabalo d’a artesa.
Falou a dona, que tiña
O corazon de manteiga.
—¡Dios llo pague, queridiña!
Xa topará a recompensa
N’o ceu... abra, miña xoya...
Excramou de pronto a vella.
—¿Logo n’é xorda, qu’oyeu?
Dixeron dentro, antramentras
Que quitaban o tranqueiro
D’a porta.
—¿Que dí, ña-prenda?
Non ll’oyo nada, mas teño
Moito sentido...
—¡Abofellas
Que non mente!... vaya, vaya,
Adentro...
—Santas y buenas
Noites teñan mis señores...
¡Xesús! seica están de festa,
Qu’hay moita xentiña xunta.
D’hoxe n’un ano aquí os vexa.
Dió-los bendiga... el Señor
Lles dé fertuna âs mancheas
E saudiña...
—¡Amen, amen!
—Busqu’un sitio n’a lareira
E quéntese...
—¿Que me dixo?
Son xorda coma un-ha pedra,
E a mais non probey frangulla
Desd’onte â noite, e n’as venas
Xa teño o sangre callado
Po-lo frio...
Y antramentras
Qu’esto dí, vais’arrimando
Ô lume moy compangueira
C’os outros probes, e fura
Por antr’eles, por antr’elas.
Brinca por riba d’o cego,
E que queiras, que non queiras,
Sempre tembrando de frio
E xorda como un-ha pedra,
Segun di, n’o mellor sitio
Con moita homildá se senta
E arrima un mando de lume
Pr’ond’ela está.
—¡Ey, miña vella!
Mire qu’hay mais que vostede
Aquí: ¡que comenenceira
Parece!...—lle di outro probe
C’un-ha cara de desteta
Nenos.
—¿Cómo di, meu fillo?
(Sorrindo reprica ela
Sentándose mais a gusto)
Eu de calquera maneira
M’amaño; qu’así n’o ceo
M’amañe el Señor...
—¡Bah! seica
Quer facer mofa d’a xente...
¡Poche, c’o xuncras d’a vella!
Mesmo parece un espeto.
—¿Si quero un neto ña prenda?
Si m’o desen inda pode
Que pouco a pouco o bebera,
Pois teño moita sediña,
E fame, e frio...
—¡Rabéa!
¡Can! que non vin un-ha xorda
Mais fraca nin lagarteira,
¿É filla d’algun raposo?
—¿Que pille un òso?... d’a vella
Quérense rir... ¡ay Dios mio!
Pero a fam’elle moy negra:
Tráyamo s’é qu’inda ten
Apegada algunha freba,
E ireino raspando á modo
C’un canteiro que me queda.

Todos riron c’a resposta


E...—¡Inda nunca Dios me dera,
Dixo o cego, que esa xorda
Sabe mais qu’eu, abofellas!
—Merece comer compango.
E voullo dar, miña vella,
Porqu’onde queira qu’a atopo
Gustame sempre a sabencia.
¡Coma e fártese!... aquí ten
Talladas e viño... beba,
Beba po-la miña conta
 salú d’as montañesas—
Dixo a dona, e doulle un prato
De callos, como un-ha cesta,
 probe, e viño, e pan branco.
Canto quixo; fartous’ela
Mesmo hastra que tuvo a tripa
Coma un pandeiro. Raventa
Por pouco..., mais o pelexo
Tiña duro, e nin siquera,
Ll’arregañou, y ô outro dia
Xa estaba tan peneireira.

Coidado,—lle dixo a dona


Cando se foy.—Conta teña
De non volver por aquí
Mentras lle dure a xordeira.
—¿Que dí, miña queridiña?
Respondeu rindose a vella.
Son mesmo com’un-ha tapia,
E non ll’oyo, anque me fendan.
XAN

Xan vay coller leña ô monte,


Xan vay á compoñer cestos,
Xan vay á podá-las viñas,
Xan vay á apañá-lo esterco,
E leva o fol ô muiño,
E tray o estrume ô cortello,
E vay â fonte por augua,
E vay á misa c’os nenos,
E fay o leito y o caldo...
Xan, en fin, é un Xan compreto,
D’esos qu’a cada muller
Lle conviña un po-lo menos.
Pero cand’un busca un Xan,
Casi sempre atopa un Pedro.

Pepa, a fertunada Pepa,


Muller d’o Xan que sabemos,
Mentras seu home traballa
Ela lava os pés n’o rego,
Cátall-as pulgas ô gato,
Peitea os longos cabelos,
Bótalles millo âs galiñas
Marmura c’o hirman d’o crego,
Mira s’hay ovos n’o niño,
Bota un ollo ôs mazanceiros,
E lambe a nata d’o leite
E si pode bota un neto
C’a comadre, qu’agachado
Traillo en baixo d’o mantelo,
E cando Xan po-la noite
Chega cansado e famento,
Ela x’o espera antr’as mantas,
E ô vêlo entrar dille quedo:

—Por Dios non barulles moito...


Que m’estou mesmo morrendo.
—¿Pois que tés, ña-mulleriña?
—¿Qu’hei de ter? deita eses nenos
Qu’esta madre roe en min
Cal roe un can n’un codelo,
Y ô cabo ha de dar comigo
N’os terrós d’o simiterio...
—Pois, ña-Pepa, toma un trago
De resólio qu’aquí teño,
E durme, ña-mulleriña
Mentras os meniños deito.

De vagoas s’enchen os ollos,


De Xan ô ver tales feitos,
Mas non temás, qu’antre mil,
N’hay mais q’un anxo antr’os demos,
N’hay mais qu’un atormentado
Antre mil que dan tormentos.
O ENCANTO D’A PEDRA CHAN

C’o sono d’a inocencia


Que non turban remorsos d’a concencia,
Y a virxen ô seu lado
Dormian os meus ánxeles n’a cuna,
Cand’âs furtadas n’un sereno dia
C’o peito palpitante d’alegría
Soya sain en busca d’a fertuna.

Iña tras d’un tesouro cobisado,


De todos iñorado,
Mais d’o que solasmentes eu sabia:
E n’era só de prata, nin só d’ouro,
Aquel sin par tesouro,
Qu’era d’un canto deseyar podia.

Nunca eu fora nin rica nin dichosa,


Y ô ver que para selo
Só me faltaba o gordo d’un cabelo,
De seca espiña me tornara en rosa.
E como virxen pura
Que por primeira vez sinte a dozura
D’as inquietús d’o amor, así eu sentia
Que algo qu’en min dormia
Despertaba, chamandom’â ventura.

Por eso dand’ô olvido


As penas que m’ouberan consumido
Dendes de que nacera,
Via a terra y o ceo, cor d’esperanza
Y ô meu redor, perene primadera.

¡Cal o sol relumbraba!


¡Que mansamente marmuraba o rio!
Y o paxariño voador cantaba,
Mentras qu’eu camiñaba
Lixeira ô meu avio.

Tal como a neve, albeas,


As roupas y as marañas
Tendidas n’as silveiras e as montañas
Xa en raro, xa âs moreas,
Cal pint’a branca nube o ceo sereno
Briland’ô sol, pintaban o paisaxe
Coma ningun ameno.

Cabo d’a ria n’a ribeira verde,


Á cal gana, á cal perde,
Xogaban os rapaces c’a onda escrava,
Á anxeliño tocaba
En un lugar veciño,
E anque os pais d’o meniño
Ô enterralo, choraban que partian.
Compasivo-l-os vellos,
¡De cantas penas se librou! decian.

En tant’os carros sin parar chirraban,


Mentras ô seu compás os carreteiros
Despaciosos cantaban;
E aquí a fonte corria,
Alá n’un-ha canteira resoaban,
Metalicos, os picos d’os pedreiros.
Mais preto os cans ladraban
Y antr’a follax o vento rebulia
Indo d’as encanadas ôs outeiros...
¡Canta paz! ¡canto sol!... ¡canta alegría!...

Ô
«¡Ô fin sorte cansache!
Y o quiñon que famenta me negache
N’a hirencia d’os praceres,
Dándome só o d’as ansias e as peleas,
Cal á aqués que ben queres,
Ora darasmo en gustos âs mancheas.»

Esto eu iba dicindo,


De dichosa cal n’outra presumindo,
Mentras que camiñaba
Tan contenta e segura
D’atopar a fortuna en qu’esperaba,
Cal sei que atopa á Dios quen o precura.

Antre buxos e silvas agachado


O encanto deseado
Estaba como merlo n’o seu niño,
Po-lo romor d’as auguas arrolado
D’o apartado mohiño...
Eu din volt’â devesa
Pasey a corredoira d’a Codesa,
¡Y ô fin cheguei!... y enriba d’un-ha lousa,
En ond’â amañecida o corbo pousa,
Un nobre cabaleiro
C’o a sua pruma enrisada n’o sombreiro,
E vestido de seda e pedrería
Á estilo d’a treidora mourería,
Dou en chamarm’arteiro,
C’un modo loumiñeiro
Que d’o ceo non d’a terra parecia.

¡El é! dixen ô punto temerosa...


Mais o d’o encanto, afeito
Seica á tratar con damas dend’antano
Sin que de verme s’atopas’estrano
Dende lonxe chamándome sorria.
Y o ceo póndose foi de cor de rosas,
Mentras n’as carballeiras e encanadas,
Sopraban un-has brisas repousadas,
Soaves e saudosas,
Cal promesas compridas, s’esperadas.

Eu non sei que sentia,


Vendo qu’él en chamarme proseguia,
Pois antr’ansiosa y-adusta
C’un-ha valor que asusta
Fumm’indo cabo d’él de gozo chea,
Cal palomiña vay tras d’a candea.

Tiña n’as mans un cetro adiamantado,


Bateu con el n’a laxe misteriosa
Que s’abreu, como s’abre d’o granado
O froito sazonado,
E con voz armoniosa
E garrido sembrante,
¡Vamos!—me dixo gasalleiro,—¡adiante!

E fun cal folla inxel vay c’a encalmada


Corrente, que primeiro asosegada,
A arrastra n’as suas auguas cristaiñas
Pra darlle sepultura cariñosa
N’as orelas veciñas,
E que dempois a leva, arrebatada
Po-la negra enxurrada
Ôs abismos d’a mare tormentosa.

¡E entrey pensando penetrar n’o ceo!...


¿Por que ten a maldade forza tanta?
Pois canto â vista encanta
E nos finxe o ardentísimo deseo
Nunca farto nin cheo,
Alí os meus ollos viron, e prendados
Quedaron como nunca e namorados.

D’o tesour’escondido
O brilo e fermosura
¿Á quen que fose de muller nacido,
Á que mortal criatura
N’a houbera contrubado e seducido?

E n’a lumieira y antr’aberta porta


Sin astreverme, de primeiro ausorta,
Á vixiar d’a espréndida morada
Un-ha tras d’outra estensa galería,
Cal si quedase para todo morta
Menos para o que via,
Escramey no supremo d’a alegría.

—Aquí Dios, aquí as dichas d’o universo


Sin voltas nin reverso,
Aquí o que á maxiñar nunca chegara,
A comprida ventura.
¡Que nunca outra topara
Mais grande, nin mais santa, nin mais pura!

Tal brasfemey, sin medo nin coidado,


¡Tola de min, cegabam’o pecado!
Y aquel brilo que via
Ô par que m’alentaba a fantesía
Daba comprida fé d’o ben buscado.

Pensando que por sorte


Ô paraiso terreal chegara
Y era verdade a dicha que soñara,
Sin m’acordar d’a vida, nin d’a morte,
Olvidando o pasado y o presente
C’o porvir xuntamente,
Soyo pensey en abarcar n’un punto
Aquel tanto ben xunto,
Iñorado d’a xente.

C’o poder d’o que pode, erguinme altiva


Sin coidar canto a humana natureza
É falibre e cativa,
E maxinando eterna fonte viva,
Tanta e tanta riqueza,
Com’ante min soberba s’ostentaba,
Dixen seguindo ô hermoso cabaleiro,
—Xa que vos atopey tan lisonxeiro
Pra gozar logo d’o qu’é meu, decime,
Por onde debo encomenzar primeiro.

—Por onde vos querás, reina e señora,


Contestou gasalloso
C’o seu falar gracioso,
Qu’é voso canto aquí vos enamora,
Pero vos e mais eu, antes bebamos
N’esta copa dourada,
Po-los mals que nos deixan e deixamos,
Y os bês que nos sorrin dend’alborada
D’un-ha mañan d’abril nunca acabada.

—¡Pois bebamos! ¡bebamos!


Repetin eu, trubada e non de viño,
Sin que a sinal d’a cruz antes fixese
Pra que ben m’emprestase o que bebese...
Y hastra o líquido fresco e cristaiño
Os dous nos abaixamos
E ambas bocas mollamos...

Nunca m’olvidarei d’aquel momento


D’inmensa dicha e d’infernal tormento,
Pois de dentro d’a copa
Saindo de repente
Un-ha e outra cabeza de sarpente
Contra min se volveno desatadas,
E todas xuntamente
Á un tempo asubiaron,
E n’as entrañas mesmas
O aguillon pezoñoso m’encrabaron.

Cain, cain ferida


E casi-que sin vida,
E inda enriba de min, feras volveno
C’o seu mortal veneno
Un-ha y outra sarpente maldecida.

Cal brétema espallada


Po-lo Sur, n’a encanada,
Dispareceu o lindo cabaleiro,
Y espesa nube de trebons preñada,
Partindo d’a sombrisa Compostela,
Que n’o confin lexano se trasvia
Cal se trasvé n’a tarde morimunda
A raya sin fulgor d’a noite fria,
Veu contrubar a miña mente inxela.

Y alí enriba d’a lousa


En dond’â mañecida o corbo pousa,
Atopeime de pronto, sin ventura,
D’as miñas doces ilusiós despida,
Soya e probe, cal n’outra criatura
Envenenada, triste e malferida.

E non sey que voz ronca marmuraba,


C’o vento que soaba,
«Coma ti, mal tesouro,
Que aquí deixou o mouro
E que a cubiza alaba,
Son os encantos todos terreales,

Á
Á tan grandes pracers, tan grandes males.»
* * *

—«Tanto e tanto nos odiamos,


Tanto e tan mal nos quixemos
Que por non verme morriche,
E desque morrich’alento.
Mas ora tócame á min
Tamen, marchar, e di o crego
Que che perdone, pois logo
Á axuntarnos volveremos.
¡O crego volveuse tolo!
¡Xuntarnos!... nunca mais, penso;
Que si ti estas ond’a Dios
Eu penso d’ir xunt’o demo.»

Esto un-ha vella viuda,


E terca como un carneiro,
Falaba do seu difunto
Xa d’os bichocos comesto.
Y en tanto qu’así falaba,
Tamen ela iba morrendo.
Mas din qu’o difunto y ela
S’atoparon n’os infernos
Man á man, e codo á codo
Como dous bós compañeiros.

—¿Conqu’estás aquí? lle dixo


Estonces a vella ô vello,
Pois voume a dond’está Dios
Xa que ti estás ond’o demo.—
E sin saberse por onde
Colleu direitiña ô ceo;
Mais topou fechada a porta,
Que lla fechàra San Pedro.

—¡Prum! ¡prum! ¡abrí, que son eu!


Falou a vella moy recio.
—Non hay, respondeu o Apóstol
Apertando o tarabelo.
—Coidá que xurey n’estar
Ond’él esté, meu San Pedro...
—Non hay, repiteull’o Santo,
Indose inda mais adentro.
—¡Por vida d’as vosas chaves,
Que facés un bon porteiro,
E que roncás!... xa se ve...
¡Como estades satisfeito!...

Mais eu xurey, e Dios manda


Qu’un cumpra seus xuramentos;
¡Â terceira vez!... ¿abrides?
—Nin âs tres nin ôs trescentos,
A muller vaya onda o home,
¡Al infierno, anda al infierno
Con él, por sempr’en jamás!
—¡Poche, meu Santo San Pedro,
Que ben deixás conocer
Qu’andiveches sempre ceibo,
Que nunca foches casado
Nin n’a terra nin n’o ceo!
Todiña-las comenencias
Para vos quixeches ¡deño!
¿Y á min non me dás ningun-ha?...
Pois vé qu’eu tamen as quero.
S’aló con cadea andiven
En têla agora non penso,
Que todo c’a morte acaba
Segun pedrican os cregos.
Un-ha ves nos separamos,
Eu y o meu home, e por certo
Que foi pra sempre... e esta dito,
Pois son terca, si sòs terco.
¿Que non me querés n’a groria?
Pois xurei non ir ô inferno
Dond’él está, y acabouse,
E n’hay que falar mais d’esto.
¿Que habés de facer de min?
¿Irei ô limbo d’os nenos?
¡Me vayas! que xa estou d’eles
Hasta a punta d’os cabelos.—
—¡Caramba, c’o a muller esta!
Dixo enfadado San Pedro,
Que si non fora por Dios...
—Bah, señor, deixavos d’eso
E permitíme que pase...
—Non, non e non. ¡Caramelos!
Fora d’aquí... e ¡pum! botouna
Direitiño cara ô inferno.
—¡Qu’o xurei! Xa o teño dito...
Berraba a vella... non entro.
Señor, Señor... Sursum corda,
Aquí estou, e aquí me quedo.

E quedouse, sí, quedouse:


¿Onde? non se sabe certo,
Nin si foi porqu’a oise Dios
Ou porque n’a quixo o deño.
Só se sabe, ben sabido,
Qu’anda n’as alas d’o vento,
Metendo medo ôs rapaces
N’as negras noites d’inverno;
Encelando namorados,
Desfacendo casamentos,
Malquistando matrimonios...
¿Porque n’a levou San Pedro?
Qu’ora anda ceiba e ben ceiba
Para meternos n’o inferno.
Poñélle a figa, mociñas,
Si querés ter casamento,
Qu’ond’ela esté, nin un home
Toparés para un remedio.
EN CORNES

Formoso campo de Cornes,


Cando te crobes de lirios
Tamen se me crobe a yalma
De pensamentos sombrisos.
De Cornes lindo lugare
Que cruzan tantos camiños,
Anque cuberto de rosas,
As rosas, tamén fan guizos.

Antr’as pedras, alelises,


Antr’os toxos, campanillas,
Por antr’os musgos, vïolas,
Regos, por antr’as curtiñas.
Rio abaixo está o moiño,
Compostela, rio arriba...
Rio arriba, ou rio abaixo,
Todo é calma n’a campía.

Convidando á meditare,
Soan de Conxo as campanas,
Beben os bois n’o teu rio
Y o sol alegra a escampada.
D’as tuas casas terreñas
Say fume y os galos cantan...
¡Quen en tan fresco retiro
Dirá que as dores fan lama!

Donde hay homes hay pesares,


Mais n’os teus campos, ña terra
Maxino que os hay mais fondos,
Cando t’amostras mais leda.
¡Por qu’ eses trios d’os páxaros,
Eses ecos y esas brétemas
Vaporosas, y esas frores,
N’alma triste, canto pesan!

Po-las silveiras errante


Vexo un-ha meniña orfa
Que triste vay marmurando,
—¡Ña Virxe, quen rosa fora!
—¿Porque quês ser rosa, nena?
Lle preguntei cariñosa,
Y ela contesta sorrindo,
—Porque non tên fame as rosas.

Cost’arriba, cost’arriba,
Desandemo-l-o camiño,
Fuxamos d’este sosego
D’os pesares enemigo.
¡Que negro contraste forman,
D’a natureza o tranquilo
Reposo, co as ansias feras
Que abaten o inxel esprito!

II

Cruceiro de Ramirez que t’ergues solitario


D’os Agros n’a espranada, antr’as rosas d’os campos,
O sol d’a tarde pousa en tí o postreiro rayo
Coma n’un alma triste, pousa un soño dourado.

Algun-ha vez n’o estio, eu ô teu pé sentada


Escoito silenciosa, mentras a tarde acaba:
Baixo d’as pedras mudas, que teu sacreto gardan
Maxino que resoa o brando son d’un arpa,
¡Música incomprensible que d’outros mundos fala!

¡Tal de Memnon s’oian ô amañecer n’a estatua,


Aqueles sons divinos que as almas encantaban!

III

Ódiote campo fresco,


C’os teus verdes valados,
C’os teus altos loureiros
Y os teus camiños brancos
Sembrados de violetas,
Cubertos d’emparrados.
Ódiovos montes soaves
Que o sol poniente aluma,
Qu’en noites mais sereas
Vin ô fulgor d’a lua,
Y ond’en mellores dias
Vaguey po-las alturas.
E tí tamén, pequeno
Rio, cal n’outro hermoso
Tamén aborrecido,
És antr’os meus recordos...
¡Porque vos amey tanto,
E porque así vos odio!
SAN LOURENZO

Ô mirar cal de novo n’os campos


Iban á abrochá-l-as rosas,
Dixen—¡En onde, Dios mio,
Irey á esconderm’agora!
E pensei de San Lourenzo
N’a robreda silenciosa.

N’algun tempo aquês vellos carballos


Amostrando as suas raices,
Cálva-l-as redondas copas
Que xa de musgo se visten,
Âs tristes almas falábanlles
Tan soyo de cousas tristes.

O alciprés que direito s’asoma


D’o convento tras d’o muro,
Y o lixeiro campanario
Cuberto d’herbas e musgo,
D’a devesa, c’o cruceiro
Eran cintinelas mudos.

Y aquel Cristo que n’o arco de pedra


Abatido a frent’incrina,
Soyo, cal s’inda n’o Gólgota
Loitase c’o as agonias,
Ôs corazós oprimidos
Resignacion ll’infundia.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like