Stokes M. Typescript and JavaScript Coding Made Simple. 2 Books in 1... 2023
Stokes M. Typescript and JavaScript Coding Made Simple. 2 Books in 1... 2023
CODING TYPESCRIPT
MADE SIMPLE CODING
MADE SIMPLE
a BEGINNER'S GUIDE TO
PROGRAMMING UPDATED
A BEGINNER'S GUIDE TO
MARK stokes PROGRAMMING UPDATED
MARK stokes
TYPESCRIPT AND
JAVASCRIPT CODING
MADE SIMPLE
A BEGINNER’S GUIDE
TO PROGRAMMING
MARK STOKES
Chapter 1: Introduction to Typescript
A BEGINNER’S GUIDE
TO PROGRAMMING
MARK STOKES
Book Introduction
Chapter Titles:
1. Introduction to Typescript
2. Typescript Fundamentals
9. Generics in Typescript
Chapter 1: Introduction
to TypeScript
'typescript
console.log("Hello," + name +
sayHello("John");
In this code snippet, we have a function called
' sayHello' that takes a parameter ' name' of type
string. Inside the function, we use the ' console.log'
function to print a greeting message.
tsc hello.ts
node hello.js
Data Types:
TypeScript provides several built-in data types that
allow us to define the type of a variable explicitly.
These data types include:
- ' any' for variables that can hold any type of value.
This is useful when working with dynamic data or
when we don't want to enforce type checking.
'typescript
// Arrays
// Tuple
// Enum
enum Color {
Red,
Green,
Blue,
// Any
// Void
console.logC'Hello!");
// Object
name: "John",
age: 25,
Basic Operations:
Typescript supports various operators for perform
ing basic operations, such as arithmetic, assign
ment, comparison, and logical operations. These op
erators include:
- Arithmetic operators: ' +', ' -', ' *', ' /', ' %' for
addition, subtraction, multiplication, division, and
modulus.
'typescript
'typescript
'typescript
'typescript
} else {
switch (fruit) {
case "apple":
break;
case "banana":
console.log("Selected fruit is banana.");
break;
default:
break;
console.log(numbers[i]);
console.log("Count:" + count);
count++;
let i: number = 0;
do {
console.log("i:" + i);
i++;
Functions:
Functions play a crucial role in Typescript develop
ment. They allow us to define reusable blocks of code
that can be called with different inputs, and they can
also have return values.
'typescript
'typescript
'typescript
function sumNumbers(...numbers: number[]): num
ber {
sum + = num;
return sum;
Interfaces:
Interfaces in Typescript allow us to define the struc
ture of objects and provide a contract for implement
ing classes. They define the properties and methods
that an object should have. Interfaces can also be
used to enforce type checking.
'typescript
interface Person {
name: string;
age: number;
name: "John",
age: 25,
sayHello: function () {
console.log("Hello!");
Classes:
Classes in Typescript provide a way to define object
blueprints or templates. They encapsulate data and
behavior into a single unit. Classes can have proper
ties (variables) and methods (functions). We can cre
ate instances of classes using the ' new' keyword.
'typescript
class Car {
brand: string;
color: string;
this.brand = brand;
this.color = color;
startEngine(): void {
Introduction:
In this chapter, we will dive into advanced con
cepts in TypeScript that will further enhance your
understanding and proficiency in the language. We
will explore topics such as union types, intersection
types, type aliases, and generics. These concepts are
powerful tools that allow for increased flexibility
and reusability in your code.
Union Types:
Union types in TypeScript allow a variable to have
multiple types. It is denoted using the pipe (' |')
symbol between the types. This enables a variable
to hold values of different types at different times.
Union types are useful when we want to work with
values that can have different data types.
'typescript
Intersection Types:
Intersection types in Typescript enable us to com
bine multiple types into a single type. It is denoted
using the ampersand ('&') symbol between the
types. This allows an object or variable to have all the
properties and methods of the intersected types.
'typescript
interface Order {
id: number;
amount: number;
interface Customer {
name: string;
age: number;
id: 1,
amount: 100,
age: 30,
Type Aliases:
'typescript
type Point = {
x: number;
y: number;
type Shape = "circle" | "square" | "triangle";
Generics:
'typescript
function reverse<T>(arr: T[]): T[] {
return arr.reverse();
Introduction:
In TypeScript, modules and namespaces provide
mechanisms for organizing and encapsulating code,
allowing for better modularity, reusability, and
maintainability in larger-scale applications. In this
chapter, we will explore the concepts of modules
and namespaces in TypeScript and how they help in
structuring and managing your codebase.
Modules:
Modules in TypeScript provide a way to encapsulate
code into separate files and define dependencies be
tween them. A module is a self-contained unit that
can export functionalities and import functionali
ties from other modules.
Exporting and Importing:
To export a functionality from a module, you can use
the ' export' keyword before a declaration, such as a
variable, function, class, or interface.
'typescript
// mathUtils.ts
export function add(a: number, b: number): number
return a + b;
11 app.ts
import {add} from "./mathUtils";
Default Export:
In addition to named exports, a module can have a
default export. The default export is the primary ex
port of a module and is usually used to export a sin
gle value or functionality.
'typescript
// mathUtils.ts
export default function add(a: number, b: number):
number {
return a + b;
// app.ts
import add from "./mathUtils";
Namespace:
Namespaces, also known as internal modules, pro
vide a way to organize related code into a named
scope. Namespaces can contain variables, functions,
classes, and interfaces.
'typescript
namespace Geometry {
export function calculateCircumference(radius:
number): number {
return 2 * Math.PI * radius;
console.log(Geometry.calculateCircumfer-
ence(5)); // Output: 31.41592653589793
console.log(Geometry.calculateArea(5)); 11 Output:
78.53981633974483
Module Resolution:
Module resolution is the process of locating and
loading modules in a Typescript application. Type-
Script supports multiple module resolution strate
gies, such as Node.js, Classic, or Module Aggregation.
\ \ \•
json
"compileroptions": {
"moduleResolution": "node"
Conclusion:
Typescript modules and namespaces provide pow
erful mechanisms for organizing and structuring
code in larger-scale applications. Modules allow you
to encapsulate code into separate files and define
dependencies between them, enabling better code
reuse and maintainability. Namespaces provide a
way to logically group related code within a named
scope. Understanding modules and namespaces in
Typescript is essential for building modular and
maintainable applications.
Chapter 6: Advanced
TypeScript Tools and
Techniques
Introduction:
In this chapter, we will explore advanced tools and
techniques that can enhance your TypeScript de
velopment experience. We will cover topics such as
type inference, type guards, module resolution, dec
orators, and code generation.
Type Inference:
Typescript's type inference system automatically
infers the types of variables when they are declared
and assigned a value. It analyzes the context and
usage of variables to determine their types. Type in
ference eliminates the need for explicit type annota
tions in many cases, making code more concise and
readable.
'typescript
let name = "John"; // Type inference assigns type
string
let age = 25; // Type inference assigns type number
let isStudent = true; // Type inference assigns type
boolean
\ \ \
Type Guards:
Type guards allow us to narrow down the type of a
value within a conditional block. They provide a way
to perform runtime checks on the type of a value.
Type guards can be created using 'typeof', 'in-
stanceof', or custom type predicates.
'typescript
function processValue(value: string I number): void {
if (typeof value = = = "string") {
console.log(value.toUpperCase());
} else if (typeof value = = = "number") {
console.log(value.toFixed(2));
Module Resolution:
Module resolution is the process by which Type-
Script resolves and locates module dependencies.
Typescript supports multiple module resolution
strategies, such as Node.js-style resolution and ES
modules. It allows us to import and use code from
external modules in a structured and organized
manner.
'typescript
import { greet} from "./greetings"; // Relative path
import
import {sum} from "math-lib"; // Package import
Decorators:
Decorators are a powerful feature in Typescript that
allow us to add metadata and modify the behav
ior of classes, methods, or properties at design time.
They are denoted by the ' @' symbol followed by
a decorator function. Decorators provide a way to
implement cross-cutting concerns, such as logging,
authentication, and validation, in a modular and re
usable manner.
'typescript
function log(target: any, propertyKey: string, de
scriptor: PropertyDescriptor): void {
const originalMethod = descriptor.value;
class Calculator {
©log
add(a: number, b: number): number {
return a + b;
const calculator = new CalculatorQ;
const sum = calculator. add( 5, 10); 11 Logs: Calling
method add with arguments: 5,10
// Logs: Method add returned:
15
Code Generation:
Typescript supports code generation through tools
like Babel and Typescript Compiler (tsc). These tools
allow us to transpile Typescript code to JavaScript,
enabling compatibility with different environments
and browsers. Code generation plays a crucial role in
the build and deployment processes of Typescript
projects.
Introduction:
Object-Oriented Programming (OOP) is a popular
programming paradigm that allows developers to
organize code into reusable and modular compo
nents called objects. TypeScript, with its support for
classes, interfaces, and other OOP features, provides
a strong foundation for building robust and scalable
applications. In this chapter, we will explore the key
concepts of OOP and how they are implemented in
TypeScript.
'typescript
class Circle {
radius: number;
constructor(radius: number) {
this.radius = radius;
getArea(): number {
return Math.PI * this.radius ** 2;
getCircumferenceQ: number {
return 2 * Math.PI * this.radius;
Inheritance:
Inheritance is a mechanism in OOP that allows
classes to inherit properties and methods from other
classes. Typescript supports single inheritance,
where a class can inherit from a single parent class.
This promotes code reuse and facilitates the creation
of hierarchical relationships between classes.
'typescript
class Shape {
color: string;
constructor(color: string) {
this.color = color;
getColorQ: string {
return this.color;
getArea(): number {
return this.width * this.height;
Encapsulation:
Encapsulation is the practice of bundling related
properties and methods within a class and control
ling their accessibility. In Typescript, we can use
access modifiers ('public', 'private', and 'pro
tected ') to define the visibility of class members.
This allows us to enforce encapsulation and restrict
direct access to sensitive data or implementation de
tails.
'typescript
class BankAccount {
private balance: number;
constructor(initialBalance: number) {
this.balance = initialBalance;
getBalanceQ: number {
return this.balance;
'typescript
class Animal {
makeSound(): void {
console.log("Animal makes a sound");
Interfaces:
Interfaces in Typescript define a contract for classes
to follow. They specify the structure and behavior
that a class must adhere to, allowing for code in
teroperability and achieving loose coupling between
components. Interfaces can define properties, meth
ods, and even extend other interfaces.
'typescript
interface Printable {
print(): void;
print(): void {
console.log(this.content);
constructor(amount: number) {
this.amount = amount;
print(): void {
console.log(' Invoice amount: $$ {this.amount}
const document = new Document("Sample docu
ment");
const invoice = new Invoice(lOOO);
Introduction:
Generics in TypeScript provide a powerful tool for
creating reusable and type-safe code components.
They allow you to define functions, classes, and in
terfaces that can work with different types, provid
ing flexibility and enhancing code reusability. In this
chapter, we will explore the concept of generics and
how they are used in TypeScript.
'typescript
function toArray<T>(arg: T): T[] {
return [arg];
Generic Classes:
Generic classes allow you to create classes that can
work with different types. The type parameter can
be used to define properties, method arguments, and
return types within the class.
'typescript
class Box<T> {
private value: T;
constructor value: T) {
this.value = value;
getValue(): T {
return this.value;
'typescript
interface Lengthable {
length: number;
Benefits of Generics:
Using generics in Typescript provides several bene
fits:
Conclusion:
Generics in Typescript offer a powerful mechanism
for creating reusable and type-safe code compo
nents. By using generic type parameters, you can
build functions, classes, and interfaces that work
with a variety of types, enhancing code reusability,
type safety, and flexibility. Generics are particularly
useful in scenarios where you want to create compo
nents that can handle different types of data with
out sacrificing type correctness.
Chapter 9: Decorators and
Metadata in TypeScript
Introduction:
Decorators and metadata are advanced features in
TypeScript that allow you to add additional infor
mation and modify the behavior of classes, meth
ods, and properties at runtime. Decorators provide a
way to annotate and modify the structure of a class
or its members, while metadata allows you to attach
and retrieve additional data associated with these
entities. In this chapter, we will explore the concepts
of decorators and metadata and how they can be
used in TypeScript.
Decorators:
Decorators are a special kind of declaration that can
be attached to classes, methods, properties, or pa-
rameters. They are prefixed with the ' @' symbol
and can be used to modify or enhance the behavior
of the target entity. Decorators are executed at run
time and can be used to add functionality, modify
behavior, or provide additional metadata.
Creating a Decorator:
To create a decorator, you define a function that
takes the target entity as its parameter. The decora
tor function can then perform actions or modify the
target entity by returning a new value or modifying
its properties.
'typescript
function log(target: any) {
console.log("Decorating class:", target);
©log
class MyClass {
// Class implementation
'typescript
class MyClass {
©log
myMethod() {
// Method implementation
©readonly
myProperty: string = "Hello, Typescript!";
Decorating Parameters:
Decorators can also be applied to parameters of a
method or constructor. This allows you to add ad
ditional behavior or validation to the parameters
passed to a function.
'typescript
class MyClass {
myMethod(@validate input: string) {
// Method implementation
Metadata:
Metadata provides a way to attach additional data
to classes, methods, properties, or parameters. This
metadata can be retrieved at runtime and used for
various purposes, such as reflection, dependency in
jection, or runtime analysis.
Attaching Metadata:
To attach metadata to an entity, you can use the ' Re-
flect.metadata' function provided by Typescript.
The ' Reflect.metadata' function takes two parame
ters: a metadata key and a metadata value.
'typescript
class MyClass {
@Reflect.metadata("custom:tag", "Some meta
data")
myMethodO {
// Method implementation
In the above example, the ' Reflect.metadata' func
tion is used to attach metadata to the ' myMethod'
method. The metadata key is ' "custom:tag"', and
the metadata value is '"Some metadata"'. This
metadata can be retrieved at runtime using reflec
tion techniques.
Retrieving Metadata:
To retrieve metadata at runtime, you can use the
' Reflect.getMetadata' function provided by Type-
Script. The ' Reflect.getMetadata' function takes a
metadata key and the target entity as its parameters.
'typescript
class MyClass {
@Reflect.metadata("custom:tag", "Some meta
data")
myMethod() {
// Method implementation
Conclusion:
Decorators and metadata provide powerful features
in Typescript, allowing you to modify the behavior
of classes, methods, properties, or parameters and
attach additional data at runtime. Decorators en
able you to add functionality, modify behavior, and
separate cross-cutting concerns. Metadata provides
a way to attach and retrieve additional information
about entities at runtime. By leveraging decorators
and metadata, you can enhance the modularity, ex
tensibility, and flexibility of your Typescript appli
cations.
Chapter 10: Asynchronous
Programming with
TypeScript
Introduction:
Asynchronous programming is a crucial aspect of
modern software development, especially in scenar
ios where you need to handle time-consuming oper
ations such as fetching data from a server, reading
from a file, or making network requests. TypeScript
provides powerful tools and language features to
handle asynchronous operations in a structured and
efficient manner. In this chapter, we will explore the
concepts and techniques of asynchronous program
ming in TypeScript.
Callbacks:
One of the traditional approaches to asynchronous
programming in JavaScript and Typescript is the use
of callbacks. A callback is a function that is passed as
an argument to another function and gets invoked
once the asynchronous operation completes.
'typescript
function fetchData(callback: (data: any) = > void) {
// Simulating an asynchronous operation
setTimeout(() = > {
const data = "Some data";
callback(data);
}, 1000);
11 Usage
fetchData((data) = > {
console.log(data);
});
In the above example, the ' fetchData' function ac
cepts a callback function as an argument. After a
simulated asynchronous delay of 1 second, it in
vokes the callback function with the fetched data.
This approach allows you to handle the result of the
asynchronous operation once it's available.
Promises:
Promises provide a more structured and intuitive
way to handle asynchronous operations. A promise
represents the eventual completion or failure of an
asynchronous operation and allows you to attach
callbacks to handle the success or error cases.
'typescript
functionfetchDataQ: Promise<any> {
return new Promise((resolve, reject) => {
// Simulating an asynchronous operation
setTimeout(() = > {
const data = "Some data";
resolve(data);
}, 1000);
1);
// Usage
fetchData()
.then((data) = > {
console.log(data);
})
,catch((error) = > {
console.error(error);
});
Async/Await:
Async/await is a modern and more concise approach
to handle asynchronous operations introduced in
ECMAScript 2017 (ES8) and supported in Type-
Script. It allows you to write asynchronous code in
a synchronous-looking manner, making it easier to
understand and maintain.
'typescript
async function fetchDataQ: Promise<any> {
return new Promise((resolve, reject) => {
// Simulating an asynchronous operation
setTimeout(() = > {
const data = "Some data";
resolve(data);
}, 1000);
1);
// Usage
async function getDataQ {
try{
const data = await fetchData();
console.log(data);
} catch (error) {
console.error(error);
getDataQ;
Conclusion:
Asynchronous programming is a fundamental as
pect of modern software development, and Type-
Script provides powerful tools and language fea
tures to handle asynchronous operations effec
tively. Whether you choose callbacks, promises, or
async/await syntax, understanding and leveraging
asynchronous techniques is essential for build
ing responsive, scalable, and efficient applications.
By embracing asynchronous programming, you can
improve performance, enhance the user experience,
and write more maintainable code in your Type-
Script projects.
Chapter 11: Error Handling
and Asynchronous
Programming in TypeScript
Introduction:
Error Handling:
In TypeScript, error handling is typically done using
try-catch blocks. The try block contains the code that
might throw an error, and the catch block handles
the error if one occurs. We can also use the optional
finally block to execute code that should always run,
regardless of whether an error occurred or not.
'typescript
try{
} catch (error) {
} finally {
Callbacks:
setTimeout(() = > {
callback(data);
}, 2000);
'typescript
setTimeout(() = > {
resolve(data);
}, 2000);
});
fetchData()
1)
,catch((error) = > {
});
Async/Await:
Async/await is a modern approach to asynchronous
programming that makes code more readable and
easier to reason about. The 'async' keyword is
used to define an asynchronous function, and the
' await' keyword is used to pause the execution of a
function until a promise is resolved or rejected.
'typescript
setTimeout(() = > {
resolve(data);
}, 2000);
async function fetchDataAndProcess():
Promise < void > {
try{
} catch (error) {
fetchDataAndProcessQ;
Introduction:
Unit Testing:
Unit testing is a widely adopted practice in soft
ware development that involves testing individual
units or components of code to ensure they func
tion as expected. TypeScript supports various test
ing frameworks like Jest, Mocha, and Jasmine. These
frameworks provide powerful tools for writing and
executing tests.
'typescript
expect(sum(2, 3)).toBe(5);
});
expect(sum(-5, -10)).toBe(-15);
Debugging Tools:
Typescript integrates seamlessly with modern de
bugging tools, enhancing the development experi
ence. Debuggers like VS Code and Chrome Dev-
Tools provide features such as breakpoints, stepping
through code, inspecting variables, and evaluating
expressions. These tools enable you to track down
and resolve issues in your Typescript projects effi
ciently.
Debugging Strategies:
When encountering bugs in your Typescript code,
it's essential to follow effective debugging strategies
to identify and fix the problem efficiently. Here are
some strategies to consider:
1. Reproduce the Issue: Try to reproduce the bug
consistently by identifying the steps or inputs that
trigger it. This helps in isolating the problem and un
derstanding its scope.
Introduction:
Configuring tsconfig.json:
"compileroptions": {
"target": "es6",
"module": "commonjs",
"outDir": "dist",
"strict": true
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
Type Declarations:
JavaScript libraries and frameworks may not have
type information available natively. However, Type-
Script provides a way to include type declarations
for JavaScript code using declaration files (' .d.ts'
files).
Declaration files provide type information for exist
ing JavaScript libraries, allowing you to benefit from
Typescript's static typing and tooling features.
'bash
'typescript
$('#myElement').addClass('highlight');
Gradual Conversion:
Integrating Typescript with JavaScript doesn't mean
you have to convert your entire codebase to Type-
Script at once. Typescript supports gradual conver
sion, allowing you to introduce Typescript gradu
ally by converting individual files or sections of your
codebase.
Conclusion:
Introduction:
1. Install Typescript:
'bash
\ \•
json
"compileroptions": {
"target": "es6",
"module": "commonjs",
"outDir": "dist"
"include": ["src/*’7*.ts"]
The ' tsconfig.json' file above specifies the target
ECMAScript version, the module system, and the
output directory for the transpiled JavaScript files. It
also specifies which files to include in the compila
tion process.
'bash
tsc
\\\
Conclusion:
A BEGINNER’S GUIDE
TO PROGRAMMING
MARK STOKES
JAVASCRIPT CODING
MADE SIMPLE
Chapter 1: Introduction
to JavaScript
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
'javascript
console.log("Hello, World!");
X\\
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var outputElement = document.getElement-
Byld("output");
outputElement.textContent = "Hello,
JavaScript!";
</script >
</body>
</html>
In this example, we select the ' <hl > ' element with
the ' id' attribute of "output" and update its con
tent using the 'textcontent' property. When the
page loads, the JavaScript code will execute, and the
text "Hello, JavaScript!" will replace the initial "Hello,
World!" text within the ' <hl > ' element.
1.7 Variables and Data Types
'javascript
'javascript
'javascript
/*
'javascript
var x = 5;
var y = 2;
var sum = x + y; // 7
var difference = x - y; // 3
var product = x * y; // 10
var remainder = x % y; // 1
x++;//xis now 6
y-; // y is now 1
2.2.2 Assignment Operators
'javascript
var x = 5;
var y = 2;
x + = y; // Equivalent to x = x + y; (x is now 7)
- ' > ': Checks if the value on the left is greater than
the value on the right.
- ' < ': Checks if the value on the left is less than the
value on the right.
- ' > = ': Checks if the value on the left is greater than
or equal to the value on the right.
- ' < = ': Checks if the value on the left is less than or
equal to the value on the right.
'javascript
var x = 5;
var y = 2;
'javascript
var x = 5;
var y = 2;
var result = (x + y) * 3;
console.log(result); // 21
In this example, the expression ' (x + y) * 3' per
forms addition and multiplication to produce the re
sult 21.
'javascript
'javascript
var x = 5;
var y = 10;
console.log(result); // true
In this example, the logical expression '(x > 3) &&
(y < 15)' evaluates whether both conditions are true
and returns 'true'.
2.4 Conclusion
'javascript
if (condition) {
if (condition) {
} else {
'javascript
'javascript
switch (expression) {
case value 1:
break;
case value 2:
break;
default:
break;
Let's see an example:
'javascript
switch (day) {
case "Monday":
break;
case "Tuesday":
break;
default:
console.logf'It's an unknown
day.");
break;
'javascript
console.log(i);
'javascript
while (condition) {
'javascript
vari = 1;
while (i <= 5) {
console.log(i);
i++;
In this example, the loop will iterate five times, simi
lar to the previous ' for' loop example.
'javascript
do {
} while (condition);
vari = 1;
do {
console.log(i);
i++;
3.3 Conclusion
'javascript
// code to be executed
function square(number) {
return result;
'javascript
var number = 5;
console.log(squaredNumber); // Output: 25
\\\
'javascript
function square(number) {
return result;
var number = 5;
console.log(squaredNumber); // Output: 25
X\\
function square(number) {
var number = 5;
console.log(squaredNumber); // Output: 25
'javascript
function myFunction() {
'javascript
console.log("Hello," + name +
'javascript
console.log(double(5)); //Output: 10
In this example, we define an arrow function called
' double' that takes a ' number' parameter and re
turns the doubled value of that number. The arrow
function syntax ' (number) = > number * 2' repre
sents a compact way of writing the function.
4.9 Conclusion
'javascript
'javascript
'javascript
'javascript
fruits[l] = 'grape';
'javascript
console.log(fruits.length); // Output: 3
'javascript
fruits.push('grape');
console.log(fruits); // Output: ['apple', 'banana',
'orange', 'grape']
'javascript
fruits. shift();
fruits.unshiftfgrape', 'kiwi');
'javascript
5.6.4 'concat()'
'javascript
5.7 Conclusion
'javascript
var person = {
age: 30,
'javascript
car.make = "Toyota";
car.model = "Camry";
car.year = 2022;
In this example, we create an object called 'car'
using the ' Object()' constructor and assign proper
ties to it using dot notation.
'javascript
'javascript
console.log(person['age']); // Output: 30
'javascript
person.age = 35;
carf'year'] = 2023;
'javascript
person.gender = "Male";
delete car.model;
'javascript
var calculator = {
return a + b;
console.log(calculator.subtract(10,4)); // Output: 6
\\\
'javascript
6.9 Conclusion
'javascript
button.onclick = functionQ {
alert("Button clicked!");
In this example, we select an HTML button element
with the id "myButton" using ' document.getEle-
mentByldQ'. We then assign an anonymous func
tion to the ' onclick' event handler of the button.
When the button is clicked, the function is executed,
and an alert message saying "Button clicked!" is dis
played.
'javascript
alert("Button clicked!");
});
button.addEventListener("click", function(event) {
});
X \ \
7.7 Conclusion
'javascript
xhr.open("GET", "https://api.example.com/data",
true);
xhr.onreadystatechange = functionQ {
xhr.sendQ;
'javascript
fetch("https://api.example.com/data")
.then(function(response) {
if (response.ok) {
return response.jsonQ;
} else {
1)
.then(function(data) {
console.log(data);
1)
.catch(function(error) {
console .log(error);
});
In this example, we use the 'fetchQ' function
to send a GET request to the specified URL. The
' fetchQ' function returns a Promise that resolves to
the response from the server.
'javascript
fetch("https://api.example.com/data")
.then(function(response) {
if (response.ok) {
return response.jsonQ;
} else {
1)
.then(function(data) {
console.log(data);
1)
.catch(function(error) {
8.7 Conclusion
With AJAX and the Fetch API, you can create dy
namic and interactive web applications that retrieve
data from servers in the background, providing a
seamless user experience. In the next chapter, we
will delve into JavaScript's advanced concepts, in
cluding Promises, async/await, and error handling
techniques. Get ready to take your JavaScript skills to
the next level!
Chapter 9: Advanced
JavaScript Concepts
9.1 Promises
Promises are a powerful tool in JavaScript for
handling asynchronous operations. They provide a
cleaner and more intuitive way to manage asynchro
nous code compared to callbacks. A Promise repre
sents the eventual completion or failure of an asyn
chronous operation and allows us to chain multiple
asynchronous operations together.
'javascript
// Asynchronous operation
});
myPromise
.then((value) = > {
});
'javascript
try{
const response = await fetch('https://api.exam-
ple.com/data');
console.log(data);
} catch (error) {
console .log(error);
fetchData();
'javascript
fetch('https://api.example.com/data')
.then((response) = > {
if (iresponse.ok) {
return response.jsonQ;
})
.then((data) = > {
console.log(data);
In the previous example, we demonstrate error han
dling within a Promise chain using the ' catchQ'
method. After making the 'fetch()' request, we
check if the response is not okay (' iresponse.ok'). If
it's not, we throw a new ' Error' object with a cus
tom error message that includes the response status.
'javascript
function divide(a, b) {
if (b === 0) {
throw new Error('Division by zero is not al
lowed');
return a / b;
try{
console.log('Result:', result);
} catch (error) {
9.4 Generators
'javascript
function* countUpTo(n) {
yield i;
console.log(generator.next().value); 11 Output: 1
console.log(generator.next().value); 11 Output: 2
console.log(generator.next().value); 11 Output: 3
console.log(generator.next().value); 11 Output: 4
console.log(generator.next().value); 11 Output: 5
\\\
9.5 Conclusion
'javascript
// module.js
return number * 2;
'javascript
// main.js
console.log(double(5)); // Output: 10
In this example, we import the ' PI' constant and
the 'doubleO' function from the 'module.js' mod
ule. We can then use these imported entities in our
' main.js' module.
'javascript
const person = {
name: 'John',
age: 30,
greetQ {
'javascript
this.name = name;
this.age = age;
Person.prototype.greet = functionQ {
}/
'javascript
const personPrototype = {
greet() {
person.name = John';
person.age = 30;
'javascript
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
greetQ {
console.log(' Hello, my name is ${this.name} and
I'm ${this.age} years old.');
super(name, age);
this.grade = grade;
study() {
Here's an example:
'javascript
class Shape {
constructor) {
this.name = 'Shape';
draw() {
console.log('Drawing a shape.');
constructor) {
super();
this.name = 'Circle';
draw() {
console.log('Drawing a circle.');
class Square extends Shape {
constructor) {
super();
this.name = 'Square';
draw() {
console.log('Drawing a square.');
11.5 Conclusion
Object-oriented programming in JavaScript provides
a powerful way to structure and organize our code
by utilizing objects, encapsulation, inheritance, and
polymorphism. By understanding the principles and
techniques of OOP, we can create more modular, re
usable, and maintainable JavaScript applications.
Here's an example:
'javascript
try{
console.log(result);
} catch (error) {
'javascript
function divide(a, b) {
if (b === 0) {
try{
console.log(result);
} catch (error) {
'javascript
try{
} catch (error) {
fetchDataQ;
In this example, we define an 'async' function
' fetchData' that makes an asynchronous network
request using the ' fetch' API. We use ' await' to
wait for the response and the parsed data. If an
error occurs during the request or parsing, it will be
caught in the ' catch' block.
12.6 Conclusion
fetch('https://api.example.com/data')
.then(data = > {
console.log(data);
1)
,catch(error = > {
});
'javascript
const userData = {
email: 'john@example.com',
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
}/
body: JSON.stringify(userData),
})
.then(data = > {
console.log(data);
})
,catch(error = > {
'javascript
fetch('https://api.example.com/data', {
headers: {
}/
})
.then(data = > {
console.log(data);
1)
,catch(error = > {
'javascript
fetch('https://api.example.com/data')
.then(response = > {
if (response.ok) {
return response.json();
} else {
1)
.then(data = > {
console.log(data);
,catch(error = > {
});
13.8 Conclusion
14.2 React.js
14.3 Angular
14.4 Vue.js
14.5 jQuery
14.8 Conclusion
15.3 Flutter
15.5 NativeScript
15.6 Capacitor
Capacitor is a JavaScript-based runtime and bridge
that allows developers to build mobile apps using
web technologies like HTML, CSS, and JavaScript. It
enables developers to create apps that run natively
on iOS, Android, and the web.
Capacitor provides a consistent API across plat
forms, making it easy to access native features and
plugins. It also offers tools for app packaging, de
ployment, and app store distribution.