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

Instant Download (Ebook) Simplified JavaScript for Very Important Programmers : The Fast Track to Mastering Essential JavaScript Concepts by Ebenezer Don ISBN 9798378081837, 8378081834, B0BW38DCB1 PDF All Chapters

The document provides a list of various eBooks available for download on ebooknice.com, focusing on JavaScript programming and related topics. It includes titles such as 'Simplified JavaScript for Very Important Programmers' and 'JavaScript for Impatient Programmers,' along with their ISBNs and links for purchase. Additionally, it outlines the contents of the book 'Simplified JavaScript for Very Important Programmers,' detailing essential JavaScript concepts and programming techniques.

Uploaded by

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

Instant Download (Ebook) Simplified JavaScript for Very Important Programmers : The Fast Track to Mastering Essential JavaScript Concepts by Ebenezer Don ISBN 9798378081837, 8378081834, B0BW38DCB1 PDF All Chapters

The document provides a list of various eBooks available for download on ebooknice.com, focusing on JavaScript programming and related topics. It includes titles such as 'Simplified JavaScript for Very Important Programmers' and 'JavaScript for Impatient Programmers,' along with their ISBNs and links for purchase. Additionally, it outlines the contents of the book 'Simplified JavaScript for Very Important Programmers,' detailing essential JavaScript concepts and programming techniques.

Uploaded by

aihukianteur
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) Simplified JavaScript for Very Important


Programmers : The Fast Track to Mastering
Essential JavaScript Concepts by Ebenezer Don ISBN
9798378081837, 8378081834, B0BW38DCB1
https://ebooknice.com/product/simplified-javascript-for-
very-important-programmers-the-fast-track-to-mastering-
essential-javascript-concepts-48134224

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) Biota Grow 2C gather 2C cook by Loucas, Jason;


Viles, James ISBN 9781459699816, 9781743365571,
9781925268492, 1459699815, 1743365578, 1925268497
https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374

ebooknice.com

(Ebook) JavaScript for impatient programmers (ES2020


edition) by Dr. Axel Rauschmayer ISBN 9781091210097,
1091210098
https://ebooknice.com/product/javascript-for-impatient-programmers-
es2020-edition-22278312

ebooknice.com

(Ebook) JavaScript for Programmers by Paul J. Deitel,


Harvey M. Deitel ISBN 9780137001316, 0137001312

https://ebooknice.com/product/javascript-for-programmers-2016688

ebooknice.com

(Ebook) JavaScript for impatient programmers (ES2021


edition) by Dr. Axel Rauschmayer ISBN 9781091210097,
1091210098
https://ebooknice.com/product/javascript-for-impatient-programmers-
es2021-edition-23217092

ebooknice.com
(Ebook) JavaScript: Learn JavaScript in 24 Hours or Less -
A Beginner’s Guide To Learning JavaScript Programming Now
(JavaScript, JavaScript Programming). by Robert Dwight.
ISBN B01HDPSYKW
https://ebooknice.com/product/javascript-learn-javascript-in-24-hours-
or-less-a-beginners-guide-to-learning-javascript-programming-now-
javascript-javascript-programming-55923064
ebooknice.com

(Ebook) Git Prodigy : Mastering Version Control with Git


and GitHub by Ebenezer Don ISBN 9798851556104, 8851556105

https://ebooknice.com/product/git-prodigy-mastering-version-control-
with-git-and-github-52362654

ebooknice.com

(Ebook) Matematik 5000+ Kurs 2c Lärobok by Lena


Alfredsson, Hans Heikne, Sanna Bodemyr ISBN 9789127456600,
9127456609
https://ebooknice.com/product/matematik-5000-kurs-2c-larobok-23848312

ebooknice.com

(Ebook) Mastering the Internet, XHTML and JavaScript by


Zeid, Ibrahim ISBN 9780131400863, 013140086X

https://ebooknice.com/product/mastering-the-internet-xhtml-and-
javascript-22041750

ebooknice.com

(Ebook) Mastering JavaScript Design Patterns by Simon


Timms ISBN 9781785882166, 1785882163

https://ebooknice.com/product/mastering-javascript-design-
patterns-6724550

ebooknice.com
Simplified JavaScript for Very
Important Programmers
The Fast Track to Mastering Essential
JavaScript Concepts

Ebenezer Don
This book is for sale at http://leanpub.com/vip-javascript

This version was published on 2023-03-10

This is a Leanpub book. Leanpub empowers authors and


publishers with the Lean Publishing process. Lean Publishing is
the act of publishing an in-progress ebook using lightweight tools
and many iterations to get reader feedback, pivot until you have
the right book and build traction once you do.

© 2023 Ebenezer Don


Contents

Getting The Book . . . . . . . . . . . . . . . . . . . . . . . . 1

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

What is JavaScript and How Does it Work? . . . . . . . . 3


How Does JavaScript Work? . . . . . . . . . . . . . . . . . 4
History of JavaScript . . . . . . . . . . . . . . . . . . . . . 4
Differences Between JavaScript and HTML/CSS . . . . . 5
Uses of JavaScript across multiple fields . . . . . . . . . . 6

How to write and run JavaScript code . . . . . . . . . . . . 8


Using a web browser . . . . . . . . . . . . . . . . . . . . . 8
Using an online code editor . . . . . . . . . . . . . . . . . 9
Using an offline code editor . . . . . . . . . . . . . . . . . 9

JavaScript syntax and Data types . . . . . . . . . . . . . . . 10


Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Comments in JavaScript . . . . . . . . . . . . . . . . . . . 13
Basic conditional statements (If-else) . . . . . . . . . . . . 15

Variables in JavaScript . . . . . . . . . . . . . . . . . . . . . 18
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Variable declaration and assignment . . . . . . . . . . . . 20
Variable naming rules and conventions . . . . . . . . . . 22

Basic JavaScript operators . . . . . . . . . . . . . . . . . . . 26


CONTENTS

Arithmetic operators . . . . . . . . . . . . . . . . . . . . . 26
The Concatenation operator . . . . . . . . . . . . . . . . . 28
Assignment operators . . . . . . . . . . . . . . . . . . . . . 29
Comparison operators . . . . . . . . . . . . . . . . . . . . 30
Logical operators . . . . . . . . . . . . . . . . . . . . . . . 31

Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
How to define functions in JavaScript . . . . . . . . . . . 33
The return keyword . . . . . . . . . . . . . . . . . . . . . . 34
Function Parameters vs Arguments . . . . . . . . . . . . . 36
More on the return statement . . . . . . . . . . . . . . . . 36
Anonymous functions . . . . . . . . . . . . . . . . . . . . 37
Multi-line return statements . . . . . . . . . . . . . . . . . 39
Arrow Functions . . . . . . . . . . . . . . . . . . . . . . . 40
Functions best practices . . . . . . . . . . . . . . . . . . . 41
JavaScript String Methods . . . . . . . . . . . . . . . . . . 42
JS Math functions . . . . . . . . . . . . . . . . . . . . . . . 44

Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Declaring and Initializing Arrays . . . . . . . . . . . . . . 48
Accessing and modifying Array Elements . . . . . . . . . 49
Array Length . . . . . . . . . . . . . . . . . . . . . . . . . 50
Array Methods . . . . . . . . . . . . . . . . . . . . . . . . 51

Higher Order Functions (HOFs) and Callbacks . . . . . . . 58


Creating Higher-order functions . . . . . . . . . . . . . . 60
Built-in HOFs and Array Methods . . . . . . . . . . . . . 61
The JavaScript Timing methods . . . . . . . . . . . . . . . 72

JavaScript Objects . . . . . . . . . . . . . . . . . . . . . . . . 76
Rules and Guidelines for creating objects . . . . . . . . . 77
Adding, modifying and Removing Properties . . . . . . . 82
Object.prototype . . . . . . . . . . . . . . . . . . . . . . . . 85
Object methods . . . . . . . . . . . . . . . . . . . . . . . . 87
Object destructuring . . . . . . . . . . . . . . . . . . . . . 90
CONTENTS

Conditional Statements . . . . . . . . . . . . . . . . . . . . . 94
Else-if statements in JavaScript . . . . . . . . . . . . . . . 94
Nested if statements . . . . . . . . . . . . . . . . . . . . . . 97
The Switch statement . . . . . . . . . . . . . . . . . . . . . 100
The ternary operator . . . . . . . . . . . . . . . . . . . . . 106

Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
The for Loop . . . . . . . . . . . . . . . . . . . . . . . . . . 109
The for...in loop . . . . . . . . . . . . . . . . . . . . . . . 113
The for...of loop . . . . . . . . . . . . . . . . . . . . . . . 115
The while Loop . . . . . . . . . . . . . . . . . . . . . . . . 117
The do...while Loop . . . . . . . . . . . . . . . . . . . . . 119

The Document Object Model (DOM) . . . . . . . . . . . . . 123


Accessing the DOM . . . . . . . . . . . . . . . . . . . . . . 125
Modifying DOM Elements . . . . . . . . . . . . . . . . . . 138
Removing elements from the DOM . . . . . . . . . . . . . 147
Traversing the DOM . . . . . . . . . . . . . . . . . . . . . 148
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . 152

How to include JavaScript in an HTML file . . . . . . . . . 153


Writing JavaScript in the HTML file (inline JavaScript) . 153
Creating a separate JavaScript file (external JavaScript) . 154
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . 157

Browser Events . . . . . . . . . . . . . . . . . . . . . . . . . . 158


Event Object Properties and Methods . . . . . . . . . . . . 161
Browser Event types and listeners . . . . . . . . . . . . . . 165
Keyboard Events . . . . . . . . . . . . . . . . . . . . . . . 166
Form Events . . . . . . . . . . . . . . . . . . . . . . . . . . 166
Window Events . . . . . . . . . . . . . . . . . . . . . . . . 166

Browser Storage . . . . . . . . . . . . . . . . . . . . . . . . . 169


Cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
LocalStorage and SessionStorage . . . . . . . . . . . . . . 172
CONTENTS

Building A Todo List App with JavaScript . . . . . . . . . . 178


Using HTML to structure our app . . . . . . . . . . . . . . 178
Using JavaScript to add functionality to our app . . . . . 179
Rendering saved tasks to the browser . . . . . . . . . . . . 181
Adding tasks to the list . . . . . . . . . . . . . . . . . . . . 183
Marking tasks as complete . . . . . . . . . . . . . . . . . . 185
Removing Tasks . . . . . . . . . . . . . . . . . . . . . . . . 186
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . 190

Asynchronous JavaScript . . . . . . . . . . . . . . . . . . . . 192


What is Asynchronous JavaScript? . . . . . . . . . . . . . 192
Promises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
Promise Methods . . . . . . . . . . . . . . . . . . . . . . . 197
Making HTTP Requests with Promises and the Fetch API 202
Async/Await . . . . . . . . . . . . . . . . . . . . . . . . . . 207

Working with Date and Time . . . . . . . . . . . . . . . . . 212


Creating a Date Object . . . . . . . . . . . . . . . . . . . . 212
Getting the Date and Time Components . . . . . . . . . . 214
Setting the Date and Time Components . . . . . . . . . . 216
Formatting Dates and Times . . . . . . . . . . . . . . . . . 216

Final Thoughts . . . . . . . . . . . . . . . . . . . . . . . . . . 219


Getting The Book
I’m thrilled that you’re interested in this book! To get your hands on
a legitimate copy, I highly recommend visiting vipjavascript.com*,
Leanpub.com/vip-javascript† or selar.co/vip-javascript‡.
By purchasing from the official websites, you’ll receive access to the
latest updates and corrections, and you’ll be supporting my hard
work as an author.
I kindly ask that you refrain from sharing or pirating the book.
I’ve put in countless hours of work, and it’s important that I’m
compensated for my efforts.
Thank you for your support, and happy reading!
*https://vipjavascript.com
†https://leanpub.com/vip-javascript
‡https://selar.co/vip-javascript
Introduction
“Simplified JavaScript for Very Important Programmers” is a re-
freshing and practical guide for beginners who want to master ev-
ery essential aspect of JavaScript. In this book, I offer a streamlined
approach to learning JavaScript with relatable real-life examples
that make the concepts easy to understand, even for those without
programming experience.
I’ve divided this book into two parts. The first part is designed
for everyone learning JavaScript, and the second part focuses on
using JavaScript on the web, building on the foundational concepts
covered in the first part.
I’ve written everything in clear and concise language, making it
easy for everyone to follow along and grasp. Whether you’re a
student, an entrepreneur, or simply someone interested in program-
ming, this book will guide you through the essential concepts of
JavaScript with ease and efficiency.
From variables and operators to loops, functions and objects,
we’ll cover everything you need to know to become a competent
JavaScript programmer. The examples and exercises throughout
this book are designed to reinforce your learning and help you
apply your knowledge in real-world scenarios.
If you’re looking for a practical and enjoyable way to learn
JavaScript, you’re reading the perfect book.
What is JavaScript and
How Does it Work?
JavaScript is a programming language that was initially developed
as a means to add dynamic and interactive elements to websites.
Today, it is one of the most popular programming languages in
the world and is used for a wide range of applications, including
web development, mobile app development, server-side scripting,
machine learning, game development, and more. When learning
web development, it is essential to understand how JavaScript
works and how you can use it to build dynamic websites and add
interactivity to your web pages.
JavaScript is a dynamically-typed language, which means that you
can use it to store different types of information without telling
the computer what you’ll put there ahead of time. Since you don’t
have to keep track of so many rules, it’s usually easier to read
and write JavaScript than other programming languages like C++,
Java, or Rust. However, this also means that you can make mistakes
that are hard to catch, so it’s important to be careful when writing
JavaScript code.
JavaScript is often used in conjunction with HTML and CSS to
create interactive and dynamic websites. One of its main features
is its ability to manipulate and interact with web pages; it can be
used to change the content and layout of a webpage, respond to user
input, and communicate with servers to retrieve and update data.
So, while HTML provides the structure and content of a webpage,
and CSS defines its style and layout, JavaScript adds behavior and
interactivity.
What is JavaScript and How Does it Work? 4

How Does JavaScript Work?


When a JavaScript program is run, the computer reads the code and
follows its instructions.
In the case of web development, JavaScript is usually run in a
web browser like Google Chrome or Mozilla Firefox. When you
open a webpage that contains JavaScript, your browser reads the
JavaScript code and uses it to interact with and modify the content
of the webpage, its layout, and its behavior.
You can also use JavaScript in other contexts like mobile app
development and server-side programming, in which case, the
JavaScript code is run on a different type of device or platform, but
the process of executing the code is similar.
One thing to note is that JavaScript is an interpreted language,
meaning it is not compiled (translated into machine code) before
it is run. Instead, the computer interprets the code as it is being
executed. This makes writing and debugging JavaScript programs
easier, but it can also make them run slower than programs written
in compiled languages.

History of JavaScript
JavaScript was created by Brendan Eich in 1995 and was first
introduced with the release of Netscape Navigator 2.0, a popular
web browser at the time. JavaScript was initially called Mocha but
later renamed to LiveScript and then to JavaScript in an attempt
to take advantage of the buzz surrounding the Java programming
language.
JavaScript quickly gained popularity among web developers and be-
came supported by other major web browsers like Internet Explorer
and Safari. In 1996, JavaScript was standardized by the European
What is JavaScript and How Does it Work? 5

Computer Manufacturers Association (ECMA) as ECMAScript,


which remains its official name today.

Differences Between JavaScript and


HTML/CSS
JavaScript is often used with HTML and CSS to build websites.
However, there are some important differences between the three
languages. One crucial difference is that JavaScript is a program-
ming language, while HTML is a markup language and CSS is a
style sheet used to describe the appearance of a webpage. So, you’ll
often find JavaScript more difficult to learn than HTML and CSS.
Some key features of JavaSCript that are not found in HTML and
CSS include:

• The ability to execute code based on conditions or events


• The ability to iterate through data and perform actions on
multiple elements
• The ability to create and manipulate different types of data
• The ability to make requests to servers and retrieve data

While HTML and CSS are important for defining the content and
appearance of a webpage, without JavaScript, it’s difficult to add
interactivity to your webpage that’ll make users love it. JavaScript
allows developers to build more sophisticated and engaging user
experiences, and it is a critical component of modern web develop-
ment.
What is JavaScript and How Does it Work? 6

Uses of JavaScript across multiple


fields
Apart from web development, you can use JavaScript for a wide
range of applications, including:

Server-side programming

When you visit a website, your web browser sends a request to


the website’s server, which then executes the code responsible
for handling that request and generating an appropriate response.
Tools like Node.js and Deno make it possible to run JavaScript on
the server instead of a browser. This enables developers to build
scalable, high-performance applications that can handle many con-
current users.

Mobile app development

You can use JavaScript to build cross-platform mobile apps with


tools like Cordova, React Native, and NativeScript. These tools
allow developers to write JavaScript code that is compiled and run
on a mobile device rather than in a browser.

Game development

You can also use JavaScript to build browser-based games with tools
like Phaser and Babylon.js. These tools allow you to create 2D and
3D games that can be played in a web browser.
What is JavaScript and How Does it Work? 7

Data visualization

JavaScript libraries like D3.js and Highcharts can be used to create


interactive data visualizations for websites and applications.

Robotics

You can use JavaScript to control and program robots using plat-
forms like NodeBots and Johnny-Five.

Internet of Things (IoT)

JavaScript can be used to build applications that interact with and


control connected devices, such as smart home appliances and
sensors.

Machine learning

With JavaScript libraries like TensorFlow.js and Brain.js, you can


build machine-learning models and incorporate them into web
applications.
How to write and run
JavaScript code
The best way to learn JavaScript is by writing JavaScript. Let’s
explore the different ways you can write and run JavaScript code
so that it’ll be easy for you to practice whatever you learn.

Using a web browser


One of the simplest and most accessible ways to write JavaScript
code is by using a web browser. Most modern web browsers, such
as Google Chrome, Mozilla Firefox, and Safari, have a built-in
JavaScript engine that allows you to write and run JavaScript code
directly in the browser.
To write JavaScript code in a web browser, you can use the
browser’s developer tools. To open the developer tools in Google
Chrome, right-click on any webpage and select “Inspect” from the
context menu. Alternatively, you can press Ctrl + Shift + I on a
Windows or Linux computer, or Command + Option + I on a Mac.
Once the developer tools window is open, navigate to the “Console”
tab, where you’ll be able to write your JavaScript code. For example,
you can try typing the following code into the console, but with
your name instead of mine:

1 console.log('My name is Ebenezer Don')


2 console.log('JavaScript is awesome!')

To run your JavaScript code, press the Enter key on your keyboard.
This will print the message “My name is Ebenezer Don” and
How to write and run JavaScript code 9

“JavaScript is awesome!” to the console. Good job! I’ll explain every


part of the code you just wrote later on.

Using an online code editor


Another way to write and run JavaScript code is by using an online
code editor or online Integrated Development Environment (IDE).
There are many online code editors and IDEs available that allow
you to write and run JavaScript code from your web browser. Some
popular options include CodePen, JSFiddle, and JS Bin.
You need an internet connection to use an online code editor, but it
has several advantages too. First, it allows you to write and run code
from anywhere. Second, you can easily share your code with others
through links. Third, many online code editors and IDEs have built-
in features that can ease the process of writing code and checking
for errors.

Using an offline code editor


There are also several offline code editors and IDEs you can use
to write and run JavaScript code. Some popular options include
Eclipse, NetBeans, Visual Studio and Visual Studio Code (with the
help of extensions). These IDEs need to be installed on your local
computer and typically have more features and functionality than
online code editors. They are often used for more complex projects,
and even if you don’t start with them, you’ll eventually need one
as you progress.
The easiest to get started with is your browser console, so I
recommend writing and running your first JavaScript code on it,
and when you do, take a screenshot and save it where you can
access it a year from now. I’m sure you’ll be proud of your progress.
JavaScript syntax and
Data types
JavaScript syntax and data types are fundamental concepts that you
should understand as you learn JavaScript. The syntax of a pro-
gramming language includes its rules for writing and structuring
code, while data types represent the classification of values that
you can store and manipulate in your code.

Syntax
Here are some basic rules for writing and structuring JavaScript
code:

• JavaScript is case-sensitive, which means that the case of the


characters and keywords you use matters. So if you write
a word like ‘name’ in your code, JavaScript will see it as
different from ‘Name’ or ‘nAme’. This is a common confusion
for beginners when writing code, so pay close attention to the
cases you use.
• Use spaces, tabs, and newlines to make your code readable,
but make sure to stay consistent. This is also known as
indentation and you’ll see examples as we progress.
• You can choose to write a semicolon (;) at the end of each
statement. A statement is any line of code that instructs the
computer to perform a specific task. Terminating statements
with semicolons used to be a requirement for JavaScript code
to run properly but that isn’t the case anymore. So you’ll
see some codebases with semicolons and some without it.
JavaScript syntax and Data types 11

It’s important to keep your code style consistent as this will


ease readability and understanding, so if you choose to use
semicolons, use them for every statement in your code, and
if you choose to do without semicolons, don’t use them at all.

There are some more rules that won’t be easy for you to understand
now, so I’ll show them to you as we progress.

Data Types
In JavaScript, there are several data types that are used to represent
different types of information, like numbers, text, or true/false val-
ues. The most basic data types are numbers, strings, and Booleans.
A collection of multiple values with the same or different data types
is called a data structure.
JavaScript is a dynamically-typed language, which means that
the type of a value is determined while the program is running
and can change during the program. This is different from other
programming languages where you have to set the type of a value
when creating, and can’t change it later. These other languages are
called “statically-typed”.
There are several basic data types in JavaScript, including:

Numbers

Numbers in JavaScript can be integers or floating-point values.


Integers are whole numbers like 1, 2, or 3, and floating-point values
are numbers with decimal points like 7.8 or 0.05.
You’ve already used console.log() to display your name in the
browser console. console.log() is also a method, which we’ll
explain in detail later on. For now, you can recognize methods with
JavaScript syntax and Data types 12

the parenthesis() after them. They represent a set of instructions for


the computer.
Let’s introduce another method, typeof(). We’ll use this to find
out the type of any value we create in JavaScript. On your browser
console, writing the following code and hitting the Enter key should
display the text “number”:
typeof(10)

It’s important that you practice everything you learn to make


understanding and remembering it easier. Try using thetyepof()
method to find out the type of -10.
Notice that you still get the response, ‘number’. This is because
there is no difference between positive and negative numbers.
Positive numbers are numbers greater than zero, and negative
numbers are less than zero. You can represent both positive and
negative numbers with the same syntax in JavaScript.

Strings
In JavaScript, a string is a group of characters that is used to store
text. Strings are commonly used to store words and sentences. To
write a string, you have to wrap it in either single quotes (‘This
is a string’) or double quotes (“This is also a string”). Both types
of quotes can be used to write strings, as long as they are used
consistently. So, if you start writing a string with single quotes, you
must end it with single quotes.
A string can be a single word, sentence or multiple paragraphs, and
It can contain any combination of letters, numbers and spaces.
The text “My name is Ebenezer Don” in the console.log() state-
ment we used earlier is also a string. Remember to always use your
name wherever you see “Ebenezer Don”.
Let’s print the string “Hello World” to the console, using both single
quotes and double quotes:
JavaScript syntax and Data types 13

1 console.log('This is really cool!')


2 console.log('This is really cool!')

Now, try using the tyepof() method to find out the type of “Hello
World”. Remember to pay close attention to the casing of keywords.
For example, there’s no uppercase letter in the typeof() method.
The string is an important data type in JavaScript. You can use it to
represent text-based data like names, messages or addresses.

Booleans
Booleans represent true or false values. They are often used to make
comparisons and to determine whether a set of instructions should
be executed. When you run the code tyepof(true) in your browser
console, you should get the response, ‘boolean’.
To make value comparisons in JavaScript, you can use the symbols;
> (greater than), < (less than), or === (is the same as).

Now, let’s see if the strings “Hey” and ‘hey’ are the same in
JavaScript. Run the following line of code in your browser console:

1 'hey' === 'HEY'

Running the above code should return false, and that’s because
strings are case-sensitive in JavaScript.
Booleans are an important data type in JavaScript, as they allow
you to represent logical values, make comparisons and run code
conditionally.

Comments in JavaScript
In JavaScript, comments are pieces of text within the code that
are ignored when the code is executed. They are useful for adding
JavaScript syntax and Data types 14

notes to your code, or for temporarily disabling a piece of code


without having to delete it. There are two ways to write comments
in JavaScript: Single-line comments and Multi-line comments.

Single-line comments

Single-line comments start with two forward slashes (//) and


continue until the end of the line. For example:

1 // This is a single-line comment

Multi-line comments

Multi-line comments start with a forward slash and an asterisk (/*)


and end with an asterisk and a forward slash (*/). They can span
multiple lines and can be used to disable blocks of code or to add
longer notes and explanations to your code. Here’s an example of
a multi-line comment:

1 /*
2 This is a
3 multi-line comment
4 */

It’s a good practice to make your code readable enough that you
don’t need to add comments to explain what it does. However,
comments are useful when you want to explain why you did
something a certain way, or when you believe that your code might
be confusing to someone else or even your future self. Overuse of
comments can make your code cluttered and difficult to read, so
it’s important to strike a balance between writing readable code
and adding comments where necessary.
JavaScript syntax and Data types 15

Basic conditional statements


(If-else)
In JavaScript, you can use conditional statements to run different
blocks of code depending on whether or not a condition is met. A
block of code is a group of statements enclosed in curly braces.
Conditional statements are a crucial aspect of programming, as they
allow you to control the flow of your program and make it behave
differently in various situations.
There are two main types of conditional statements in JavaScript:
if statements and switch statements. In this section, you’ll learn
about if statements, and later on, switch statements.

The If Statement
An if statement enables you to run a block of code if a specific
condition is true. This is the basic syntax for an if statement:

1 if (condition) {
2 // code to run if condition is true
3 }

The condition is a boolean expression that evaluates to either true or


false. An expression is a combination of values and operators that
evaluates to a single value. For example, 10 > 5 is an expression
that evaluates to true, and 10 < 5 is an expression that evaluates to
false. An expression can also be a single value, like a number, string,
or boolean.
If the condition evaluates to true, the code block inside the if
statement is executed. If the condition evaluates to false, the code
block is skipped. The code block is enclosed in curly braces {}and
is called the if body.
JavaScript syntax and Data types 16

For instance, running the following code should return the string
“7 is greater than 5”:

1 if (7 > 5) {
2 console.log('7 is greater than 5')
3 }

SInce 7 is greater than 5, the console.log() statement in the curly


braces will run. Likewise, running the following code will not
return anything on your console:

1 if (7 < 5) {
2 console.log('7 is less than 5')
3 }

Notice that we changed the comparison symbol from > (greater


than) to < (less than). As 7 is not less than 5, the computer will
not execute the console.log() statement.
You’ll also notice that the code block inside the curly braces has two
spaces before it. This is called indentation, and it makes code easier
to read and understand. We indent code to show that it is inside a
block. If we didn’t indent the code inside the if statement, it would
be hard to tell whether it’s part of the if statement or whether
it’s a separate statement entirely Indentation is not required for
JavaScript to run, but it’s necessary for writing readable code and
avoiding errors. You can use any number of spaces for indentation,
but it’s common to use two spaces. You’ll find some developers
who use four spaces or tabs, but it’s best to stay consistent with
whichever style you or your team choose.

The Else clause


You can add an else clause to an if statement, which allows you to
specify a block of code to run if the condition is false. This is the
basic syntax for an if-else statement:
JavaScript syntax and Data types 17

1 if (condition) {
2 // code to run if condition is true
3 } else {
4 // code to run if condition is false
5 }

Let’s add an else clause to our conditional statement:

1 if (7 < 5) {
2 console.log('7 is less than 5')
3 } else {
4 console.log('The condition is false')
5 }

Since 7 is not less than 5, running the above code should return the
string “The condition is false”.
Conditional statements are an essential tool for creating programs
that can adapt to different circumstances and make decisions based
on the data they receive. We’ll cover more complex conditional
statements and other ways we can write them as we progress.
Variables in JavaScript
Introduction
It’s not easy to write JavaScript code without using variables. So
far, we’ve done an excellent job of avoiding them, but it’s time you
learned about one of the most important concepts in programming.
A variable is a named location for storing data in the computer’s
memory. In simple words, it’s a container in which we can store
all kinds of data, like numbers, text, pieces of code, and even other
variables. So, think of a variable as a box with a label on it. The label
is the variable’s name, and the content of the box is the variable’s
value.
Here’s an example of a variable in JavaScript:

1 let myName = 'Ebenezer Don'

In this example, we created a variable named “myName” and stored


the string value “Ebenezer Don” inside it. This is called variable
declaration. The variable declaration is made up of four parts: the
declaration keyword, the variable name, the assignment symbol (=),
and the variable value.

The declaration keyword


The keyword let is one of the ways you can declare a variable in
JavaScript. There are other ways to declare variables, but let is the
most common one. You’ll learn about the other variable declaration
keywords as we progress. In JavaScript, a keyword is a reserved
word with a specific purpose.
Variables in JavaScript 19

The variable name


The variable name in this example is myName. It’s a good practice to
use descriptive names for your variables because when the name of
your variable represents its value, your code is easier to understand.

The assignment symbol (=)


The assignment symbol (=) is used to assign a value to a variable. It’s
also called the assignment operator, and there are other operators in
JavaScript, like the addition operator (+), the subtraction operator (-
), the multiplication operator (*), and the division operator (/). You’ll
learn about them in the next chapter.

The variable value


In our example, the variable value is the string “Ebenezer Don.” The
value of a variable can be of any type, including numbers, strings,
booleans, or other variables.
We can use the console.log() function to print the variable’s value
to the console. In addition to the code above, run the following
console.log statement in your browser’s console:

1 console.log(myName)

This will print the value of the variable myName to the console.
We can also reassign a variable’s value by using the assignment
operator (=). So if we want to change the value of the variable
myName to “Jane Butters,” we could do so by writing this line of code:

1 myName = 'Jane Butters'

Now, if you rerun the console.log statement, you’ll get the string
“Jane Butters” printed on the console.
Variables in JavaScript 20

Variable declaration and assignment


There are several ways to declare a variable in JavaScript, each with
its use case.

The let keyword

The let keyword is the most common way to declare a variable in


JavaScript. It’s used to create local variables, which are variables
that are accessible only within a particular block of code.
Here’s an example of a local variable with the let keyword:

1 if (true) {
2 let message = 'JavaScript is awesome!'
3 }
4
5 console.log(message)

In this example, the message variable is local and is only accessible


within the block of code enclosed in the curly braces. So you’ll get
an error if you try to access it outside this block like we’re doing in
the console.log statement.
Global variables, on the other hand, are variables that are acces-
sible from anywhere in your code. If you want to create a global
variable with the let keyword, you can do so by declaring it outside
your code blocks.
Here’s an example of a global variable with the let keyword:
Variables in JavaScript 21

1 let name = 'Jane'


2
3 if (true) {
4 console.log(name)
5 }

Running this code will return the string value “Jane” to the console.
This is because the name variable is global and is accessible from
anywhere in your code.

The var keyword


The var keyword is the oldest way to declare a variable in JavaScript
and is used to create global variables. So, if we used the var keyword
in our first example to declare the message variable, we wouldn’t
get an error.
Here’s an example of a global variable with the var keyword:

1 if (true) {
2 var message = 'JavaScript is awesome!'
3 }
4
5 console.log(message)

The above code will not return any errors because the message
variable is global. This means that it is accessible from anywhere
in the code, including outside the block of code in which it was
declared.
It’s important to be careful when using global variables. Since they
can be accessed from anywhere in your code, global variables can
cause problems. For example, if you declare a global variable with
the same name as a local variable in your code, the global variable
will overwrite the local variable; this can lead to unexpected results
and confusion in your code.
Variables in JavaScript 22

The const keyword


So far, we’ve seen how to create local and global variables which
can be reassigned. But most times, it’s safer to create variables
that can’t be reassigned so that we don’t accidentally change their
values. The const keyword is used for this purpose.
Here’s an example of a constant variable:

1 const age = 21

If we attempt to reassign the value of the age variable, we’ll get an


error:

1 age = 22
2
3 // Uncaught TypeError: Assignment to constant variable.

This is because the age variable is a constant variable and can’t


be reassigned. Using the const keyword is my preferred way of
declaring variables that don’t need to be reassigned.

Variable naming rules and


conventions
In programming, a convention is a set of guidelines you should
follow to ensure that your code is written in a consistent style and
is easy to read and understand. When naming your variables, it’s
essential to follow the JavaScript variable naming conventions to
ensure that your code runs properly and to avoid bugs. A bug is an
error in your code that causes it to run incorrectly or not run at all.
Here are the rules and conventions commonly followed when
naming variables in JavaScript. We’ll start with the things you
Variables in JavaScript 23

should avoid, then move on to what you should do when naming


your variables.

Avoid using numbers as the first character


of a variable name

Variable names can’t start with a number, although they can


contain numbers. For example, the variable name person1 is valid,
but if you name your variable 1person, you’ll get an error.

Avoid using special characters in variable


names

In JavaScript, special characters are characters that have a specific


meaning or use in the language and are not letters, numbers, or
symbols. These include the following: @ ! # $ % ^ & * ( ) _ + - = { }
[]:;“’<>,.?/\|‘~
Variable names cannot contain special characters, so if you try
to name your variable name-of-person or #name_of_person, you’ll
get an error. The dollar symbol is sometimes used as a prefix for
variable names, but this is not a requirement and is generally not
recommended.

Avoid using spaces in variable names

Variable names cannot contain spaces. So naming your variable my


country or my age will result in an error.
Variables in JavaScript 24

Avoid using reserved words in your variable


names

JavaScript has a list of reserved words that cannot be used as


variable names. These include words like var, const, and let. Using
a reserved word as a variable name will result in an error. You can
check out the full list of JavaScript reserved words in the Mozilla
Developer Network (MDN) documentation. (link here)

Maximum and Minimum length of a


variable name

There is no explicit maximum or minimum length for variable


names in JavaScript. However, some constraints can affect the
maximum length of your variable name.
One such constraint is the maximum length of a string in JavaScript,
which is 2^53 - 1 (approximately 9 quadrillion characters). So you
can’t have a variable name longer than this, but it’s unlikely that
you’ll need to use a variable name this long in practice.

Use camelCase for variable names

When naming variables, one word might not be enough to describe


what the variable is storing. Since you cannot use spaces in variable
names, you can use camelCase to separate the words that make up
your variable name.
CamelCase is a naming convention in which the first letter of a
variable name is in lowercase, and the first letter of each subsequent
word is in uppercase. For example, if you want to name a variable
that stores a student’s age, you can write it as studentAge or
ageOfStudent.
Variables in JavaScript 25

In JavaScript, camelCase is the most commonly used naming con-


vention for variables. So, when naming your variables, always start
with a lowercase letter and use camelCase to separate the words.

Use meaningful variable names

It’s important to use descriptive and meaningful names for your


variables; this will make your code easier to write, read and
understand. For example, if you’re creating a variable to store a
student’s name, you should write something like nameOfStudent or
stuendentName instead of x or sname. Your variable names should
always represent the data they store because descriptive variable
names make it easier to understand the purpose and function of
variables. This will help you avoid bugs, improve the quality of
your code and make it easier to maintain.
How you name your variables is very important, and by following
the recommended conventions, you’ll be able to write code that is
easy to read, understand and maintain.
Basic JavaScript
operators
Operators are symbols that perform actions on values. For example,
when you write 2+3 on your calculator, you use the + operator to
add two values. The values 2 and 3 are called operands, while the
plus symbol (+) is the operator. In this chapter, we’ll explore the
different types of operators in JavaScript, including:

• Arithmetic operators
• String operators
• Assignment operators
• Comparison operators
• Logical operators

Arithmetic operators
We use arithmetic operators to perform mathematical calculations
like addition (+), subtraction (-), multiplication (*), and division (/).
Here are examples you can try in the console:

1 console.log(10 + 2) // Output: 12
2 console.log(10 - 2) // Output: 8
3 console.log(10 * 2) // Output: 20
4 console.log(10 / 2) // Output: 5

We also have the increment and decrement operators. The incre-


ment operator (++) increases the value of a variable by 1, while the
Basic JavaScript operators 27

decrement operator (—) decreases the value of a variable by 1. These


operators can be placed before or after the operand.
When placed before the operand, the operators are called prefix
operators, which means that the operation is applied before the
value is returned, giving us a new value. Here’s an example:

1 let firstValue = 3
2 console.log(++value) // Output: 4

When placed after the operand, they are called postfix operators;
the operation is applied to the variable after the current value is
returned. Here’s an example:

1 let secondValue = 5
2 console.log(value++) // Output: 5
3 console.log(value) // Output: 6

Notice that we have to log the variable separately to get its new
value. This is because when you use the postfix operator, the value
is returned first, and then the operation is applied.
It’s also important to note that the increment and decrement
operators reassign new values to variables, so you can only do this
with variables you declare using the let keyword. If you try to use
these operators on a variable you declare with the const keyword,
you’ll get an error. Let’s give it a try. Remember always to run these
examples yourself to see the results:

1 const thirdValue = 7
2 console.log(++value)
3 // Uncaught ReferenceError: value is not defined

There are two other arithmetic operators that you can use in
JavaScript: the remainder operator (%) and the exponentiation
operator (**).
Basic JavaScript operators 28

The remainder operator returns the remaining value when an


operand is divided by another. So if you run 5 % 2 on your console,
you’ll get 1 because 2 will go into 5 twice and leave 1 as the
remainder.
The exponentiation operator raises the first operand to the power
of the second operand. So if you run 2 ** 3 on your console, you’ll
get 8 because 2 to the power of 3 is 8 (that is 222).

The Concatenation operator


In JavaScript, we use the concatenation operator to concatenate
strings. The plus symbol (+) serves as the concatenation operator
when one or more of the operands are strings. So if you run 'Hello'
+ 'World' on your console, you’ll get “HelloWorld” as the output.
Also, if you run 'Hello' + 1 on your console, you’ll get ‘Hello1’
as the output. When you use the plus operator with strings and
numbers, the numbers will be converted to their string form and
then concatenated. Let’s try some more examples:

1 console.log('Hello' + ' ' + 'Everyone')


2 // Output: Hello Everyone
3 console.log('James ' + 'Bond ' + 007)
4 // Output: James Bond 007
5 console.log(
6 10 + 'years from now' + "I'll be a 100 years old"
7 ) // Output: 10 years from now I'll be a 100 years old

Notice that we used the space character (’ ’) to separate the words


in the first example. If we didn’t use the space character, we would
get ‘HelloEveryone’ as the output.
In the second example, we added the space character in the same
string as the word ‘James’. This is another way to add spaces
between words when concatenating strings.
Basic JavaScript operators 29

In the third example, we used double quotes (“ “) to enclose the


string. This is because the string (I’ll) contains a single quote which
will cause an error if we also use single quotes (’ ’) to it.

Assignment operators
We use assignment operators to assign a value to a variable. You’ve
already seen the assignment operator (=) in action. There are also
compound assignment operators in JavaScript, which include: +=,
-=, *=, /=, and %=. These compound operators perform an operation
with a variable and an operand and then assign the result to the
variable. For example, if you have a variable named “age” with a
value of 10, and you want to increment it by 5, you can use the +=
operator like this:

1 let age = 10
2 age += 5 // Output: 15

Using the += operator is the same as writing age = age + 5, which


reassigns the age variable to 10 + 5. Let’s try some more examples
with the other compound assignment operators:

1 age = 10
2 age *= 5 // Output: 50
3 age /= 5 // Output: 10
4 age -= 5 // Output: 5
5 age %= 5 // Output: 0

Compound assignment operators are a great way to make your code


less repetitive.
Basic JavaScript operators 30

Comparison operators
We use comparison operators to compare two values and return a
boolean value (true or false) based on the comparison result. Here
are the comparison operators and their meanings:

• ==: equal to
• != : not equal to
• > : greater than
• < : less than
• >= : greater than or equal to
• <= : less than or equal to
• === : strict equal to (compares both the value and the type of
the operands)
• !== : strict not equal to (compares both the value and the type
of the operands)

Let’s try some examples:

1 console.log(10 == 10)
2 // Output: true
3 console.log(10 == 5)
4 // Output: false
5 console.log(10 != 5)
6 // Output: true
7 console.log(10 > 5)
8 // Output: true
9 console.log(10 < 5)
10 // Output: false
11 console.log(10 >= 10)
12 // Output: true
13 console.log(10 >= 11)
14 // false: 10 is neither greater than nor equal to 11
15 console.log(10 <= 10)
Basic JavaScript operators 31

16 // true: 10 is equal to 10
17 console.log(10 <= 9)
18 // false: 10 is neither less than nor equal to 9
19 console.log(10 === 10)
20 // true: 10 is equal to 10 and they are both numbers
21 console.log(10 === '10')
22 // false: number 10 is not the same as string 10
23 console.log(10 !== 9)
24 // true: 10 is not equal to 9
25 console.log(10 !== '10')
26 // true: number 10 is not the same as string 10

Logical operators
In JavaScript, we use logical operators to perform logical operations
like AND (&&), OR (||), and NOT (!). Here are some examples:

1 console.log(true && true) // Output: true


2 console.log(true && false) // Output: false
3 console.log(false && true) // Output: false
4 console.log(false && false) // Output: false
5
6 console.log(true || true) // Output: true
7 console.log(true || false) // Output: true
8 console.log(false || true) // Output: true
9 console.log(false || false) // Output: false
10
11 console.log(!true) // Output: false
12 console.log(!false) // Output: true

The AND operator returns true if both operands are true, and false
if either operand is false. So if you run console.log(10 > 5 && 7
< 10) on your console, you’ll get true as the output because 10 is
greater than 5, and 7 is less than 10. But if you run console.log(10
Basic JavaScript operators 32

> 5 && 7 > 10) on your console, you’ll get false as the output
because 10 is greater than 5, but 7 is not less than 10. When using
the AND operator, both operands must be true for the result to be
true.
The OR operator returns true if any of the operands is true, and false
if both operands are false. So if you run console.log(10 > 5 || 7 >
10) on your console, you’ll get true as the output because one of the
operands is true (10 is greater than 5). If you run console.log(10 <
5 || 7 > 10) on your console, you’ll get false as the output because
both operands are false.
The NOT operator returns true if the operand is false, and false if
the operand is true. So you can read !true as “not true”, and !false
as “not false”.
Operators are an essential part of programming, and you’ll always
need them when writing code. Remember that you must practice a
lot to become a good JavaScript developer. So go over this chapter
a hundred times if you need to, and try using each of the operators
with different examples. You’ll get better at them with time.
Functions
In JavaScript, functions are a way to group code that can be reused
or executed as many times as needed in a program.
You’ve already used the console.log() method to display things in
your console, and the typeof() method to find the type of values.
In JavaScript, built-in functions are called methods.
The console.log() statement contains several lines of code you don’t
see, and this is what actually tells the JavaScript engine to display
the value you put in parenthesis on the console so that when
you run console.log('Hello World!'), the JavaScript engine will
display the text Hello World!
With JavaScript functions, you can run the same set of statements
from multiple places in a program without having to rewrite it each
time.

How to define functions in


JavaScript
JavaScript allows us to define functions in different ways. A com-
mon way to do this is through the function keyword. Let’s write a
function that multiplies any number by two and returns the result:

1 function multiplyByTwo(value) {
2 const result = value * 2
3 return result
4 }

From our above function;


Functions 34

• The name of our function is multiplyByTwo, which is provided


right after the function keyword.
• The parenthesis next to the function name holds the function
parameters.
• Parameters are names used to represent the values we want
to use in our functions.
• The code block after the opening curly brace is the function
body.
• The return keyword is used to end the execution of a function
while returning a specified value. This value is called the
return value.

Function parameters

The parameters of a function are names used to represent real


values we intend to provide when we call a function. In our
example above, our function parameter is value. When we call
the multiplyByTwo function, we’ll provide the actual value for this
parameter.

What is a function call?

A function call or function invocation is a request to execute a


function. We’ll see how to do this when we use the multiplyByTwo
function.

The return keyword


We use the return keyword to end the execution of a function
while providing a specified value. In our case, the multiplyByTwo
function returns the calculation result. Let’s see how to use the
return keyword to end the execution of our function conditionally:
Functions 35

1 function multiplyByTwo(value) {
2 if (isNaN(value)) {
3 return ' Value must be a number'
4 }
5
6 const result = value * 2
7 return result
8 }

In our new function, we added a condition that checks if the value


parameter is a number, using the built-in JavaScript isNaN function.
isNaN means “is not a number” and returns true if the provided
value is not a number. In this case, if the value parameter is not
a number, the first return statement would terminate the function
and return the string, “Value must be a number”.
The above syntax we used to define our JavaScript function is called
function declaration. Now, let’s tell our function to run the code
it contains.
We’ll do this by invoking it. And to invoke our JavaScript function,
we only need to write its name followed by a parenthesis:

1 multiplyByTwo()

Remember that in our function definition, we used the parameter,


to represent the real value to be multiplied.
value

To provide that number to our function, we’ll place it inside the


parenthesis invoking our function:

1 console.log(multiplyByTwo(35))

Here’s what we’ll see on our console when we run the above code:
Functions 36

1 70

Let’s try supplying our function with a non-number:

1 console.log(multiplyByTwo('this is a string'))
2 // output: Value must be a number

Function Parameters vs Arguments


When invoking our function, the values we supply to it in place of
its parameters are known as arguments.
So in our case, the number 35 and the string “this is a string” are
our function arguments.

• During a function definition, the names representing the val-


ues we intend to supply to the function are called parameters.
• During a function call, the actual we provide to the function
are known as arguments.
• We can use up to 255 parameters in a function definition.

More on the return statement


Without using the return statement to tell our function what to
return, its default value will be undefined.
Let’s test this by creating a function without a return statement
and then invoking it:
Functions 37

1 function multiplyByTwo(value) {
2 const result = value * 2
3 }
4
5 console.log(multiplyByTwo(35))
6 // output: undefined

The function also returns undefined by default when we provide


the return keyword without a value.This makes it an **empty
return**:

1 function multiplyByTwo() {
2 const result = value * 2
3 return
4 }
5
6 console.log(multiplyByTwo(35))
7 // output: undefined

Anonymous functions
You’ve seen how to use function declarations to define named
functions. You can also use function declarations to define anony-
mous functions and Immediately Invoked Function Expressions
(IIFE).
Anonymous functions are functions that are without names;
hence, the word anonymous.

1 function () {
2 return alert("I'm a function, and I'm anonymous!")
3 }

Since we cannot reference the above function by a name, there


is no way to call it elsewhere in our codebase. When this is the
Functions 38

case, the function is usually an IIFE (Immediately Invoked Function


Expression), which means that it’ll be invoked immediately after it
is declared. To achieve this, we’ll wrap the function in parenthesis
and immediately call it with another open-and-close parenthesis
right after its declaration:

1 ;(function () {
2 return alert("I'm a function, and I'm anonymous!")
3 })()

Notice how we declared our function inside the parenthesis before


invoking it.

Function expression

To reuse an anonymous function, we have to assign it to a variable.


This way, we can reference it by that variable name. A way to do
this is through Function expression. Let’s assign our anonymous
function to a variable:

1 const alertUser = function () {


2 return alert("I'm anonymous, but with a name!")
3 }

Now, we can invoke (or call) our function the same way we invoked
multiplyByTwo(). Since our function has no parameter, there’ll be
no need to supply an argument.

1 alertUser()

Result:
Functions 39

1 I'm anonymous, and you can reference me by a name!

Multi-line return statements


When returning an expression in a function, don’t add
a new line between return and the value.

You might be tempted to separate your expression from the return


statement like this:

1 function multiplyByFive(value) {
2 return
3 value * 5
4 }
5
6 console.log(multiplyByFive(10))
7 // output: undefined

Calling the above multiplyByFive function will return undefined,


and this is because our compiler ends the statement after the return
keyword, making it an empty return. If you want to wrap the return
statement across multiple lines, you should start your expression on
the same line as the return keyword or have an opening parenthesis
on the same line as the return keyword:

1 function multiplyByFive(value) {
2 return value * 5
3 }
4
5 console.log(multiplyByFive(10))
6 // output: 50
Other documents randomly have
different content
«Signora Marchesa, voi mi chiudeste la porta di vostra casa, ed io
passai per la finestra. Sono sul balcone, ed aspetto i vostri ordini.»
«Luigi.»
(Indignata). Oh! quale arditezza! ma io chiamerò gente (riflette) no,
non va bene.... nascerebbe uno scandalo. Ah, signor Luigi, voi siete
sul balcone con questo gelo, eccovi punito, stateci tutta la notte
(chiude col catenaccio). Ora sono sicura. Cioè, non mi metto certo in
letto; leggerò qui accanto al fuoco, e domani lo troverò gelato (siede
sulla poltrona). La è però una crudeltà; poverino, fa un freddo
dannato.... ebbene, se ne vada per la strada che è venuto. Ma ora
che ci penso, di là non c’è mezzo a discendere, non vi è il pergolato
sotto. Dunque resti, per me ci penso punto, faccia il suo comodo e
buona notte (pausa). Infine che vuole? cos’è venuto a far qui?... Mio
Dio! mi prende rimorso; potrebbe morirsi pel freddo. — Per carità, è
meglio aprire, e farlo ridiscendere dalla finestra (va verso il balcone),
mi tremano le mani. Ah, prima chiudasi questa porta che mette nelle
stanze di mia cognata; potrebbero sentirlo (chiude l’uscio a destra,
poi apre il balcone). Signore! venga fuori, e se ne vada per dove è
venuto (siede sulla poltrona voltando le spalle a Luigi che entra).
Luigi (entra lentamente, rinchiude la vetriata e resta indietro).
Marchesa (senza voltarsi). Dunque, signore, se ne va, oppure debbo
farlo accompagnare da’ miei servi?... non risponde nemmeno? ha
forse la lingua gelata?
Luigi. Eh! ci manca poco.
March. Si sbrighi, apra la finestra, e buona notte. Fortuna per lei che
non ha trovato una donna di cuor duro.
Luigi. Ci aveva contato prima sul suo buon cuore.
March. Non ascolto verbo, vada via.
Luigi. Ma prima... mi permetta...
March. Signore! Io mi meraviglio di lei. Che fosse ardito, lo sapeva,
ma sino a questo punto... (sempre senza voltarsi).
Luigi. Per carità, marchesa, non si alteri, ne avrei troppo dolore. Lo
depongo qui sul tavolo?
March. Che cosa?
Luigi. Il mio mazzolino che le offro pel suo giorno onomastico. Le
pare che io avrei potuto lasciarmi sfuggire una sì bella occasione
senza darle prova del mio profondo rispetto?
March. Ah! ella intende darmi prova di rispetto passando per la
finestra?
Luigi. Il rispetto si esprime come si può. Per la porta non c’era il
passo libero, e sarebbe stata dal canto mio una grave mancanza
quella di non rimediarvi alla meglio.
March. Ho capito. Ora può andare.
Luigi. Signora marchesa, non mi faccia quest’affronto; accetti i fiori di
mia mano, poi me ne vado. Poverini sono intirizziti.
March. No. Le ho detto d’andare, e badi che se indugia ancora
chiamo gente.
Luigi. Se avesse quest’intenzione l’avrebbe già fatto; ma ella è tanto
buona.
March. Eppure le ripeto che...
Luigi. Non si faccia cattiva; io non ci credo; tanto è vero che ella ha
persino chiuso quella porta.
March. (con stizza). Ah!...
Luigi. Dunque? (con preghiera).
March. Dia qui quei fiori.
Luigi (avanzandosi lentamente). Eccoli.
March. Presto.
Luigi. Gli è che non posso camminare, ho le membra irrigidite dal
gelo.
March. (voltandosi a guardarlo). Mio Dio, com’è stravolto!
Luigi. Lo credo... se restava là un altro poco, era finita.
March. (con premura generosa). Oh! mi perdoni, signore, sono una
gran trista! (lo fa sedere sulla poltrona).
Luigi (riscaldandosi al fuoco). Grazie, signora marchesa, il cielo vi
restituisca altrettanto.
March. (ironica). Spero che non ne avrò di bisogno, perchè certo non
vado ad arrampicarmi per le finestre come...
Luigi. Come un furfante. Dica pure, signora. Ma io ho una gran
giustificazione.
March. E sarebbe?
Luigi. Sarebbe che io son venuto qui a cercare della cosa mia.
March. Il giudizio forse?
Luigi. Cerco la mia testa che si ostina a gironzarle intorno.
March. Questo sarebbe un confessare che ella è senza testa. A lei,
eccole il mio Album, cerchi, e se la porti via.
Luigi. Scusi, ma la mia testa non ci può stare lì dentro.
March. Perchè? ce ne sono tante d’altri.
Luigi. Saranno teste piccole.
March. Certo la sua è più grossa; c’è tanto fumo!
Luigi. È tutto quello mi resta del mio amor proprio.
March. Basta; ora che si è riscaldato, spero che se ne vorrà andare.
Luigi. Io, no certo.
March. Oh!
Luigi. Non già che io voglia, è lei che mi manda.
March. Come le aggrada.
Luigi (alzandosi). Se debbo dir il vero non avrei mai sperato di
trovare tanta indulgenza; ho scoperto in lei una dote superiore a
quella già grande della sua bellezza...
March. Sentiamola.
Luigi. La generosità.
March. Ma siccome non bisogna dare negli eccessi, così nel
ringraziarla tanto della sua bontà, la prego di andar via.
Luigi. Lo vuole proprio?
March. (affettando serietà). Signor Luigi! se io non la conoscessi per
originale, direi che ella è...
Luigi. Animo, me lo dica su.
March. Un pocolino temerario...
Luigi. È un sistema che adotto; dicono che così facendo s’incontra
fortuna colle donne.
March. Questa volta però...
Luigi. Fui fortunatissimo, perchè mi trovo qui a quest’ora, solo, colla
più amabile fra le donne.
March. Ella si schermisce a complimenti.
Luigi. Faccio come il cane, il quale lambisce la mano che gli tira le
orecchie.
March. Ecco, per esempio, una similitudine mal trovata.
Luigi. E perchè? l’atto di mandarmi via è per me assai più che tirarmi
le orecchie, e per conto mio le giuro che accetterei di restar qui tutta
la notte anche a costo di pagar domani la mia felicità colla vita.
March. Va bene.... ho capito, ma vada.
Luigi. È troppo giusto. Signora marchesa, i miei rispetti. Ridiscendo
dalla finestra, come i gatti. È il caso di dire che l’amore invece
dell’ali, mi ha dato quattro gambe (verso la finestra). Dunque buona
sera; mi perdoni l’audacia, e se domani sentirà dire che io fui trovato
morto sotto le sue finestre, pensi pure che mi sono scavezzato il
collo.
March. Via, signore, non faccia pompa di eroismo. Scommetto che
c’è una corda alla finestra.
Luigi. La signora s’inganna... venga a vedere.
March. (dopo aver guardato). E come farà?
Luigi. Mi provo.
March. E se ruzzolasse abbasso?
Luigi. Pazienza! siamo tanto in alto, che non avrei tempo di pensarci
sopra.
March. Signore! Ella ha voluto rendermi complice di qualche
disgrazia!
Luigi. Starebbe a lei prevenirla.
March. Allora scenda come può; già infine tutto è commedia; avrà
preso le sue precauzioni.
Luigi. Le giuro che no, tanto è vero che era disposto a morir di
freddo sul suo verone. L’ho scritto nel mio biglietto.
March. Nego. Sul biglietto non vi è nulla di tutto ciò.
Luigi. Guardi meglio.
March. (riprende il biglietto). Ecco qui. Non c’è altro.
Luigi. Ma volti. (legge) «Comprendo benissimo che la mia è temerità
eccessiva; se vorrà punirmene, mi lasci fuori per tutta la notte, e
colla presente, scritta di mio pugno, l’assolvo da ogni responsabilità
qualora diventassi sorbetto.»
(La marchesa resta sopra pensiero). Dopo tutto, signora, mi sembra
d’essere stato poco indulgente con me stesso.
March. Sì, ma infine avrebbe picchiato per farsi aprire.
Luigi. No certo. Anzi, se madama la marchesa lo desidera, ritorno sul
verone, e vi starò a suo piacimento. Dal canto mio sarò ben lieto di
scontare un poco il mio peccato.
March. Manco male che ne conviene.
Luigi. Certo! e se mi fosse lecito proclamerei ai quattro venti la sua
grande indulgenza.
March. Badi, signore, che non mi merito questa réclame, tanto è vero
che la costringo a scendere dalla finestra.
Luigi. E che perciò? Ella fa il dover suo.
March. Tuttavia se le accadesse qualche malore ne sarei desolata.
Luigi. Grazie, bella marchesa! le sue parole mi danno coraggio.
Scenderei dalla luna per farle piacere. Però, una preghiera. Io
scendo, ma può darsi che invece precipiti, ed allora... felice notte.
March. Ebbene?
Luigi. Ebbene, mi rincrescerebbe passare all’altro mondo senza esser
certo del suo perdono.
March. È perdonato.
Luigi. Desidero altro, un bacio su quella graziosa manina.
March. Oh!
Luigi (con grazia). È la preghiera di un morente!
March. (tende la mano). A lei (Luigi la bacia, ma mentre fa per
andarsene ella lo trattiene serrando la mano). Peraltro, signor mio,
non riesco a comprendere la cagione di questa sua eccentricità. Per
portarmi i fiori? non valeva la pena d’arrischiarsi a tanto.
Luigi. La signora marchesa mi permetterà di tacere — preferisco
scender subito.
March. Si tratta forse d’una scommessa?
Luigi (serio). Signora, aveva pur detto d’avermi perdonato, ma quel
suo pensar così male sui miei propositi, mi addolora.
March. Dunque dica su.
Luigi. Signora, no. Se entro nella via delle confidenze ridivento
colpevole. Eppoi l’ora è tarda. Ella avrà forse bisogno di riposo.
(Notisi che qui parla maliziosamente, e fingendo una riserva che non
ha).
March. Chissà! forse non ci penso ancora, passerò qualche tempo
leggendo; anzi, se ella avesse qualche storiella in pronto, così tanto
per impiegare una mezz’ora...
Luigi. E poi?
March. Poi studieremo un mezzo per farlo scender con minor
pericolo.
Luigi. Accetto di cuore.
March. Allora s’accomodi... racconti ed io lavorerò un poco. (La
marchesa occupa la poltrona, Luigi siede presso di lei).
Luigi. Signora marchesa, io sono franco, e le dico sinceramente che
se domani dovessi morire, non mi lamenterei.
March. Lo credo io, non ne avrebbe più il tempo.
Luigi. Ah! mi dimenticava che ella è materialista.
March. E lei?
Luigi. Una volta lo era io pure, ma mi sono corretto; ho cambiato
dottrina.
March. Evviva la fede.
Luigi. Non mi parli di fede, tutto è convenzione a questo mondo; si
giudica sempre dal punto di vista delle convenienze.
March. Se ne avessi il tempo, mi proverei a convertirlo.
Luigi. Lo tenti, ma sarà fatica sprecata, ed anzi in questo momento
mi persuado viemmeglio delle assurdità del materialismo.
March. Mi dica in grazia, perchè ha cambiato bandiera?
Luigi. Non è cosa agevole il dirlo, ma quello che sento alla vista del
bello mi esalta, mi commove, e certo la materia non ha tanto potere.
Oh! io mi meraviglio altamente che ella non creda nell’ignoto! ma si
guardi, signora marchesa, si guardi nello specchio, cerchi ne’ suoi
occhi pieni di fuoco, e mi neghi se lo può la potenza del fascino. Io
poi che la vedo nel suo insieme, io che in guardarla mi sento acceso
d’entusiasmo non posso porre in dubbio l’esistenza di quell’anima
che si cela sotto forme sì vaghe; non posso negare che vi siano degli
angioli, se me ne vedo davanti uno tanto bello.
March. (con fino motteggio). Molto bene. Ella si serve di tutto per
venire allo scopo. — Ha spezzato una lancia contro il materialismo
per farmi un po’ di corte.
Luigi. No, proprio davvero, non c’entra la premeditazione; egli è nella
foga di parlare che mi sono tradito.
March. Poverino, si è tradito! — Ella fa gran sfoggio d’ingenuità, ma,
caro mio, gli ingenui non vanno in casa delle signore passando per le
finestre.
Luigi. Madama la marchesa si dimentica che per me la porta era
chiusa.
March. Eravi forse necessità di venir stassera?
Luigi. Certo, passata la festa si spegne il moccolo, dice il proverbio,
domani era tardi per portare i fiori.
March. Non era un gran male!
Luigi. Comprendo benissimo che il mio omaggio è per lei cosa di
poco conto, e che altri migliori di me si meritano preferenze,
tuttavia, anche colla certezza di essere tenuto fra gli ultimi, non sarei
stato meno colpevole lasciandomi sfuggire l’occasione per
dimostrarle che la mia devozione per lei è tanto grande, quanto la
sua degnazione per me.
March. Signor Luigi! io non credo d’averle mai dato diritto ad un
rimprovero così acerbo. Se a mostrarsi sinceramente amica si
guadagna il compenso di essere mal compresa, ne sono dolente. —
Ella non è per nulla l’ultimo fra i miei amici, anzi se mi fosse lecito far
delle distinzioni, ne farei a suo riguardo. Lo sa più di quanto io possa
provarglielo. La mia condizione m’impone dei riguardi che io debbo
subire rassegnata, epperciò quando incontro un amico sincero,
mentre col cuore gli sono gratissima, debbo però usare seco lui quel
fare vago che non desta sospetti o maldicenze. Sa pure che io voglio
mantenere assoluta la mia libertà d’azione. Ho i miei capricci e
dubito molto degli uomini; sono vedova e voglio godermi in pace la
vita; ma ciò non impedisce che io possa degnamente apprezzare un
sentimento d’amicizia vera ed affettuosa. Ella dunque, signor mio, è
un ingrato; perchè sa tutte queste cose senza che io mi sforzi a
provargliele, eppure si diletta a metterle in dubbio.
Luigi. In fede mia, ella ha tutte le ragioni (stringendole la mano).
Sono proprio un ingrato, giacchè se è vero che posseggo un poco
della sua amicizia, ho assai più che non mi meriti.
March. Così va bene.
Luigi. A dirla franca, mi pareva che il barone Calani occupasse un
posto distinto.
March. Oh! Cielo, mi fa una corte ostinata, non trascura nulla, dai
mazzolini parlanti ai confetti colle cartoline amorose; ma io non sono
tanto ingenua da cader nelle reti per sì poco.
Luigi. E quel marchesino?
March. Mio cugino? Colui mi fa il galante colla certezza d’averne
diritto. È mio parente, e lo tratto come tale. Del resto è una creatura
molto noiosa.
Luigi. Il conte Pollini però è uomo di spirito, e mi sembra degno di
occupare una sedia chiusa.
March. Sì, il conte è meco molto amabile, ma anche lui ha il suo
difetto. Si figuri che dice di sognarmi tutte le notti, o colle corna da
diavoletto, o colle ali d’angelo.
Luigi. E lei ci crede.
March. Può chiedermelo? non credo agli uomini quando son desti,
dovrei fidarmi se dormono?
Luigi. Peccato!
March. Perchè mai?
Luigi. Aveva io pure un sogno da raccontarle.
March. Dica, sentiamo, per lei faccio un’eccezione.
Luigi. Ma non crede?
March. (ironica). Altrochè! e ci punterò sopra cento lire al lotto.
Luigi. Allora ritiro il sogno; ma badi, signora marchesa, i sogni sono
rivelazioni divine, Giuseppe salvò l’Egitto.
March. E lei sarebbe un nuovo Giuseppe?
Luigi. Signora no, per quanto poco ci tenga al mio carattere d’uomo,
pure le confesso che non sarebbe necessario di lacerarmi il mantello
per trattenermi.
March. Peccato che le manchi l’occasione.
Luigi. Si provi lei a prendermi per i panni.
March. (alzandosi). Invece la storia è alquanto modificata; madama
Putifarre manda via Giuseppe.
Luigi. Dunque non vuol saperne del mio sogno? Ella è una donna
senza fede.
March. Tutt’altro! di fede ne ho molta, quella che mi manca è la
buona fede.
Luigi. Ecco una graffiata che non mi merito. Mandarmi via sta bene,
ma così bruscamente... Se non racconto il mio sogno, non morirò
tranquillo.
March. Me ne rincresce tanto, ma la è proprio così.
Luigi. In guardia, signora marchesa! questa sua repentina risoluzione
potrebbe contraddirla alquanto su quella indifferenza che vanta
tanto.
March. Vale a dire?
Luigi. Vale a dire che mandandomi via ella confessa in certo modo
che la mia presenza le desta un po’ di turbamento.
March. Oh! questo poi no. Ma ella è un gran briccone, e mi costringe
a darle prova del mio sangue freddo. Animo ritorni qui, e mi racconti
il suo sogno.
Luigi. Così va bene! (si siedono ancora).
March. Racconti pure.
Luigi. Eccomi (tossisce), prima di tutto, dichiaro che trattandosi di un
sogno io non ci ho nessuna responsabilità. Quando si entra nel regno
di Morfeo, bisogna adattarvisi alla meglio.
March. Questa è la prefazione.
Luigi. Se la signora marchesa sel ricorda, pochi giorni sono, mi invitò
a scrivere dei versi nel suo album.
March. (con intelligenza). Ah! sì.
Luigi. C’è una strofa infine che dice:

Talor sognando appagasi


La brama che mi strugge,
Mi desto allora... ahi misero!
Il labbro tuo mi sfugge.

March. (sorridendo). È una petizione quella poesia.


Luigi. Quasi. Oh i poeti sono ben pazzi!
March. Con tutta modestia ella si mette fra i poeti?
Luigi. Mi permetterà almeno di stare fra i pazzi.
March. Non lo contesto.
Luigi. Il mio sogno s’attacca a quei versi. Si figuri che una notte ella
venne in casa mia, proprio nella mia camera. Io me ne stava al
tavolo leggendo il Faust di Göethe, e vagolava colla mente per la
notte Classica di Valburga sui campi di Farsaglia, e nei gorghi
dell’Egéo fra sirene, najadi, sfingi e gnomi, quando ad un tratto vidi
proprio lei, signora marchesa, comparirmi innanzi... bella, bella come
Elena, avvolta in una lunga veste bianchissima. In vederla io rimasi
sorpreso, confuso, elettrizzato, e tratteneva il respiro per la tema di
turbare la dolce visione. Vi fu qualche minuto di silenzio per ambe le
parti, finalmente l’ombra sclamò con voce delicata:
«Signor Luigi, siete uno sciocco.»
March. Aveva dello spirito quell’ombra (ride).
Luigi. Era la vostra, poteva esserne priva?
March. Continui pure.
Luigi. Perchè? chiesi io, e l’ombra rispose:
«Perchè non avete coraggio; da un anno mi fate la corte, e non
sapeste trovare un momento buono.
«Ma, risposi io, marchesa mia, voi avete un’antipatia marcata per gli
uomini... diceste voi stessa di non creder più all’amore.
«Sono cose che si dicono, soggiungeste voi (fingendo d’essersi
sbagliato). Oh! perdono m’imbroglio, mi lasci che le dia del voi, sarò
più libero nella parola.
March. Fate pure.
Luigi. Signora marchesa, se io sapessi... se potessi... dunque vi do
del voi?
March. Sentiamo cosa rispondeste all’ombra.
Luigi. [1] Balbettai qualche parola, e poi facendomi animo sclamai:
«Ma io, cara marchesa, sono timido, non so dirvi l’animo mio... non
l’oso; voi avete delle tristi prevenzioni sugli uomini. D’altronde posso
io aspirare ad un vostro sguardo?... voi il fiore della nobiltà, voi così
bella, così vagheggiata, non trovereste neanche un sorriso di pietà
pel temerario che ardisse alzare gli occhi sino a voi. — Infine io
riconosco troppo bene la distanza che ci separa; voi mi stimate
assai, ma io valgo poco, perchè indegno della vostra amicizia come
della vostra stima, oso di volervi un po’ di bene, ed alimento in me
una passione insensata.»
March. Per fortuna che siete timido... del resto chissà dove vi sareste
fermato.
Luigi. La timidezza è il mio debole; sognando ho del coraggio, ma
quando vi sono vicino mi manca l’animo di aprir bocca.
March. Allora continuate a sognare.
Luigi. Quando ebbi finito, stetti aspettando una severa risposta; ma
la vostra ombra invece mi si appressò, e mi stese la mano che io
baciai sclamando: «Oh! signora voi siete la creatura più buona che io
mi conosca. La vostra anima generosa chiude in sè una scintilla
divina, e beato quegli che ne saprà comprendere le segrete
aspirazioni!»
March. E l’ombra?
Luigi. Mi rispose: «Vedete, Luigi, non sono poi quella ritrosa
indifferente che mi credevate. Ho del cuore io pure, tutto sta
saperne trovare la strada. Nata col retaggio di un nome che porta
corona di nobiltà; non mi inorgoglisco d’un titolo che sarebbe vano
se non fosse accompagnato da prodigalità di cuore e squisitezza di
sentire. — Io vi ho compreso benissimo, e voi che siete tanto timido,
voi solo meritate un poco del mio affetto, e sì dicendo.... (esita).... e
sì dicendo....
March. Avanti.
Luigi. Io non ci ho colpa, marchesa, è un sogno.
March. Ma infine! (durante il racconto la marchesa ricama sempre
affettando indifferenza).
Luigi (con fare elegante). E sì dicendo, si abbassò su me, ed io la
baciai in fronte.
March. (indifferente). Eppoi?
Luigi (sorpreso). E poi... mi sono svegliato.
March. E l’ombra?
Luigi. Sparita! — d’allora in poi mi punge il desiderio di realizzare il
mio bel sogno, e da un mese tento tutti i mezzi, tutti i sotterfugi
leciti per venire allo scopo. Mille volte dissi fra me: oggi vado da lei e
le dico: Signora marchesa, io ho bisogno di farvi un bacio, del resto
morrò... non dormirò più, non mangerò... Siate tanto buona da
concedermelo... fate conto di far limosina... ma quando sono qui, mi
trema il cuore, divento timido come uno scolaretto, e succede di me
come di quell’Olindo che

Brama assai, poco spera, e nulla chiede.

March. Ammiro la vostra timida riservatezza... gli ardimentosi mi


vanno poco a genio.
Luigi. Dunque?
March. (fingendo stupore). Dunque che cosa?
Luigi. È proprio un sogno?
March. E sarà sempre tale.
Luigi. Insomma, signora marchesa, se tanti mesi d’un’amicizia
disinteressata, se una devozione rispettosa si meritano qualche
distinzione, lasciate che io deponga un bacio sulla vostra bella
fronte... eppoi discendo di botto dalla finestra, anche colla certezza
che ho d’ammazzarmi.
March. Io non mi altero punto, nè mi offendo; so che la indiscrezione
degli uomini tocca il sublime, ma vi giuro che se anche foste lì per
morire di questa voglia, mi rifiuterei ugualmente (sempre con fare di
motteggio).
Luigi. Infine, marchesa mia, per voi non la è la gran cosa! vi lasciate
baciar la mano da chi lo desidera.
March. Ma nella mano ho le unghie, e graffio.
Luigi. E non avete lì due occhi che straziano assai più.
March. Ah! poverino, fate sforzi da Ercole per trovare una goccia di
spirito, ma in questo momento non siete in voi...
Luigi. È verissimo, sono in voi.
March. Ci manca il mio permesso.
Luigi. Non ne abbisogno, io sono nel mio diritto. La chiesa dice: Non
desiderare la donna d’altri, ma voi siete di nessuno. Siete vedova,
che è quanto dire in disponibilità.... dunque posso arrischiarmi.
March. Bevete del papavero e sognerete ancora.
Luigi. Signora marchesa, la vostra ombra è un po’ più arrendevole.
Infine poi non vi ha nulla di male in quello che chieggo. Un bacio
sulla fronte ha del paterno.
March. Avrei un padre molto scapestrato.
Luigi (con qualche stizza). Oh! sogno traditore! se non fosse troppo
vecchia la cavata esclamerei: (comicamente) Perchè mi risvegliai!?
March. Davvero che se esamino bene, trovo in voi la solita
presunzione, eterno retaggio di questo uomo che si chiama forte.
Ah! la vi par cosa facile realizzare un sogno! e con un coraggio
degno di miglior sorte, voi siete qui venuto per dirmi che sognate
delle corbellerie... ma, mio caro, andando di questo passo vi
fisserete in mente qualche giorno di abbracciare la luna. Avrete detto
fra voi: m’è venuto il ghiribizzo di fare un bacio alla marchesa, ho
dello spirito, delle risorse, e posso tentare il colpo. Colle vostre
circonlocuzioni viziose un giorno mi obbligaste a domandarvi dei
versi, e voi subito una stoccata per cantarmi in rima il vostro
desiderio inqualificabile. Oh le donne sono scioccamente ingenue,
cascano presto nella rete!... Quattro versi stirati alla meglio, alcune
cadenze pescate nel Rimario, fanno un grand’effetto. E lì giù a
comporre e scrivermi sull’Album una poesia ch’io leggo per
esilararmi.
Luigi. Oh!
March. Ma sì, certo, credete forse che io presti fede al vostro
struggimento? (lo canzona) poverino! se vi batte il cuore prendete
del cloraglio... oppure bagni freddi; vi gioveranno per la testa che è
un pochino guasta. Credete voi altri che bastino alle donne le vostre
affettature galanti, e le eterne frottole che andate snocciolando coi
soliti sospiri e contorcimenti d’occhi?... Ih! ih! ci vuol altro! cuore e
sincerità, non presunzione e frivolezza. Credete di ingannar noi, ma
quasi sempre siete voi gli ingannati. Ci vuol altro, caro signor Luigi,
ci vuol più spirito e più giudizio. Dopo tutto una cosa sola mi dà
pena, ed è quella di vedervi fare una figura molto comica in
quest’affare. (ridendo) Per carità non raccontate l’avventura ai vostri
amici, ne riderebbero un’eternità.
Luigi (sopraffatto). Signora marchesa, felice notte.
March. Dove andate adesso?
Luigi. Mi butto di balzo giù dalla finestra, non mi resta a fare altro
per provarvi di non esser tanto leggiero.
March. So benissimo che non mettereste le ali.
Luigi. Ma se resto qui ancora mi spunteranno le orecchie.
March. Non avete giustificazioni?
Luigi. Sì, signora, ne ho una che vale per tutte. Se io caddi in errore
si fu per creder troppo nell’esperienza di uno dei nostri grandi poeti.
March. Quale?
Luigi. Il Tasso che scrisse nell’Aminta quei versi:

Oh tu non sai com’è fatta la donna!


Fugge, e fuggendo vuol ch’altri la segua.
Nega, e negando vuol ch’altri si tolga,
Pugna, e pugnando vuol che altri la vinca.

Io ci ho creduto; voi negaste ed io volli togliermi, pugnaste e volli


vincervi, e mi resto dopo tutto con un pugno di vento.
March. Ma voi che siete poeta, come mai credete alle fanfaluche dei
vostri confratelli? pensate a tutte le bugie che diceste in rima, e
ditemi se avete ancor coraggio di credere. Però debbo riconoscere in
voi un abile strategico, avete esplorato il mio campo di battaglia,
studiato i miei libri. Davvero che siete assai previdente; duolmi che
abbiate sciupato la fatica per battagliare contro un mulino a vento.
Don Giovanni è diventato don Chisciotte! (ride).
Luigi. Sono lieto di una cosa, ed è che se non altro riesco a mettervi
di buon umore.
March. Sfido io a star seria con questi squarci di lirica che m’andate
tirando fuori. Ah voi siete della scuola del Tasso? vi compiango di
cuore, perchè se seguite in tutto il vostro maestro finirete voi pure in
un ospizio di pazzi, con molto minor gloria.
Luigi. Se ciò accadesse, voi signora marchesa, dovrete averne
rimorso.
March. Oh! bella, e perchè mai?
Luigi. È facile respingere una responsabilità, e certo a bella prima
sembra che voi siate la creatura più innocente del mondo. Pure non
è così, la bellezza, signora mia, in certi casi è un reato. Che ne
possiamo noi poveri uomini dalla fantasia accendibile se al fascino
d’uno sguardo, alle graziose movenze, al suono di una voce soave,
non sappiamo tener salda la ragione? Ma io mentre vi guardo mi
sento capace di tutto, non sono più padrone di me, e se mi
comandaste di passarmi il cuore vi ubbidirei!... E tutto ciò non è
forse l’effetto di una malìa, l’influenza del fascino che esercitate? Se
domani venissi tratto in giudizio, io vi citerei come mia complice,
perchè colla vostra cortesia severa mi faceste dar di volta al cervello.
March. Molto bene; ma è forse nostra colpa se gli uomini sono tanto
buoni da far pazzie per nostro conto?
Luigi. Sì, e ve lo provo. Voi siete bella, lasciate che vel dica, so che vi
fa piacere; ostentate indifferenza per questa dote eccelsa della
vostra persona, ma il fatto vi contraddice. Perchè se non badate agli
uomini, perchè vi fate più bella coi ricci bizzarri della capigliatura,
con abiti provocanti, con pizzi e merletti che sfumano misteriosi
confini? Così facendo, tradite la vostra intenzione, quella di piacere.
Ecco la colpa, ecco il male. Noi poveri uomini alla vista di tanta
leggiadria andiamo in delirio; il tocco di una bella manina ci desta dei
fremiti, le movenze graziose ci esaltano, un’occhiata ci fulmina... noi
vediamo e siamo vinti. Supplichiamo per una grazia ed eccoci un
rifiuto; domandiamo un sorriso e ci si risponde con un’occhiata torva.
Dunque resta provato che tiranneggiate per progetto, e la
responsabilità dei nostri errori ricade tutta su di voi! — (La marchesa
lo guarda con aria quasi di crederlo... Luigi dopo una pausa si
avanza dubbioso e sorridente). — Dopo tutto, signora marchesa,
eccomi ancor qui umile e supplichevole; lasciate che realizzi il mio
bel sogno, eppoi farò quello che più vi piacerà.
March. (con malizia). No, no. Ah! credete che io mi lasci persuadere
da dolci parole? Io non mi piego.
Luigi. È la virtù delle canne deboli; si rompono.
March. Dite quel che vi piace. In quanto al vostro sogno, farete
meglio giuocandolo al lotto.
Luigi. È questa l’ultima parola?
March. No, la penultima... eccovi l’ultima (gli dà la mano); felice
notte.
Luigi (risoluto). E sia. Signora marchesa, io ricorderò quest’ora
passata insieme come quella più lieta di mia vita.
March. Ciò è cavalleresco! Badate, nello scendere, con alquanta
precauzione, vi troverete sul pergolato. Domani, se siete ancor vivo,
venite a dirmi come ve la siete cavata.
Luigi (un po’ serio). Mi rincresce, ma domani non posso, vado via.
March. Ebbene dopo domani.
Luigi. Nemmeno.
March. Andate dunque molto lontano?
Luigi. Oh molto... vado in America!
March. (colpita). Oh! che dite?
Luigi. Parto per Lima, ove raggiungo mio fratello.
March. E poi?
Luigi (commosso). E poi... mi fermo là.
March. (c. s.) Per sempre?
Luigi. Chi sa!
March. Necessità d’affari forse?
Luigi. No, signora, disgusto di stare in questa vecchia Europa, terra
per me di fallaci lusinghe.
March. (con apprensione). Che volete voi dire?
Luigi. Voglio dire, signora marchesa, che quando si fanno dei bei
sogni, bisogna scontarli con un triste risveglio. Voglio dire che
quando si è tanto stolti da crescere nel seno delle false speranze,
bisogna sopportarne le delusioni. Ma io non ho la forza di restar qui
coll’eterno spettacolo dinanzi agli occhi di una felicità che sarà
sempre un sogno per me. Parto, il viaggio, e gli affari faranno forse
più di quanto non potè la ragione.
March. (commossa). Luigi! giuratemi che questa partenza non è uno
stratagemma.
Luigi. Sull’onor mio, signora!
March. (con qualche imbarazzo). Ebbene, poichè andate tanto
lontano... e forse non ci vedremo più! non voglio certo lasciarvi
partire disgustato. Se veramente vi fa piacere... se lo desiderate
proprio di cuore, eccovi la fronte, fatevi un bacio!
Luigi (con slancio represso). Matilde, voi siete un angelo!... (la
bacia).
March. (un po’ confusa). Ricordatevi degli amici... e di me!
Luigi. Sempre serberò di voi la più cara memoria (la bacia ancora poi
fa per partire).
March. (con tenerezza). Luigi! restate in Europa?
Luigi. È impossibile, soffrirei troppo.
March. (dopo breve esitanza). Allora PORTAMI con TE in America.
Luigi (tornando a lei). Che dite?
March. (con slancio stringendogli le mani). Dico che un cuore nobile
come il TUO si merita assai più che non sia il meschino dono della
mia mano!
Luigi (inginocchiandosi). Oh! grazie!
March. (rialzandolo). Dunque, partirai ancora?
Luigi. No, resto in Europa! (l’abbraccia).

FINE DEL LEI, VOI E TU.


VERSI
ALLA BUONA
«IL CAVALIERE»

Mio carissimo Pipetto!.....

Già lo sai, mio gran difetto


Sta nel fare il beccafico
Sulle cose della gente,
Schiettamente te la dico,
Sono alquanto impertinente,
Ma che vuoi? tacer non posso
In veder certi asinoni
Animali fino all’osso
Che la fanno da padroni!

Dimmi tu come ho da fare


La mia tempra a raffrenare,
Tu m’insegna a darvi passo
Ed a starmene sul duro,
Se m’incontro ad ogni passo
Con quei ceffi da figuro. —
Uno poi mi dà sui piedi,
Cavalier de’ miei... stivali,
E tu amico deh concedi
Che con te la stizza esali.

Se lo vedi andare a spasso


Con quell’aria da gradasso,
Tu lo pigli in buona fede
Per un uomo d’importanza;
Tutto serio e grave incede
Pien di boria e tracotanza;
Per costume veste in nero
Porta guanti ed occhialino,
E a vederlo sembra invero
Alcunchè di sopraffino.

Affettando negligenza
Della croce ei ne fa senza,
E portar si degna appena
All’occhiello un picciol nastro.
Tiene al collo gran catena.
Un baston da borgomastro,
Con sussiego guarda attorno,
E si gonfia dal piacere,
Se si sente dire intorno
«Riverito, Cavaliere!»

D’una bestia al paragone


Nulla vale quel bestione,
Ed andando a vero onore,
S’egli è stato decorato,
Si può far commendatore
Anche un asino calzato.
Consiglier municipale
Ei fu eletto da diec’anni,
Ma sua cura principale
È dormire sugli scanni.

Quando schiude quella bocca


La sciocchezza vi trabocca,
Dà consigli, dà sentenze
Quello stolto babbuino,
Dice tante incongruenze
Da sgradarne Bertoldino.
Sa poi leggere, ma come
Nel latin di sacristia,
E per scrivere il suo nome
Fa un error d’ortografia.
Ignorante consigliere,
Petulante cavaliere
Pien di fumo, pien di boria,
Asinone in quintessenza,
Star coi nobili si fa gloria
Giacchè, a dirla in confidenza,
Questo stolido baggeo
Vero tipo dei COLOMBI
Sdegna il sangue di plebeo
Che gli scorre dentro ai lombi.

Ei passeggia lungo i viali


Pien di carte e di giornali,
Sbircia attorno colle lenti,
E se degna d’un saluto
Crede far tutti contenti;
Se poi sa d’esser veduto
Atteggiandosi a sussiego,
Tira fuori di scarsella
Qualche carta qualche piego,
Qualche lettera o parcella.

Entra in casa gravemente,


E ’l portiere immantinente;
— Ben tornato Cavaliere!
Batte all’uscio e il servo lesto:
— Riverisco Cavaliere,
Di ritorno così presto?
Forse l’aria è troppo fresca?
Ei si stempra pel piacere,
Ed il servo alla fantesca;
— Colazione al Cavaliere!

Cavalier dovunque suona


E per l’aria ognor risuona,
Te lo abbaja la cagnina,
E lo canta in grotta il gallo;
Nelle sale ed in cucina
Lo ripete il pappagallo,
Ed ovunque ti rivolga
Di scappar non hai potere,
Non c’è santo che ti tolga,
Suona sempre — Cavaliere. —

Ha una faccia che dà ai nervi,


Guarda tutti come servi
Dir che è un asino, un villano
Dir che è sciocco, è poco o niente;
Egli è un fior di ciarlatano
Ignorante impertinente.
— S’è la polvere inventata
Che distrugge insetti e bruchi,
Oh perchè non fu trovata
Polve tal per questi ciuchi?

E di simil raffataglia
Tanto è zeppa quest’Italia
Che ne incontri ad ogni istante
In ogni angolo di via,
E in tal modo andando avante,
Stammi a udir la profezia,
Si faranno cavalieri
Truffatori e burattini
Gabbamondi, barattieri
Stenterelli ed Arlecchini.
LA MORALE

Sei fior del secolo


Santa morale
Sei fatta l’idolo
Universale,
Ed il tuo fascino
Trascorre a volo
Come l’elettrico
Di polo in polo;
Are t’innalzano
Tutte le genti,
E ti strombazzano
Ai quattro venti.

Tu sei l’immagine
D’una speranza
Bella ed eterea
Nella sembianza,
Tutti ti guardano
Siccome un punto
Inaccessibile
Non mai raggiunto,
Tutti t’ammirano,
Ognun ti ha in bocca,
Ma infin dell’opera
Nessun ti tocca.

Il prete in pergamo
Ti canta lodi,
E di te predica
In mille modi;
Ma spesso ipocrita
Mentre si piega,
In fondo all’anima
Poi ti rinnega,
E lodi e prediche
Che a josa insacca,
Non son che il trespolo
Della baracca.

Dall’alte cattedre
Gravi retori
D’austere regole
Son banditori;
Coll’arma facile
Della parola
Fan d’arzigogoli
Confusa scuola,
Ma infin gonfiandosi
Con ciance vane,
Fan nulla e gracchiano
Come le rane.

Tutti t’inneggiano
MORALE Santa,
Ognun discepolo
Di te si vanta,
Delle tue massime
Si fa gran smercio
Come d’articoli
Messi in commercio;
E ti conservano
Nella vetrina
La dama rigida
E la sgualdrina.

Severi giudici
E magistrati
Sempre si vantano
Da te guidati;
Di te si dicono
Spezzata lancia,
Ma moralissimi
Son per la pancia;
Di Temi cingono
L’alma corona,
E tengon moccolo
Al Dio Mammona.

T’han messa in musica


In prosa e in rima,
Ma il mondo sdrucciola
Peggio di prima;
All’ombra placida
Di tua grandezza,
Si cela un’intima
Spudoratezza,
Tutti ti espongono
Con nobil gara
Siccome il balsamo
Di Dulcamara.

Passi qual zeffiro


Che lieve spiri,
E ’l mondo visiti
Per mille giri;
Ascendi al culmine
Di reggia aurata,
E là rimani
Mistificata;
Trascorri rapida.
Discendi all’are,
Ma ti tradiscono
Trono ed altare.

Servi di maschera
A una genìa
Grama per cinica
Ipocrisia;
Se badi a chiacchiere,
Sei vocazione
D’ogni ridicolo
D’ogni buffone;
Tutti ti spacciano
A piene mani,
Pseudo-filosofi
E ciarlatani.

Gente da trógolo
Sinistra e scura,
Coscienze livide
D’ogni lordura
Di te s’adornano
E vanno attorno,
Alto acclamandoti
E notte e giorno;
Ma sotto all’egida
Della tua maglia
Il marchio celano
Della canaglia.

Quei contafrottole
Leccastivali
Che ti strascinano
Su pei giornali,
Son gente equivoca
Che fa negozio
Di buone massime
Per stare in ozio;
Anime tenere
Fior di candore
Che ai loro comodi
Hanno il pudore.

Codesti arcangeli
Della grand’era
Diventan nottole
In sulla sera;
Deposto l’abito
Dell’apparenza,
Si fanno lecita
Ogni impudenza,
E poi risalgono
Sulla bigoncia
E ti contrattano
Un tanto all’oncia.

Nuovi proseliti
De’ tuoi dettati
Lenoni e protei
Son diventati;
Di fede in pubblico
Fan l’impresario,
Trecconi ignobili
Dietro il sipario,
E da neofiti
Di simil razza
Povera vittima
Sei tratta in piazza.

Oh! dalle nuvole


Sublime Dea
Scendi terribile
Nuova Adrastea,
E la tua collera
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