Conquering JavaScript: The Practical Handbook 9781032411675, 9781032411668, 9781003356578

Conquering JavaScript: The Practical Handbook helps the reader master the JavaScript (JS) programming language for faste

789 114 8MB

English Pages 563 Year 2023

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

Conquering JavaScript: The Practical Handbook
 9781032411675, 9781032411668, 9781003356578

Table of contents :
Cover
Half Title
Series Page
Title Page
Copyright Page
Dedication
Table of Contents
About the Editor
Acknowledgments
Zeba Academy – Conquering JavaScript
Chapter 1 Introduction to JavaScript
In this Chapter
Client-Side Javascript
What is the Purpose of Javascript?
What Makes Javascript so Special?
What are Javascript's Flaws?
How Does JavaScript Work on Our Website?
What Makes Javascript Unique Among Programming Languages?
Tools for Javascript Development
What is the Current State of JavaScript?
Javascript's Evolution
What is Modern JavaScript and How Can it Be Used?
What JavaScript Can do for Us
What Distinguishes JavaScript?
JavaScript Tendencies
Standardizing JavaScript
ECMAScript Version History
JavaScript vs. Java
Who Controls Javascript?
Oracle's Trademark is JavaScript
Various Variations
Javascript Framework
The jQuery and JavaScript Libraries
What Distinguishes JavaScript Frameworks From Libraries?
Frontend Frameworks
React
Angular
Vue
Backend Frameworks
Express
Next.JS
What are the Benefits and Drawbacks of Javascript Frameworks?
Library vs. Framework
Model View Controller (MVC)
Vanilla JS vs. React JS: Which Should We Use for Our Development?
Vanilla JS vs React JS Functionality
React JS: What is its Role in the Application's View Layer?
Why is Vanilla JS Used?
Stack Data Structure Comparison between React JS vs Vanilla JS
Performance Comparison between Vanilla JS with React JS
Future Prospects
Testing
Security
ReactJs and Vanilla js UI/UX Performance
Convenience for the Developer
Maintenance
Development Cost
5 Reasons Why Our Website Needs Javascript
Explain How Using JavaScript Will Enhance Our Website
AJAX Uses to Load Sections of Pages Independently
Notes
Chapter 2 Getting Started with JavaScript I
In this Chapter
Selecting the Best Javascript Editor From Seven Options
What is the Difference between a JavaScript Editor and an IDE?
What Exactly is an Editor?
IDE Definition
When Conflicts Arise
The Top 7 JavaScript Editors
Time to Select the Best JavaScript Editor
With a JavaScript Editor, You May Improve the Efficiency of Your Work Environment
How to Install Javascript in Visual Studio Code
Installation of Visual Studio Code in Windows
Setup Visual Studio Code
Installing Visual Studio Code on Linux
Installing Visual Studio Code on Debian, Ubuntu, or Linux Mint
Node.JS Installation on Windows
Configuring the Node Development Environment
Node Installation on Windows (Windows 10):
Node.JS Installation on Linux
How do we Start and Execute a Node.JS Project in Visual Studio Code?
Top Visual Studio Code Extensions for Javascript Developers
JavaScript (ES6) Code Snippets
ESLint
Prettier
Quokka.js
REST Client
Debugger for Chrome
Live Server
Live Share
Babel JavaScript VSCode
JavaScript Booster
Tabnine
What Exactly is 'Vanilla Javascript'?
Why Should We Learn Pure JS?
Website Performance
User Interface
It also Makes Working with Frameworks Simpler
Vanilla Script's Disadvantages
Hello World Program in Javascript
Syntax of Javascript
Our First Javascript Code
Line Breaks and Whitespace
Semicolons are Not Required
Case Sensitivity
Comment in Javascript
Benefits of JavaScript Comments
JavaScript Comment Types
Single-Line Comment in JavaScript
Multiline Comment in JavaScript
Variable in Javascript
JavaScript Variables that are Correct
JavaScript Variables that are Not Correct
Variable in JavaScript Example
Local Variable in JavaScript
The Global Variable in JavaScript
Declaring a Global Variable in JavaScript within a Function
Internals of Global Variable
Data Types in Javascript
Primitive Data Types in JavaScript
Non-Primitive Data Types in Javascript
Operators in Javascript
Arithmetic Operators
Comparison Operators
Bitwise Operators
Logical Operators
Assignment Operators
Special Operators
If-Else Statements in Javascript
If Statement
If...Else Statement
If...Else if Statement
Switch in Javascript
Loops in Javascript
For Loop
While Loop
Do-While Loop
For-in Loop
Functions in Javascript
The Benefit of the JavaScript Function
Syntax of JavaScript Functions
Function Arguments
Function with Return Value
Function Object
Parameter
Function Methods
Examples of JavaScript Function Objects
Objects in Javascript
Object Creation in JavaScript
Creating a Method in a JavaScript Object
Object Methods in JavaScript
Array in Javascript
Array Methods in JavaScript
String in Javascript
String Methods in JavaScript
Date Object in Javascript
Constructor
Date Methods in JavaScript
Date Example in JavaScript
Example of JavaScript Current Time
Example of a JavaScript Digital Clock
Math in Javascript
Math Methods
Math.sqrt(n)
Math.random()
Math.pow(m, n)
Math.floor(n)
Math.ceil(n)
Math.round(n)
Math.abs(n)
Number Object in Javascript
Number Constants in JavaScript
Number Methods in JavaScript
Javascript Boolean
Boolean Properties
Boolean Methods
Errors and Exceptions in Javascript
What Exactly is Exception Handling?
Errors in Syntax
Runtime Errors
Logical Errors
Statement of Try...Catch...Finally
The Throw Statement
The Onerror() Function
Events in Javascript
What Exactly is an Event?
onclick Event Type
onsubmit Event Type
onmouseover and onmouseout
Standard HTML 5 Events
Notes
Chapter 3 Getting Started with JavaScript II
In this Chapter
How Can we Build an Asynchronous Node.JS Function?
How do we Write an Asynchronous Function in Javascript?
Waiting for Multiple Promises
Synchronous and Asynchronous in JavaScript
Synchronous JavaScript
Asynchronous JavaScript
Explain the Difference between Asynchronous and Deferred JavaScript
Asynchronous
Deferred
Asynchronous vs Deferred
Document Object Model
Document Object Properties
Document Object Methods
Document Object Accessing Field Value
Method Document.Getelementbyid() in Javascript
Getelementsbyclassname()
Method getElementsByClassName() Example
Distinction between the Methods getElementsByClassName(), querySelector(), and querySelectorAll()
Method Document.Getelementsbyname() in Javascript
Method Document.Getelementsbytagname() in Javascript
The Innerhtml in Javascript
InnerHTML Property Example
Example of a Comment Form Using innerHTML
The Innertext in Javascript
Example of JavaScript innerText
5 Methods for Making http Requests in Javascript
XMLHttpRequest
Advantages of XMLHttpRequest
Disadvantages of XMLHttpRequest
Fetch
Advantages of Fetch
Disadvantages of Fetch
Axios
Advantages Axios
Disadvantages Axios
SuperAgent
Advantages of SuperAgent
Disadvantages of SuperAgent
Ky
Advantages of Ky
Disadvantages of Ky
HTTP Cookies
Utilization of Cookies
How Do Cookies Work?
Cookies in JavaScript
Create Cookies
Client Side
Web Server Side
Properties of Cookies
Scope of Cookies
Varieties of Cookie
First-Party Cookies
Third-Party Cookies
Session Cookies
Secure Cookies
Zombie Cookies
Form in Javascript
Overview to Forms
Referencing Forms
Submitting Form
Login Form
SignUp Form
Validation of Javascript Forms
Example of Form Validation in JavaScript
Password Retype Validation in JavaScript
Number Validation in JavaScript
Validation of JavaScript Using an Image
Email Validation in JavaScript
Working with Javascript APIS
The Most Well-Known Javascript Libraries
jQuery
Features
Use Cases
React.js
Features
Use Cases
D3.js
Features
Use Cases
Underscore.js
Features
Use Cases
Lodash
Features
Use Cases
Algolia Places
Features
Use Cases
Anime.js
Features
Use Cases
Animate On Scroll (AOS)
Features
Use Cases
Bideo.js
Features
Use Cases
Chart.js
Features
Use Cases
Cleave.js
Features
Use Cases
Choreographer.js
Features
Use Cases
Glimmer
Features
Use Cases
Granim.js
Features
Use Cases
fullPage.js
Features
Use Cases
Leaflet
Features
Case Studies
Multiple.js
Features
Use Cases
Moment.js
Features
Use Cases
Masonry
Features
Use Cases
Omniscient
Features
Use Cases
Parsley
Features
Use Cases
Popper.js
Features
Use Cases
Three.js
Features
Use Cases
Screenfull.js
Features
Use Cases
Polymer
Features
Use Cases
Voca
Features
Use Cases
Notes
Chapter 4 The Clearer Picture
In this Chapter
A Javascript Framework is What?
What Distinguishes a JavaScript Framework from a JavaScript Library?
Use a JavaScript Framework, But Why?
Libraries and Frameworks for JavaScript
Top 7 Javascript Frontend Frameworks
1. React
How it Operates
Popular React Components
Advantages
Disadvantages
When Should We Utilize React?
2. Vue.js
How it Operates
Real-Life Examples
Popular Vue.js Components
Advantages
Disadvantages
When Should We Utilize Vue.js?
3. Angular
How it Operates
Real-Life Examples
Popular Angular Components
Advantages
Disadvantages
When Should We Utilize Angular?
4. jQuery
How it Operates
Real-Life Examples
Popular jQuery Components
Advantages
Disadvantages
When Should We Utilize jQuery?
5. Svelte
How it Operates
Real-Life Examples
Popular Svelte Components
Advantages
Disadvantages
When Should We Utilize Svelte?
6. Ember
How it Operates
Real-Life Examples
Popular Ember Components
Advantages
Disadvantages
When Should We Utilize Ember?
7. Backbone.js
How it Operates
Real-Life Examples
Advantages
Disadvantages
When Should We Utilize Backbone.js?
How Can We Choose the Ideal JavaScript Framework for Our Next Project?
Team Proficiency
Backward Compatibility
Complexity
Size and Functionality
5 Backend JavaScript Frameworks
The Eight Top Javascript Game Engines
10 Major Javascript Frameworks for Developing Mobile Apps
1. React Native
In What Ways is React Native Superior?
2. NativeScript
Why is NativeScript Used?
3. Ionic
Why is Ionic Used?
4. Apache Cordova
Why Was Cordova Chosen?
5. OnSenUI
Why Use OnSen UI?
6. jQuery Mobile
7. Mobile Angular UI
8. Sencha Touch
9. Titanium
10. Meteor
The Best JS Frameworks for Desktop Applications
Are Cross-Platform Apps Interchangeable with Desktop Programs?
The Advantages and Disadvantages of a Standalone Level vs a Cross-Platform App
Are Desktop Apps Supported by React and NodeJS?
Top Five JS Frameworks for Desktop Applications (Desktop Apps)
1. Electron
2. NodeGUI
3. Proton Native
4. NW.js
5. AppJS
How to Select The Best Javascript Framework for Our Project
Development Speed and Simplicity of Use, as well as Project Support
Trends
Scalability and Mobility
The Frequency of Updates
Which JavaScript Framework Should We Start With?
React.js
Node.js
Java vs. Javascript
Python vs. Javascript
What is JavaScript?
What is Python?
Differences of Most Significance
Features of JavaScript
Features of Python
Comparison between Python vs Java Script
Jquery vs. Javascript
What Exactly is jQuery?
The Distinction between jQuery and JavaScript
Javascript vs. PHP
What Exactly is PHP?
The Distinction between JavaScript and PHP
Dart vs. Javascript
What Exactly is Dart?
Benefits and Drawbacks of Dart
Advantages
Drawbacks
What is JavaScript?
Advantages
Drawbacks
Important Distinction between Dart and JavaScript
Simplicity of Use
Speed
Type Security
Popularity
The Learning Curve
Web vs. Mobile
Frontend vs. Backend
Commercial Usage
Javascript vs. Angular JS
What is JavaScript?
JavaScript Features
What is Angular Js?
Angular JS features
Major Distinctions between JavaScript and Angular JS
Comparative Analysis of JavaScript and Angular JS
Javascript vs. Node.JS
What is JavaScript?
JavaScript's Benefits and Drawbacks are Discussed
Benefits
Drawbacks
What is Node.js?
How Does Node.js Work, and What are its Benefits and Drawbacks?
Benefits
Drawbacks
Comparing JavaScript with Node.js: Key Distinctions
In-Depth Analysis of JavaScript vs. Node JS
Notes
Chapter 5 Frontend Development
In this Chapter
Frontend vs Backend
Frontend Development
Frontend Languages
Frontend Frameworks and Libraries
Backend Development
Backend Languages
Backend Frameworks
Difference between Frontend and Backend Development
ReactJS
What does the 'React' Mean?
The Question is, 'Why React?'
React Features
JSX
Components
Data Binding, One Way Only
Virtual DOM
Simplicity
Performance
Benefits and Drawbacks of ReactJS
Benefits
Drawbacks
Version of React
Setup of the React Environment
ReactJS Installation Methods
1. By Use of the npm Command
Install NPM and NodeJS
Get React and React DOM Installed
Install Webpack
Install Babel
Creation of Files
2. Set React Application Compiler, Loader, and Server
Configure Webpack
HTML Webpack Template for the index.html File
App.jsx and main.js
Creation of .babelrc file
Running Server
Create the Bundle
3. Use the Command create-react-app
Install NodeJS and NPM
Installation of React
Develop a New React Project
App.js
Running Server
Comparison Between AngularJS vs ReactJS
AngularJS
Characteristics of AngularJS
ReactJS
Characteristics of ReactJS
AngularJS vs. ReactJS
Comparison Between ReactJS and Svelte
What is Svelte?
When Need One Use Svelte?
Which Companies Utilize Svelte?
What is React?
When Should React to Be Used?
Which Companies Utilize React?
React vs Svelte: Which is Superior?
Performance
Bundle Size
Testing
Community Assistance
Who Succeeds?
React JSX
Why Use JSX?
JSX Nested Elements
App.JSX
Attributes in JSX
Comments in JSX
Styling in JSX
Express.Js
What is Express.Js
Why Employ Express?
How Does Express Appear?
Basic_express.js
Prerequisite
Audience
Problem
Benefits of Express.js
Wsetting Up Express
The Early Stages
Its Evolution
Basics of Node.Js
Types of Primitive
Loose Typing
Object Literal
Functions
Buffer
Process Object
Defaults to Local
Utilize Global Scope
VueJS
What is VueJS?
Features
Comparative Assessment of Other Frameworks
VueJS vs React
VueJS vs Angular
Similarities
Complexity
Performance
Popularity
Dependencies
Flexibility
Reverse Compatibility
Typescript
Environment Setup For VueJS
Directly Use the Tag in an HTML File
By Using the CDN
By Using the NPM
By Using the CLI Command Line
Creating a Project with Webpack
Start the Project, Then the Server
Understanding Vue.JS
Advantages of Using Vue.js
Extremely Small in Size
Simple to Comprehend and Code
Integration with Existing Applications is Simple
Nature is Adaptable
Components
Documentation that is Simple, Thorough, and Detailed
DOM Virtualization
Two-Way Communication
Companies that Use Vue.js
Examine the Vue.js Version We Have Installed
Instances in VueJS
Example Explanation
Template in Vue.JS
Attributes Should Be Added to HTML Elements
Notes
Chapter 6 Backend Development
In this Chapter
What is Backend Development?
Node.JS
What is Node.js, and How Does it Work?
Why Should We Use Node.js?
Fast, Lightweight Applications with Real-Time Communication
Serverless and Microservice Design
The Internet of Things
Processing of Audio/Video
Quick Development
Code Integration with C++
The Downsides of Node.js
Heavy Calculation Activities Cause Performance Constraints
Callback Hell is a Problem
Tooling Immaturity
There is a Growing Need for Skilled Experts
Where Can We Use Node.js?
Where Should We Not Use Node.js?
Setup of the Node.Js Environment
Text Editor
Node.js Runtime
Get the Node.js Archive
Installation on SunOS, Mac OS X, Linux, and Unix
Setup on a Windows Computer
Executing a File Will Verify Installation
First Application of Node.JS
Creation of Node.js Application
MongoDB
What is MongoDB
How does it Work?
MongoDB Data Modeling
What Distinguishes MongoDB from RDBMS?
MongoDB Features Include
MongoDB Has the Following Advantages
MongoDB Disadvantages
Getting Started with MongoDB
Terminology
How to Get Started
Queries
How can Mongodb be Installed on Windows?
Run Mongo Shell
Server-Side JS
Server-Side Website Programming
Engines that Run JavaScript
Runtime Environment
Uses of Server-Side JavaScript
Mern Stack
Acquainting Oneself with MERN Stack Components
1. MongoDB: Cross-Platform Document-Oriented Database
Why Should We Create Mobile and Web Applications with MERN Stack?
Why Employ MongoDB?
2. Express: Backend Framework
Why Use Express?
3. React: Frontend Library
Why Use React?
4. Node.js: JS Runtime Environment
Why Use Node.JS?
What is the MERN Stack's Structural Makeup and How Does it Operate?
Web or Frontend Layer
Server or Middle Tier
Database as Backend Tier
Mern vs Mean
What are MERN Stack Developers' Futures?
Notes
Chapter 7 JavaScript for Mobile Usage
In this Chapter
Why is Javascript Regarded as One of the Finest Programming Languages for Mobile Apps in 2022?
JavaScript's Importance in the Development of Mobile Applications
Extremely Responsive
Frontend Rich Platform
Offline Assistance
Suitable for All Kinds of Developers
JavaScript Frameworks for Mobile Apps
PhoneGap
Ionic
React Native
jQuery
Native Language
Tabris.js
Should We use Javascript when Developing for Mobile?
Key Attributes of JavaScript
Native React
JQuery
PhoneGap
Ionic
Benefits of Using Javascript when Developing Mobile Apps
React Native
Setting Up a React Native Environment
How to Install React Native Environment in Steps
Install Android Studio
Set Up the Android SDK and the Java JDK
Future Significance of React Native in the Development of Mobile Apps
Why is React Native So Popular?
Building React Native Apps
Benefits of React Native App Development
Cons of React Native
Create a Mobile Application Using React Native
The Leading Cross-Platform Framework, React Native
Why Should We Use React Native When Developing Mobile Apps?
Saves Both Money and Time
High Quality
Over-the-Air Updates
The Main Advantage is Open-Source Software
Nativescript
What is NativeScript?
Why NativeScript is Preferred for the Creation of Android Applications
What is NativeScript? What are its Main Advantages and Disadvantages?
Advantages of Native Apps
Limitations with Native Apps
Setups for NativeScript Environment
Prerequisites
Verify Node.js
CLI Setup
Setupcli
Cli
Setting Up the NativeScript Playground Application
Setup for Android and iOS
Top NativeScript Usage Cases
Key Benefits of Developing Android Apps Using NativeScript
Performance of Native Apps
Reusable Program
The Very Low Learning Curve
Substantial Community Support
Comparison between Nativescript and React Native
Performance of NativeScript and React Native
Learning Curves for NativeScript and React Native
Development Community for React Native vs NativeScript
Popularity of NativeScript vs React Native
Which Should We Use between React Native and NativeScript?
Select NativeScript if
Select React Native if
Notes
Chapter 8 JavaScript for Desktop Apps
In this Chapter
How can we Use Desktop Applications?
What is an Electron?
Installation
What is an Electron?
1. WebTorrent Desktop Application
Why is Electron Used by WebTorrent for Desktop?
2. WordPress Desktop Application
Why does the WordPress Desktop App Make Use of Electron?
3. Ghost Electron Application
Why does the Ghost Desktop App Make Use of Electron?
4. The Electron App Beaker Browser
Why is Electron Used by Beaker Browser?
5. Pexels Electron App
Why does the Pexels Desktop App Make Use of Electron?
6. Slack Desktop Application
Why does the Slack Desktop App Make Use of Electron?
7. WhatsApp Electron Application
Why does the WhatsApp Desktop App Make Use of Electron?
Why do so Many Businesses Choose Electron to Create Cross-Platform Desktop Apps?
What is the Significance of This?
Benefits of Electron
Single Codebase
Quick Feature Delivery
Framework Maturity
Electron Has Several Unresolved Concerns
Alternatives for Electron
Drawbacks of Electron.JS Framework
Excessive Volume
Electron.js Framework Consumes a Lot of Resources
Specific Customer Needs
Significance of Using the Electron.JS Framework
Distinction Between the Main and Renderer Processes
Hello Everyone Code in Electron
How does this App Function?
Building UIs with Electron
Notes
Chapter 9 Appraisal
What Exactly is Javascript?
Javascript's Past and its Future
What Makes Javascript Unique?
Languages that are "Superior" To JavaScript
In Comparison to Other Languages, JavaScript
JavaScript Contrasted with C
The Contrast between Java and JavaScript
When Compared to C#, JavaScript is
JavaScript Compared to the Programming Language Python
When Compared to PHP, JavaScript is
JavaScript Compared to the Programming Language Ruby
Opportunities for Professional Development in JavaScript
Frontend Web Developer
Designer and Developer of Web Applications
Developer Skilled in JavaScript
UX/UI Designer
DevOps Engineer
Developer Who Works on All Layers
What is the Most Appropriate Framework for JavaScript?
Vanilla js
Why do we Believe that Frameworks Written in JavaScript are so Awesome?
Appendix I: Javascript Cheat Sheet
Appendix II: Brief Guide to Typescript
Appendix III: Handy Javascript Tools
Index

Citation preview

Conquering JavaScript Conquering JavaScript: The Practical Handbook helps the reader master the

JavaScript (JS) programming language for faster and more robust development. JS is a highly popular language and is often termed as the ‘language of the web.’ In addition to the internet, JS is also being used actively in game development, mobile apps, progressive applications, and now even desktop apps. As such, it is safe to say that JS is probably the most crossplatform language currently in use, and it rises in popularity with each passing day. This book covers the basics and moves on to advanced concepts using a hands-on approach with practical lessons and tutorials. JS programming, JS frameworks and various use-case scenarios are discussed in detail. Bridging the gap between beginner and intermediate-level JS literature, this book is a valuable resource to build robust knowledge.

About the Series The Conquering JavaScript series covers a wide range of topics, pertaining specifically to the JavaScript programming ecosystem, such as frameworks and libraries. Each book of this series is focused on a singular topic, and covers said topic at length, focusing especially on real-world usage and a code-oriented approach, adhering to an industry-standard coding paradigm, so as to help the learners gain practical expertise that can be useful for real-world projects. Some of the key aspects of books in this series are: • Crystal-clear text, spanning various JavaScript-related topics sorted by relevance. • Special focus on practical exercises with numerous code samples and programs. • A guided approach to JS coding with step-by-step tutorials and walkthroughs. • Keen emphasis on the real-world utility of skills, thereby cutting the redundant and seldom-used concepts and bloatware. • A wide range of references and resources to help the readers gain the most out of the books. The Conquering JavaScript series of books assume a basic understanding of coding fundamentals. The Conquering JavaScript series is edited by Sufyan bin Uzayr, a writer and educator having over a decade of experience in the computing field. Sufyan holds multiple degrees, and has taught at universities and institutions worldwide. Having authored and edited over 50 books thusfar, Sufyan brings a wide array of experience to the series. Learn more about his works at sufyanism.com. https://w w w.routledge.com/Conquering-JavaScript/book-series/ CRCCONJAV

Conquering JavaScript The Practical Handbook

Edited by

Sufyan bin Uzayr

First edition published 2024 by CRC Press 6000 Broken Sound Parkway NW, Suite 300, Boca Raton, FL 33487-2742 and by CRC Press 4 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN CRC Press is an imprint of Taylor & Francis Group, LLC © 2024 Sufyan bin Uzayr Reasonable efforts have been made to publish reliable data and information, but the author and publisher cannot assume responsibility for the validity of all materials or the consequences of their use. The authors and publishers have attempted to trace the copyright holders of all material reproduced in this publication and apologize to copyright holders if permission to publish in this form has not been obtained. If any copyright material has not been acknowledged please write and let us know so we may rectify in any future reprint. Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopying, microfilming, and recording, or in any information storage or retrieval system, without written permission from the publishers. For permission to photocopy or use material electronically from this work, access www. copyright.com or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923, 978-750-8400. For works that are not available on CCC please contact [email protected] Trademark notice: Product or corporate names may be trademarks or registered trademarks and are used only for identification and explanation without intent to infringe. ISBN: 9781032411675 (hbk) ISBN: 9781032411668 (pbk) ISBN: 9781003356578 (ebk) DOI: 10.1201/9781003356578 Typeset in Minion by codeMantra

For Dad

Contents About the Editor, xxxv Acknowledgments, xxxvii Zeba Academy – Conquering JavaScript, xxxix Chapter 1   ◾   Introduction to JavaScript

1

IN THIS CHAPTER

1

CLIENT-SIDE JAVASCRIPT

3

WHAT IS THE PURPOSE OF JAVASCRIPT?

3

WHAT MAKES JAVASCRIPT SO SPECIAL?

6

WHAT ARE JAVASCRIPT’S FLAWS?

6

How Does JavaScript Work on Our Website?

7

WHAT MAKES JAVASCRIPT UNIQUE AMONG PROGRAMMING LANGUAGES?

7

TOOLS FOR JAVASCRIPT DEVELOPMENT

8

What Is the Current State of JavaScript?

9

JAVASCRIPT’S EVOLUTION What Is Modern JavaScript and How Can It Be Used?

9 9

What JavaScript Can Do for Us

10

What Distinguishes JavaScript?

11

JavaScript Tendencies

11

Standardizing JavaScript

12

ECMAScript Version History

13

JavaScript vs. Java

14 vii

viii   ◾    Contents

WHO CONTROLS JAVASCRIPT?

14

Oracle’s Trademark Is JavaScript

15

Various Variations

15

JAVASCRIPT FRAMEWORK

15

The jQuery and JavaScript Libraries

16

What Distinguishes JavaScript Frameworks from Libraries?

16

Frontend Frameworks

17

REACT 17 ANGULAR 17 VUE 17 Backend Frameworks

17

EXPRESS 17 NEXT.JS 18 WHAT ARE THE BENEFITS AND DRAWBACKS OF JAVASCRIPT FRAMEWORKS?

18

Library vs. Framework

26

Model View Controller (MVC)

26

VANILLA JS VS. REACT JS: WHICH SHOULD WE USE FOR OUR DEVELOPMENT?

27

Vanilla JS vs React JS Functionality

27

React JS: What Is Its Role in the Application’s View Layer?

27

Why Is Vanilla JS Used?

28

Stack Data Structure Comparison between React JS vs Vanilla JS

28

Performance Comparison between Vanilla JS with React JS

28

Future Prospects

29

Testing 30 Security 30 ReactJs and Vanilla js UI/UX Performance

31

Convenience for the Developer

31

Maintenance 32 Development Cost

32

Contents   ◾    ix

5 REASONS WHY OUR WEBSITE NEEDS JAVASCRIPT

33

Explain How Using JavaScript Will Enhance Our Website

33

AJAX Uses to Load Sections of Pages Independently

34

NOTES 35

Chapter 2   ◾   Getting Started with JavaScript I IN THIS CHAPTER

37 37

SELECTING THE BEST JAVASCRIPT EDITOR FROM SEVEN OPTIONS 37 What Is the Difference between a JavaScript Editor and an IDE?

38

What Exactly Is an Editor? 38 IDE Definition 38 When Conflicts Arise 39 The Top 7 JavaScript Editors 39 Time to Select the Best JavaScript Editor 45 With a JavaScript Editor, You May Improve the Efficiency of Your Work Environment 46 HOW TO INSTALL JAVASCRIPT IN VISUAL STUDIO CODE

46

Installation of Visual Studio Code in Windows

47

Setup Visual Studio Code

51

INSTALLING VISUAL STUDIO CODE ON LINUX

54

Installing Visual Studio Code on Debian, Ubuntu, or Linux Mint 54 NODE.JS INSTALLATION ON WINDOWS Configuring the Node Development Environment

55 55

Node Installation on Windows (WINDOWS 10): 55 NODE.JS INSTALLATION ON LINUX

61

HOW DO WE START AND EXECUTE A NODE.JS PROJECT IN VISUAL STUDIO CODE?

62

TOP VISUAL STUDIO CODE EXTENSIONS FOR JAVASCRIPT DEVELOPERS

64

JavaScript (ES6) Code Snippets

64

x   ◾    Contents

ESLint 65 Prettier 65 Quokka.js 66 REST Client

67

Debugger for Chrome

67

Live Server

68

Live Share

68

Babel JavaScript VSCode

69

JavaScript Booster

69

Tabnine 70 WHAT EXACTLY IS ‘VANILLA JAVASCRIPT’? Why Should We Learn Pure JS?

71 72

Website Performance 72 User Interface 72 It also Makes Working with Frameworks Simpler 72 Vanilla Script’s Disadvantages

73

HELLO WORLD PROGRAM IN JAVASCRIPT

74

SYNTAX OF JAVASCRIPT

74

OUR FIRST JAVASCRIPT CODE

75

Line Breaks and Whitespace

76

Semicolons Are Not Required

76

Case Sensitivity

77

COMMENT IN JAVASCRIPT

77

Benefits of JavaScript Comments

77

JavaScript Comment Types

77

Single-Line Comment in JavaScript 77 Multiline Comment in JavaScript VARIABLE IN JAVASCRIPT

78 78

JavaScript Variables That Are Correct

79

JavaScript Variables That Are Not Correct

79

Variable in JavaScript Example

79

Local Variable in JavaScript

79

Contents   ◾    xi

The Global Variable in JavaScript

80

Declaring a Global Variable in JavaScript within a Function

80

Internals of Global Variable

80

DATA TYPES IN JAVASCRIPT

81

Primitive Data Types in JavaScript

81

NON-PRIMITIVE DATA TYPES IN JAVASCRIPT

81

OPERATORS IN JAVASCRIPT

82

Arithmetic Operators

82

Comparison Operators

82

Bitwise Operators

83

Logical Operators

83

Assignment Operators

83

Special Operators

84

IF-ELSE STATEMENTS IN JAVASCRIPT

84

If Statement

84

If...else Statement

85

If...else if Statement

86

SWITCH IN JAVASCRIPT

88

LOOPS IN JAVASCRIPT

89

for loop

90

while loop

90

do-while loop

91

for-in loop

91

FUNCTIONS IN JAVASCRIPT

92

The Benefit of the JavaScript Function

92

Syntax of JavaScript Functions

93

Function Arguments

93

Function with Return Value

93

Function Object

94

Parameter 94 Function Methods

94

xii   ◾    Contents

Examples of JavaScript Function Objects OBJECTS IN JAVASCRIPT

94 95

Object Creation in JavaScript

95

Creating a Method in a JavaScript Object

97

Object Methods in JavaScript

97

ARRAY IN JAVASCRIPT Array Methods in JavaScript STRING IN JAVASCRIPT

98 100 102

String Methods in JavaScript

103

DATE OBJECT IN JAVASCRIPT

106

Constructor 106 Date Methods in JavaScript

106

Date Example in JavaScript

108

Example of JavaScript Current Time

108

Example of a JavaScript Digital Clock

108

MATH IN JAVASCRIPT Math Methods

109 109

Math.sqrt(n) 110 Math.random() 110 Math.pow(m, n)

110

Math.floor(n) 111 Math.ceil(n) 111 Math.round(n) 111 Math.abs(n) 112 NUMBER OBJECT IN JAVASCRIPT

112

Number Constants in JavaScript

112

Number Methods in JavaScript

113

JAVASCRIPT BOOLEAN

113

Boolean Properties

113

Boolean Methods

114

ERRORS AND EXCEPTIONS IN JAVASCRIPT

114

Contents   ◾    xiii

What Exactly Is Exception Handling?

114

Errors in Syntax

115

Runtime Errors

115

Logical Errors

116

Statement of try...catch...finally

116

The throw Statement

119

The onerror() function

120

EVENTS IN JAVASCRIPT

122

What Exactly Is an Event?

122

onclick Event Type

123

onsubmit Event Type

123

onmouseover and onmouseout

124

Standard HTML 5 Events

125

NOTES 128

Chapter 3   ◾   Getting Started with JavaScript II IN THIS CHAPTER

131 131

HOW CAN WE BUILD AN ASYNCHRONOUS NODE.JS FUNCTION? 131 HOW DO WE WRITE AN ASYNCHRONOUS FUNCTION IN JAVASCRIPT?

134

Waiting for Multiple Promises

138

Synchronous and Asynchronous in JavaScript

141

Synchronous JavaScript 141 Asynchronous JavaScript 142 Explain the Difference between Asynchronous and Deferred JavaScript 143 Asynchronous 144 Deferred 144 Asynchronous vs Deferred

144

DOCUMENT OBJECT MODEL

145

Document Object Properties

145

Document Object Methods

146

xiv   ◾    Contents

Document Object Accessing Field Value

146

METHOD DOCUMENT.GETELEMENTBYID() IN JAVASCRIPT 147 GETELEMENTSBYCLASSNAME() 147 Method getElementsByClassName() Example

147

Distinction between the Methods getElementsByClassName(), querySelector(), and querySelectorAll() 148 METHOD DOCUMENT.GETELEMENTSBYNAME() IN JAVASCRIPT 149 METHOD DOCUMENT.GETELEMENTSBYTAGNAME() IN JAVASCRIPT 149 THE INNERHTML IN JAVASCRIPT

151

InnerHTML Property Example

151

Example of a Comment Form Using innerHTML

151

THE INNERTEXT IN JAVASCRIPT

152

Example of JavaScript innerText

152

5 METHODS FOR MAKING HTTP REQUESTS IN JAVASCRIPT 153 XMLHttpRequest 153 Advantages of XMLHttpRequest 156 Disadvantages of XMLHttpRequest 156 Fetch 156 Advantages of Fetch 158 Disadvantages of Fetch 158 Axios 159 Advantages Axios 160 Disadvantages Axios 160 SuperAgent 161 Advantages of SuperAgent 162 Disadvantages of SuperAgent 162 Ky 162

Contents   ◾    xv

Advantages of Ky 163 Disadvantages of Ky 164 HTTP COOKIES

164

Utilization of Cookies

165

How Do Cookies Work?

166

Cookies in JavaScript

166

Create Cookies 166 Client Side 167 Web Server Side 167 Properties of Cookies

168

Scope of Cookies 168 Varieties of Cookie

170

First-Party Cookies 170 Third-Party Cookies 171 Session Cookies 171 Secure Cookies 171 Zombie Cookies 172 FORM IN JAVASCRIPT

172

Overview to Forms

172

Referencing Forms

173

Submitting Form

174

Login Form

174

SignUp Form

175

VALIDATION OF JAVASCRIPT FORMS

177

Example of Form Validation in JavaScript

177

Password Retype Validation in JavaScript

178

Number Validation in JavaScript

178

Validation of JavaScript Using an Image

179

Email Validation in JavaScript

180

WORKING WITH JAVASCRIPT APIS

181

THE MOST WELL-KNOWN JAVASCRIPT LIBRARIES

191

xvi   ◾    Contents

jQuery 191 Features 191 Use Cases 192 React.js 192 Features 192 Use Cases 193 D3.js 193 Features 193 Use Cases 194 Underscore.js 194 Features 194 Use Cases 195 Lodash 195 Features 195 Use Cases 195 Algolia Places

195

Features 196 Use Cases 196 Anime.js 196 Features 196 Use Cases 197 Animate On Scroll (AOS)

197

Features 197 Use Cases 197 Bideo.js 198 Features 198 Use Cases 198 Chart.js 198 Features 198 Use Cases 199 Cleave.js 199

Contents   ◾    xvii

Features 199 Use Cases 199 Choreographer.js 199 Features 200 Use Cases 200 Glimmer 200 Features 200 Use Cases 200 Granim.js 201 Features 201 Use Cases 201 fullPage.js 202 Features 202 Use Cases 202 Leaflet 202 Features 203 Case Studies 203 Multiple.js 203 Features 203 Use Cases 204 Moment.js 204 Features 204 Use Cases 204 Masonry 204 Features 204 Use Cases 205 Omniscient 205 Features 205 Use Cases 205 Parsley 206 Features 206

xviii   ◾    Contents

Use Cases 206 Popper.js 206 Features 207 Use Cases 207 Three.js 207 Features 207 Use Cases 207 Screenfull.js 207 Features 208 Use Cases 208 Polymer 208 Features 208 Use Cases 208 Voca 208 Features 209 Use Cases 209 NOTES 209

Chapter 4   ◾   The Clearer Picture

211

IN THIS CHAPTER

211

A JAVASCRIPT FRAMEWORK IS WHAT?

211

What Distinguishes a JavaScript Framework from a JavaScript Library?

212

Use a JavaScript Framework, But Why?

212

Libraries and Frameworks for JavaScript

213

TOP 7 JAVASCRIPT FRONTEND FRAMEWORKS 1. React

214 214

How It Operates 214 Popular React Components 215 Advantages 215 Disadvantages 215 When Should We Utilize React? 215

Contents   ◾    xix

2. Vue.js

215

How It Operates 216 Real-Life Examples 216 Popular Vue.js Components 216 Advantages 217 Disadvantages 217 When Should We Utilize Vue.js? 217 3. Angular

217

How It Operates 218 Real-Life Examples 218 Popular Angular Components 218 Advantages 219 Disadvantages 219 When Should We Utilize Angular? 219 4. jQuery

219

How It Operates 219 Real-Life Examples 220 Popular jQuery Components 220 Advantages 221 Disadvantages 221 When Should We Utilize jQuery? 221 5. Svelte

221

How It Operates 221 Real-Life Examples 222 Popular Svelte Components 222 Advantages 222 Disadvantages 222 When Should We Utilize Svelte? 223 6. Ember

223

How It Operates 223 Real-Life Examples 223

xx   ◾    Contents

Popular Ember Components 224 Advantages 224 Disadvantages 224 When Should We Utilize Ember? 224 7. Backbone.js

224

How It Operates 225 Real-Life Examples 225 Advantages 225 Disadvantages 225 When Should We Utilize Backbone.js? 226 How Can We Choose the Ideal JavaScript Framework for Our Next Project?

226

Team Proficiency 226 Backward Compatibility 226 Complexity 226 Size and Functionality 227 5 Backend JavaScript Frameworks

227

THE EIGHT TOP JAVASCRIPT GAME ENGINES

231

10 MAJOR JAVASCRIPT FRAMEWORKS FOR DEVELOPING MOBILE APPS

233

1. React Native

234

In What Ways Is React Native Superior? 234 2. NativeScript

234

Why Is NativeScript Used? 235 3. Ionic

235

Why Is Ionic Used? 235 4. Apache Cordova

235

Why Was Cordova Chosen? 236 5. OnSenUI

236

Why Use OnSen UI? 236 6. jQuery Mobile

236

7. Mobile Angular UI

237

Contents   ◾    xxi

8. Sencha Touch

237

9. Titanium

238

10. Meteor

238

THE BEST JS FRAMEWORKS FOR DESKTOP APPLICATIONS 238 Are Cross-Platform Apps Interchangeable with Desktop Programs? 239 The Advantages and Disadvantages of a Standalone Level vs a Cross-Platform App

239

Are Desktop Apps Supported by React and NodeJS?

239

Top Five JS Frameworks for Desktop Applications (Desktop Apps) 240 1. Electron 240 2. NodeGUI 240 3. Proton Native 241 4. NW.js 241 5. AppJS 241 HOW TO SELECT THE BEST JAVASCRIPT FRAMEWORK FOR OUR PROJECT

242

Development Speed and Simplicity of Use, as well as Project Support 242 Trends 242 Scalability and Mobility

242

The Frequency of Updates

242

Which JavaScript Framework Should We Start With?

243

React.js 244 Node.js 244 JAVA VS. JAVASCRIPT

244

PYTHON VS. JAVASCRIPT

247

What Is JavaScript?

247

What Is Python?

248

Differences of Most Significance

248

xxii   ◾    Contents

Features of JavaScript

249

Features of Python

249

Comparison between Python vs Java Script

250

JQUERY VS. JAVASCRIPT

251

What Exactly Is jQuery?

251

The Distinction between jQuery and JavaScript

252

JAVASCRIPT VS. PHP

252

What Exactly Is PHP?

252

The Distinction between JavaScript and PHP

253

DART VS. JAVASCRIPT

254

What Exactly Is Dart?

255

Benefits and Drawbacks of Dart

255

Advantages 255 Drawbacks 255 What Is JavaScript?

256

Advantages 256 Drawbacks 256 Important Distinction between Dart and JavaScript

257

Simplicity of Use 257 Speed 257 Type Security 257 Popularity 258 The Learning Curve 258 Web vs. Mobile 258 Frontend vs. Backend 259 Commercial Usage 259 JAVASCRIPT VS. ANGULAR JS What Is JavaScript?

260 261

JavaScript Features 261 What Is Angular Js?

262

Angular JS features 262

Contents   ◾    xxiii

Major Distinctions between JavaScript and Angular JS

262

Comparative Analysis of JavaScript and Angular JS

263

JAVASCRIPT VS. NODE.JS

264

What Is JavaScript?

264

JavaScript’s Benefits and Drawbacks Are Discussed

264

Benefits 264 Drawbacks 265 What Is Node.js?

265

How Does Node.js Work, and What Are Its Benefits and Drawbacks? 266 Benefits 266 Drawbacks 266 Comparing JavaScript with Node.js: Key Distinctions

267

In-Depth Analysis of JavaScript vs. Node JS

268

NOTES 269

Chapter 5   ◾   Frontend Development

271

IN THIS CHAPTER

271

FRONTEND VS BACKEND

271

FRONTEND DEVELOPMENT

271

Frontend Languages

272

Frontend Frameworks and Libraries

272

BACKEND DEVELOPMENT

274

Backend Languages

274

Backend Frameworks

275

Difference between Frontend and Backend Development

275

REACTJS 276 WHAT DOES THE ‘REACT’ MEAN?

276

The Question Is, ‘Why React?’

276

React Features

277

JSX 278 Components 278

xxiv   ◾    Contents

Data Binding, One Way Only 278 Virtual DOM 278 Simplicity 278 Performance 279 Benefits and Drawbacks of ReactJS

279

Benefits 279 Drawbacks 281 Version of React

282

SETUP OF THE REACT ENVIRONMENT

286

REACTJS INSTALLATION METHODS

286

1. By Use of the npm Command

286

Install NPM and NodeJS 286 Get React and React DOM Installed 286 Install Webpack 287 Install Babel 288 Creation of Files 288 2. Set React Application Compiler, Loader, and Server

289

Configure Webpack 289 HTML Webpack Template for the index.html File 291 App.jsx and main.js 291 Creation of .babelrc file 292 Running Server 292 Create the Bundle 293 3. Use the Command create-react-app

293

Install NodeJS and NPM 293 Installation of React 293 Develop a New React Project 293 App.js 294 Running Server COMPARISON BETWEEN ANGULARJS VS REACTJS

295 295

AngularJS 295

Contents   ◾    xxv

Characteristics of AngularJS 295 ReactJS 296 Characteristics of ReactJS 297 AngularJS vs. ReactJS COMPARISON BETWEEN REACTJS AND SVELTE What Is Svelte?

298 298 298

When Need One Use Svelte? 299 Which Companies Utilize Svelte? 299 What Is React?

299

When Should React to Be Used? 299 Which Companies Utilize React? 300 React vs Svelte: Which Is Superior?

300

Performance 300 Bundle Size 300 Testing 301 Community Assistance 301 Who Succeeds? REACT JSX

301 302

Why Use JSX?

302

JSX Nested Elements

303

App.JSX 303 Attributes in JSX

303

Comments in JSX

305

Styling in JSX

306

EXPRESS.JS 307 WHAT IS EXPRESS.JS

307

Why Employ Express?

307

How Does Express Appear?

308

basic_express.js 308 Prerequisite 308 Audience 308

xxvi   ◾    Contents

Problem 308 Benefits of Express.js

308

SETTING UP EXPRESS

309

The Early Stages

310

Its Evolution

310

BASICS OF NODE.JS

311

Types of Primitive

311

Loose Typing

311

Object Literal

311

Functions 312 Buffer 312 Process Object

312

Defaults to Local

312

Utilize Global Scope

313

VUEJS 313 WHAT IS VUEJS?

313

Features 313 Comparative Assessment of Other Frameworks

315

VueJS vs React 315 VueJS vs Angular

316

Similarities 316 Complexity 317 Performance 317 Popularity 317 Dependencies 317 Flexibility 317 Reverse Compatibility 318 Typescript 318 ENVIRONMENT SETUP FOR VUEJS

318

Directly Use the HTML tags on a web page.

Getting Started with JavaScript I   ◾    75

We may insert the

The script tag requires two critical attributes. • Language: This element defines the scripting language that is being used. Its value is often JavaScript. Despite the fact that subsequent versions of HTML (and its successor, XHTML) have phased out the usage of this feature. • Type: The value of type is now recommended to be “text/javascript” to indicate the scripting language being used. As a result, our JavaScript portion will look like this:

OUR FIRST JAVASCRIPT CODE Let’s try printing “Hello Everyone” as an example. We included an optional HTML comment around our JavaScript code. This is done to protect our code from browsers that do not support JavaScript.10 The remark concludes with “//-->” Because “//” represents a comment in JavaScript, we include it here to prevent a browser from seeing the end of the HTML comment as JavaScript code. Then we’ll call a function document. This inserts a string into our HTML document This function can create text, HTML, or both. Take a look at the code below.

     

76   ◾    Conquering JavaScript       < script language = "javascript" type = "text/ javascript">                          

Line Breaks and Whitespace JavaScript disregards spaces, tabs, and newlines in JavaScript scripts. We may freely utilize spaces, tabs, and newlines in our program, and we can style and indent it in a clean and uniform manner that makes the code simple to read and comprehend. Semicolons Are Not Required Simple statements in JavaScript, like those in C, C++, and Java, are ­usually followed by a semicolon character. JavaScript, on the other hand, permits us to eliminate this semicolon if each of our statements is on a distinct line. The following code, for example, might be written without semicolons.

However, semicolons must be used when formatting in a single line, as seen below.

Getting Started with JavaScript I   ◾    77

Case Sensitivity JavaScript is a case-sensitive programming language. This implies that all language keywords, variables, function names, and other identifiers must be entered with consistent letter capitalization. In JavaScript, the identifiers Time and TIME will have distinct meanings. NOTE: When naming variables and functions in JavaScript, use caution.

COMMENT IN JAVASCRIPT JavaScript comments are an effective technique to convey information. It is used to include code information, cautions, or recommendations so that the end user can easily read the code.11 The browser’s built-in JavaScript engine disregards the JavaScript comment. Benefits of JavaScript Comments JavaScript comments have primarily two benefits. • To make coding more understandable, it may be used to develop the code so that the end user understands it easily. • To prevent the needless code, it can also use to prevent the code from running. Sometimes, we add code to do a certain activity. However, the code may need to be disabled after a while. In this instance, it is preferable to utilize comments. JavaScript Comment Types In JavaScript, there are two kinds of comments. • Single-line comment • Multiline comment Single-Line Comment in JavaScript It is denoted by two forward slashes (//). It can be used both before and after the sentence. Let’s look at an example of a single-line comment, which is put before the statement.

Let’s look at an example of a single-line comment, which is placed after the statement.  

Multiline Comment in JavaScript It may be used to add single or multiple line comments. As a result, it is more convenient. It is symbolized as a forward slash followed by an asterisk, followed by another forward slash. As an example: /* code here  */  

It can be used before, after, or in the midst of a sentence.  

VARIABLE IN JAVASCRIPT A JavaScript variable is nothing more than the name of a storage place.12 Variables in JavaScript are classified into two types: local variables and global variables. There are several guidelines to follow when declaring a JavaScript ­variable (also known as identifiers). • The name begins with the letter (a-z or A-Z), underscore (_), or ­dollar ($) symbol.

Getting Started with JavaScript I   ◾    79

• We can put numbers (0–9) after the initial letter, for example value1. • Variables in JavaScript are case sensitive; therefore, x and X are different. JavaScript Variables That Are Correct var d = 20;   var _value="sonoo";  

JavaScript Variables That Are Not Correct var  321=20;   var *bb=310;

Variable in JavaScript Example Let’s look at a basic JavaScript variable example.  

Local Variable in JavaScript A local variable in JavaScript is declared within a block or function. It is only available within the function or block. As an example:  

OR  

The Global Variable in JavaScript A global variable in JavaScript may be accessed from any function. A global variable is one that is defined outside of the function or declared with the window object. As an example:  

Declaring a Global Variable in JavaScript within a Function We must utilize the window object to define JavaScript global variables within a function. As an example: window.value=70;  

It may now be defined within any function and accessed from any function. As an example: function m(){       window.value=120;//declaring the global variable by window object       }       function n(){       alert(window.value);//accessing the global variable from the other function       }  

Internals of Global Variable When we declare a variable outside of a function, it is automatically added to the window object. We may also get to it via the window object. As an example:

Getting Started with JavaScript I   ◾    81 var value=60;   function a(){   alert(window.value);//access global variable   }  

DATA TYPES IN JAVASCRIPT JavaScript supports many data types for storing various sorts of values. In JavaScript, there are two kinds of data types:13 • Primitive data type • Non-primitive data type JavaScript is a dynamic type language; therefore, there’s no need to specify the variable’s type before using it in code. To indicate the data type, we must use var here. It may store any sort of value, such as integers, strings, and so on. As an example: var a=60;//hold number   var b="Raman";//hold string  

Primitive Data Types in JavaScript In JavaScript, there are five basic data types. These are their names: Data Type

Description

String

Indicates a string of characters, such as “hi.”

Number Boolean Undefined Null

Depicts a set of numbers, e.g., 100. Indicates a Boolean value that can be either false or true. Signifies an undefined value. Represents null, that is, no value at all.

NON-PRIMITIVE DATA TYPES IN JAVASCRIPT The following are the non-primitive data types: Data Type

Description

Object

Represents an instance that allows us to access members.

Array RegExp

Indicates a set of values that are comparable. Stands for regular expression.

82   ◾    Conquering JavaScript

OPERATORS IN JAVASCRIPT Operators in JavaScript are symbols that are employed to perform actions on operands. As an example14: var sum=30+10;  

The arithmetic operator + is used here, while the assignment operator = is used. In JavaScript, there are several sorts of operators. • Arithmetic operators • Comparison (relational) operators • Bitwise operators • Logical operators • Assignment operators • Special operators Arithmetic Operators To conduct arithmetic operations on the operands, arithmetic operators are employed.15 JavaScript arithmetic operators are the operators listed below. Operator

Description

+

Addition

− * / % ++ --

Subtraction Multiplication Division Modulus (remainder) Increment Decrement

Example

20+20 = 40 30−10 = 20 20*20 = 400 40/10 = 4 40%10 = 0 var a=20; a++; Now a = 21 var a=20; a--; Now a = 19

Comparison Operators The comparison operator in JavaScript compares the two operands. The following are the comparison operators:

Getting Started with JavaScript I   ◾    83 Operator

Description

Example

==

Is equal to

20==10 = false

=== != !== > >= < 20 = true 30>=20 = true 302) = 2

Logical Operators JavaScript logical operators include the basic operators. Operator

&& || !

Description

Example

Logical AND Logical OR Logical Not

(20==10 && 10==33) = false (20==10 || 10==33) = false !(20==10) = true

Assignment Operators JavaScript assignment operators include the following operators. Operator

= += -= *= /= %=

Description

Example

Assign Add and assign Subtract and assign Multiply and assign Divide and assign Modulus and assign

20+20 = 40 var a=20; a+=10; Now a = 30 var a=10; a-=20; Now a = 10 var a=20; a*=10; Now a = 200 var a=20; a/=2; Now a = 10 var a=20; a%=2; Now a = 0

84   ◾    Conquering JavaScript

Special Operators JavaScript special operators include the following operators. Operator

Description

Based on the condition, the Conditional Operator returns a value. It’s similar (?:) to if-else. , Multiple expressions can be evaluated as a single statement using the Comma Operator. delete The Delete Operator removes a property from an object. in Operator determines if an object has the specified attribute. instanceof Tests to see whether the object is an instance of the provided type makes an instance (object) checks the object’s type. new It ignores the return value of the expression. typeof Validates what the generator’s iterator returns in a generator. void Based on the condition, the Conditional Operator returns a value. It’s similar to if-else. yield Multiple expressions can be evaluated as a single statement using the Comma Operator.

IF-ELSE STATEMENTS IN JAVASCRIPT The if-else statement in JavaScript is used to run code whether the condition is true or false. In JavaScript, there are three types of if statements:16 • If Statement • If else statement • If else if statement If Statement It only analyses the content if the expression is true. The JavaScript if statement’s signature is shown below. if(expression){   //content to evaluate }  

Getting Started with JavaScript I   ◾    85

Flowchart: start

Cond ition

false

if code

after if

exit

Statement of if

Let’s look at a basic if statement in JavaScript.  

If...else Statement It determines if the condition is true or false. The syntax of the if-else statement in JavaScript is shown below.17 if(expression){       //content to evaluate if the condition is true       }       else{       //content to evaluate if the condition is false       }      

86   ◾    Conquering JavaScript

Flowchart: start

Cond ition

false

else code

true if code

after if

exit

Statement of if-else

Let’s look at an example of an if-else statement in JavaScript to determine if a number is even or odd.  

If...else if Statement It only analyses the content if one of multiple expressions is true. The JavaScript if else if statement’s signature is shown below. if(expression1){  

Getting Started with JavaScript I   ◾    87                      

                     

//content to evaluate }   else if(expression2){ //content to evaluate }   else if(expression3){ //content to evaluate }   else{   //content to evaluate }  

if the expression1 is true     if the expression2 is true     if the expression3 is true  

if no expression is true  

Flowchart:

start

false Condition 1 false Condition 2 false Condition n true true true Statement 1

Statement 2

Statement n

Statement s

next statement

Statement of if-else-if

Let’s look at a basic if-else-if expression in JavaScript.  

is equal to 10”);  

is equal to 15”);  

is equal to 20”);  

is not equal to 20, 25 or 40”);  

SWITCH IN JAVASCRIPT The JavaScript switch statement is used to perform a single piece of code from a collection of expressions. It is the same as the else if statement that we studied on the previous page. However, it is more handy than if...else... if since it may be used with integers, characters, and so on.18 The JavaScript switch statement’s signature is shown below. switch(expression){       case value1:        code to execute;        break;       case value2:        code to execute;        break;       ......             default:        code to execute if the above values are not matched;       }      

Let’s look at a basic switch statement in JavaScript.19  

Let’s look at how the switch statement works in JavaScript.  

LOOPS IN JAVASCRIPT JavaScript loops are used to repeat code using for, while, do-while, and for-in loops. It makes the code smaller. It is most often used in arrays.20 In JavaScript, there are four kinds of loops: • for loop • while loop

90   ◾    Conquering JavaScript

• do-while loop • for-in loop for loop The JavaScript for loop loops over the components a certain number of times. If the number of iterations is known, it should be utilized. The syntax for the for loop is shown below. for (initialization; condition; increment)   {       code to execute  }  

Let’s look at a simple for loop in JavaScript.  

while loop The JavaScript while loop iterates over the components indefinitely. When the expected number of iterations is uncertain, this method should be used. The while loop syntax is seen below. while (condition)   {       code to execute  }  

Let’s look at a simple while loop in JavaScript.  

do-while loop The JavaScript do-while loop, like the while loop, iterates the items indefinitely. Regardless of whether the condition is true or not, the code is performed at least once. The following code demonstrates the do-while loop syntax. do{       code to execute   }while (condition);  

Let’s look at a basic do-while loop in JavaScript example.  

for-in loop The JavaScript for-in loop is used to iterate through an object’s attributes. It consists of three crucial components: • The loop initialization, in which we set our counter to a beginning value. Before the loop starts, the initialization statement is performed.21 • The test statement determines whether or not a particular condition is true. If the condition is met, the code contained inside the loop will be performed; otherwise, the control will exit the loop. • The iteration statement, which allows us to raise or decrease the counter. • All three components may be presented on a single line, separated by semicolons.

92   ◾    Conquering JavaScript for (initialization; test condition; iteration statement) {     Statement(s) to execute if the test condition is true  }

To discover how a for loop works in JavaScript, try a simple example.

                           

Set variable to a different value and then try

   

FUNCTIONS IN JAVASCRIPT JavaScript functions are used to do out tasks. To reuse the code, we may call the JavaScript method many times. The Benefit of the JavaScript Function JavaScript functions have primarily two benefits: • Code reusability: We may invoke a function several times to save coding time. • Less coding: This reduces the size of our software. We don’t need to write a lot of code every time we do the same thing.

Getting Started with JavaScript I   ◾    93

Syntax of JavaScript Functions The syntax for defining a function is as follows. function function_Name([arg1, arg2, ...argN]){       //code to execute    }  

JavaScript functions may take zero or more parameters. Let’s look at a basic JavaScript function that doesn’t take any parameters.         

Function Arguments Functions may be called by giving parameters. Let’s look at an example of a function with just one parameter.                        

Function with Return Value We may utilize a function that returns a value in our application. Let us look at an example of a function that returns a value.    

Function Object The function constructor’s purpose in JavaScript is to build a new Function object. It runs the code on a global scale. However, if we directly use the constructor, a function is built dynamically but in an insecure manner. Syntax: new Function ([arg_1[, arg_2[, ....arg_n]],] functionBody)  

Parameter • arg_1, arg_2,..., arg_n: It represents the function parameter. • functionBody: This is the definition of the function. Function Methods Method

Description

It is used to invoke a function that takes this value as well as a single array of apply() arguments. bind() It is used to implement a new function. call() It is used to invoke a function that takes this value and a list of arguments. toString() It gives us the result as a string.

Let’s look at function methods and their descriptions. Examples of JavaScript Function Objects Example 1 Let’s look at an example of displaying the total of two integers.  

Example 2 Let’s look at an example to demonstrate the strength of offered value.  

OBJECTS IN JAVASCRIPT A JavaScript object is a stateful entity with behavior (properties and method), for example, a vehicle, a pen, a bicycle, a chair, a glass, a ­keyboard, and a monitor. JavaScript is an object-oriented programming language. In JavaScript, everything is an object. JavaScript is template-based rather than classbased.22 We don’t construct a class to retrieve the object here. However, we guide the creation of things. Object Creation in JavaScript Objects may be created in three ways. • By object literal. • By generating instance of Object directly (using the new keyword). • By making use of an Object constructor (using the new keyword). By object literal By generating instance of Object directly (using the new keyword) By making use of an Object constructor (using the new keyword)

Object Creation in JavaScript

96   ◾    Conquering JavaScript

1. Object by object literal The syntax for constructing an object using an object literal is as follows: object={property1:value_1,property2:value_2..... propertyN:value_N}  

As we can see, property and value are distinguished by : (colon). Let’s look at a basic example of object creation in JavaScript.  

2. By generating an Object instance The syntax for generating an object directly is as follows: var object_name=new Object();  

The new keyword is used to construct the object in this case. Let’s look at an example of directly constructing an object.  

3. By making use of an Object constructor We must construct a function with parameters here. This keyword may be used to assign each parameter value to the current object. The keyword this relates to the current object. The following example shows how to create an object using an object constructor.  

Creating a Method in a JavaScript Object In a JavaScript object, we may specify methods. However, before we define method, we must add a property in the function with the same name as method. The following is an example of defining a method in an object.  

Object Methods in JavaScript Object’s numerous methods are as follows: S.No

Methods

1

Object.assign()

2

Object.create()

3

Object.defineProperty()

Description

Enumerable and own properties are transferred from a source object to a destination object using this method. This function is used to generate a new object using the prototype object and properties given. This approach is used to characterize some of the property’s behavioral characteristics. (Continued)

98   ◾    Conquering JavaScript S.No

4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

Methods

Description

Object.defineProperties()

Multiple object attributes can be created or configured using this technique. Object.entries() This function returns an array containing arrays of key-value pairs. Object.freeze() This strategy avoids the removal of existing properties. Object.getOwnPropertyDescriptor() This function returns a property descriptor for the given object’s property. Object.getOwnPropertyDescriptors() This function retrieves all of an object’s own property descriptors. Object.getOwnPropertyNames() This function produces an array of all properties discovered (enumerable or not). Object.getOwnPropertySymbols() This function produces an array containing all of our own symbol key attributes. Object.getPrototypeOf() The prototype of the given object is returned by this method. Object.is() This function compares two values to see if they are the same. Object.isExtensible() This method detects whether or not an object is extendable. Object.isFrozen() This method detects whether or not an item was frozen. Object.isSealed() This method detects whether or not an item is sealed. Object.keys() This function returns an array containing the names of the properties of the supplied object. Object.preventExtensions() This technique is used to prohibit an object from extending. Object.seal() This approach disables the addition of new properties and labels all current properties as non-configurable. Object.setPrototypeOf() This function assigns the prototype of one object to another. Object.values() This method returns a value array.

ARRAY IN JAVASCRIPT An object that represents a group of identical objects in JavaScript is called an array. In JavaScript, there are three methods to create an array.23 • By array literal.

Getting Started with JavaScript I   ◾    99

• By explicitly generating an Array instance (using new keyword). • By making use of an Array constructor (using new keyword).

By array literal

By explicitly generating an Array instance (using new keyword) By making use of an Array constructor (using new keyword)

Array in JavaScript

1. Array literal in JavaScript The syntax for building an array using an array literal is as follows: var arrayname=[value_1,value_2.....value_N];  

As we can see, values are enclosed by [] and separated by, (comma). Let’s look at a basic example of constructing and utilizing an array in JavaScript.  

The .length attribute returns the array’s length. 2. Array directly in JavaScript (new keyword) The syntax for constructing an array directly is as follows: var array_name=new Array();  

In this case, the new keyword is used to construct an array object. Let’s look at an example of directly generating an array.

100   ◾    Conquering JavaScript  

3. The array constructor in JavaScript (new keyword) We must build an array instance by providing parameters to the constructor so that we do not have to specify a value manually. The following is an example of object creation using an array constructor.  

Array Methods in JavaScript Let’s go through the JavaScript array methods and their descriptions. Methods

Description

concat()

It creates a new array object from two or more merged arrays.

copywithin()

It replaces the provided array’s elements with its own and returns the transformed array. It generates an iterator object and a loop that loops through each key/ value pair. It checks if all of the items of an array fulfill the function criteria. It generates a new array with sub-array entries concatenated recursively until the desired depth is reached. It uses a mapping function to map all array items, then flattens the result into a new array. It populates an array with static values. (Continued)

entries() every() flat() flatMap() fill()

Getting Started with JavaScript I   ◾    101 Methods

from() filter() find() findIndex() forEach() includes() indexOf() isArray() join() keys() lastIndexOf()

Description

It generates a new array containing an identical duplicate of another array element. It returns a new array containing the entries that satisfy the function’s requirements. It returns the value of the first array element that meets the provided criterion. It returns the index of the first member in the provided array that meets the criterion. It calls the specified method once for each array element. It determines whether the provided element is present in the provided array. It searches the provided array for the specified element and provides the index of the first match. It determines whether the provided value is an array. It creates a string by joining the members in an array. It constructs an iterator object that just includes the array keys, then loops through these keys.

It returns the value of the first array element that meets the provided criterion. map() It executes the supplied function on each array element and returns the new array. of() It generates a new array from a configurable number of parameters, which can be of any type. pop() It removes and returns the array’s final element. push() It appends one or more array elements to the end. reverse() It flips the items of the provided array. reduce(function, It runs the specified function for each value in the array from left to initial) right, reducing the array to a single value. reduceRight() It runs the specified function for each value in the array from right to left, reducing the array to a single value. some() It determines if any member of the array satisfies the implemented function’s test. shift() It removes and returns the array’s first member. slice() It returns a new array containing a duplicate of the specified array’s portion. sort() It returns the sorted elements of the provided array. splice() It adds and removes elements from the specified array. toLocaleString() It returns a string containing all of the members in the array supplied. toString() It translates the items of a given array into string form while leaving the original array alone. unshift() It inserts one or more elements at the start of the provided array. values() It generates a new iterator object with values for each array index.

102   ◾    Conquering JavaScript

STRING IN JAVASCRIPT A string in JavaScript is an object that represents a series of characters.24 In JavaScript, there are two methods for creating strings. • Using a string literal • Using a string object (using new keyword) 1. Using a string literal Double quotes are used to construct the string literal. The syntax for constructing a string using a string literal is as follows: var string_name=”string_value”;    

2. Using a string object (using new keyword) The new keyword’s syntax for creating a string object is as follows: var string_name=new String(“string_literal”);  

In this case, the new keyword is used to construct a string instance. Let’s take a look at a JavaScript string that was formed using the new keyword.  

Getting Started with JavaScript I   ◾    103

String Methods in JavaScript Let’s go over the examples for the JavaScript string methods. Methods

charAt()

Description

The char value located at the specified index is returned.

charCodeAt() concat() indexOf()

It provides the character’s Unicode value at the specified index. It allows us to combine two or more strings. It gives the position of a char value inside the given string as a response. lastIndexOf() It provides the location of a char value inside the given string by returning the results of its search starting from the last position. search() It searches a provided text for a specified regular expression and, if a match is discovered, returns its location. match() If a match is discovered, it checks a given text for a specified regular expression and returns that regular expression. replace() It substitutes the provided string with the given string. substr() Based on the specified beginning position and length. ,i It is used to obtain a portion of the given string. substring() Based on the specified index ,i It is used to get a section of the given text. slice() We may use it to get a section of the given string. We can provide both positive and negative indices thanks to it. toLowerCase() It lowercases the string that is sent to it. toLocaleLowerCase() It transforms the provided string to lowercase letters based on the current locale of the host. toUpperCase() It changes the string to uppercase letters. toLocaleUpperCase() It turns the provided text to an uppercase letter based on the host’s current locale. toString() A string that represents the particular object is returned. valueOf() It returns the string object’s primitive value. split() It creates substring arrays from a string and then returns the resultant array. trim() It removes the white space from the string’s left and right sides.

1. String charAt(index) Method in JavaScript The charAt() function of the JavaScript String returns the character at the specified index.  

2. JavaScript String concat(str) (Method) The String concat(str) method in JavaScript concatenates or unites two strings.  

3. String indexOf(str) Method in JavaScript The JavaScript String indexOf(str) function returns the string’s index position.  

4. Method JavaScript String lastIndexOf(str) The JavaScript String lastIndexOf(str) function returns the string’s last index point.  

5. The toLowerCase() method in JavaScript The String toLowerCase() function in JavaScript returns the provided string in lowercase characters.  

6. The toUpperCase() method in JavaScript The String toUpperCase() function in JavaScript returns the provided string in uppercase characters.  

7. String slice(beginIndex, endIndex) Method in JavaScript The String slice(beginIndex, endIndex) function in JavaScript returns the sections of a string from beginIndex to endIndex. The beginIndex is inclusive and endIndex is exclusive in the slice() function.  

8. String trim() Method in JavaScript The JavaScript String trim() function eliminates whitespace from the beginning and end of a string.  

9. String split() method in JavaScript  

106   ◾    Conquering JavaScript

DATE OBJECT IN JAVASCRIPT We may use the JavaScript date object to retrieve the year, month, and day. The JavaScript date object may be used to show a timer on a website. To generate a date object, we may utilize several Date25 constructors. It includes methods for retrieving and setting the day, month, year, hour, minute, and seconds. Constructor To build a date object, we may use one of four Date constructor variants. • Date() • Date(milliseconds) • Date(dateString) • Date (year, month, day, hours, minutes, milliseconds, seconds) Date Methods in JavaScript Let’s go through the JavaScript date methods and their descriptions. Methods

getDate() getDay() getFullYears() getHours() getMilliseconds() getMinutes() getMonth() getSeconds() getUTCDate() getUTCDay()

Description

It generates an integer number, ranging from 1 to 31, which represents the day for the specified date and time in local time. It produces an integer number between 0 and 6 that reflects the weekday based on local time. It returns the integer number representing the year in local time. It produces an integer number between 0 and 23 representing the hours in local time. It returns an integer number between 0 and 999 representing milliseconds in local time. It produces an integer number between 0 and 59 representing the minutes in local time. It actually gives an integer value between 0 and 11 that, based on local time, reflects the month. It produces an integer number between 0 and 60 representing the seconds in local time. It produces an integer number between 1 and 31 representing the day for the given date in universal time. It generates an integer number, ranging from 0 to 6, which corresponds to the day of the week in universal time. (Continued)

Getting Started with JavaScript I   ◾    107 Methods

getUTCFullYears()

Description

It returns the integer number representing the year in universal time. getUTCHours() It returns an integer number between 0 and 23 representing the hours based on universal time. getUTCMinutes() It produces an integer number between 0 and 59 representing the minutes in universal time. getUTCMonth() It produces an integer number between 0 and 11 representing the month in universal time. getUTCSeconds() It returns an integer number between 0 and 60 representing the seconds in universal time. setDate() It determines the day value for the given date using local time. setDay() It determines the specific day of the week based on local time. setFullYears() It determines the year value for the given date using local time. setHours() It determines the hour value for the given date using local time. setMilliseconds() It determines the millisecond value for the given date using local time. setMinutes() It determines the minute value for the given date using local time. setMonth() It determines the month value for the given date using local time. setSeconds() It determines the second value for the given date based on local time. setUTCDate() It determines the day value for the given date using universal time. setUTCDay() It establishes the specific day of the week based on universal time. setUTCFullYears() It determines the year value for the given date using universal time. setUTCHours() It determines the hour value for the given date using universal time. setUTCMilliseconds() It computes the millisecond value for the given date using universal time. setUTCMinutes() Minute values for the given date are calculated using UTC. setUTCMonth() It determines the month value for the given date using universal time. setUTCSeconds() It determines the second value for the given date using universal time. toDateString() It returns a Date object’s date component. toISOString() It returns the date in ISO standard string form. toJSON() It returns a string containing the Date object’s representation. During JSON serialization, it also serializes the Date object. toString() It returns a string representation of the date. toTimeString() It gives us the time component of a Date object. toUTCString() The input date is converted to a string representing UTC time. valueOf() It returns a Date object’s basic value.

108   ◾    Conquering JavaScript

Date Example in JavaScript Let’s look at a simple example of printing a date object. It publishes both the date and the time. Current Date and Time:    

Let’s look at another code to print the date, month, and year.  

Example of JavaScript Current Time Let’s look at a basic example of printing the system’s current time. Current Time:    

Example of a JavaScript Digital Clock Let’s look at a basic example of displaying a digital clock using a JavaScript date object. In JavaScript, we may specify intervals using either the setTimeout() or setInterval() methods. Current Time:    

MATH IN JAVASCRIPT The JavaScript math object has a number of constants and methods for performing mathematical operations.26 It does not have constructors, unlike the date object. Math Methods Let’s go through the JavaScript math methods and their descriptions.27 Methods

abs() acos() asin() atan() cbrt() ceil() cos() cosh()

Description

It gives the absolute value of the number provided. The arccosine of the provided integer in radians is returned. It computes the arcsine of the provided number in radians and returns it. It returns the arc-tangent in radians of the provided integer. It returns the cube root of the integer supplied. The function returns the smallest integer greater than or equal to the given parameter. It returns the cosine of the number provided. The hyperbolic cosine of the provided integer is returned. (Continued)

110   ◾    Conquering JavaScript Methods

Description

exp() It returns the provided number’s exponential form. floor() The largest integer that is less than or equal to the given value is returned. hypot() It gives back the cube root of the sum of the squares of the given numbers. log() It computes the natural logarithm of a number. max() It returns the greatest possible value of the provided numbers. min() It returns the smallest of the provided numbers. pow() It returns the value of the base multiplied by the power of the exponent. random() It returns a random number between 0 (inclusive) and 1 (exclusive) (exclusive). round() It returns the integer value that is closest to the specified number. sign() It returns the sign of the number provided. sin() It returns the sine of the number provided. sinh() The hyperbolic sine of the provided integer is returned. sqrt() It computes the square root of the input number. tan() It returns the tangent of the integer provided. tanh() The hyperbolic tangent of the supplied integer is returned. trunc() It gives back an integer portion of the provided number.

Math.sqrt(n) The math.sqrt(n) function in JavaScript returns the square root of the provided integer. The Square Root of 14 is:        

Math.random() The math.random() function in JavaScript provides a random integer between 0 and 1. The Random Number is:      

Math.pow(m, n) The JavaScript math.pow(m, n) function returns mn, which is m to the power of n.

Getting Started with JavaScript I   ◾    111 5 to the power of 2 is:    

Math.floor(n) The math.floor(n) function in JavaScript delivers the lowest integer for the supplied value. For example, 3 for 3.7, 5 for 5.9, and so on. The Floor of 5.2 is:    

Math.ceil(n) The math.ceil(n) function in JavaScript gives the biggest integer for the supplied number. For example, 4 for 3.7, 6 for 5.9, and so on. The Ceil of 5.2 is:        

Math.round(n) The JavaScript calculation. The round(n) function returns the rounded integer that is closest to the provided number. If the fractional component is equal to or larger than 0.5, the upper value 1 is used; otherwise, the lower value 0 is used. For instance, 4 for 3.7, 3 for 3.3, 6 for 5.9, and so on. The Round of 5.2 is:
    The Round of 5.6 is:      

Math.abs(n) The math.abs(n) function in JavaScript returns the absolute value of the provided integer. For example, 4 for -–4, 6.6 for –6.6, and so on. The Absolute value of -6 is:        

NUMBER OBJECT IN JAVASCRIPT We may express a numeric value using the JavaScript number object. It may be either integer or floating point. To represent floating-point numbers, the JavaScript number object adheres to the IEEE standard.28 In JavaScript, we may build a number object with the Number() constructor. As an example: var nm=new Number(value);  

If the value cannot be converted to a number, it returns NaN (Not a Number), which may be tested using the isNaN() function. We may also directly assign a number to a variable. As an example: var var var var

x=110;//integer value   y=132.7;//floating point value   z=14e6;//exponent value, output: 140000   n=new Number(15);//integer value by number object  

Number Constants in JavaScript Check out the defined JavaScript constants for numbers. Constant

Description

MIN_VALUE

The biggest minimum value is returned.

MAX_VALUE POSITIVE_INFINITY NEGATIVE_INFINITY NaN

The biggest maximum value is returned. overflow value, yields positive infinity. overflow value, yields negative infinity. reflects the value “Not a Number.”

Getting Started with JavaScript I   ◾    113

Number Methods in JavaScript Let’s go through the JavaScript number methods and their descriptions. Methods

isFinite()

Description

It checks to see if the provided value is a finite number.

isInteger() It checks to see if the provided number is an integer. parseFloat() It translates a string into a floating-point number. parseInt() It turns the string provided into an integer number. toExponential() It returns the string that represents the provided number in exponential notation. toFixed() It returns a string with the exact digits following a decimal point. toPrecision() It returns a string representing a number with the precision requested. toString() It returns the specified number as a string.

JAVASCRIPT BOOLEAN A JavaScript Boolean object represents a value in one of two states: true or false.29 The JavaScript Boolean object may be created with the Boolean() constructor, as seen below. Boolean bn=new Boolean(value);  

The JavaScript Boolean object’s default value is false. Example of a JavaScript Boolean

Boolean Properties Property

Description

constructor The reference to the Boolean function that produced the Boolean object is returned. prototype

allows us to include attributes and methods in a Boolean prototype.

114   ◾    Conquering JavaScript

Boolean Methods Method

toSource() toString() valueOf()

Description

The source of the Boolean object is returned as a string. converts a Boolean to a String. converts another type to a Boolean value.

ERRORS AND EXCEPTIONS IN JAVASCRIPT An exception denotes the occurrence of an abnormal circumstance that necessitates the use of unique operational approaches. An exception in programming is a piece of code that deviates from the regular flow of the code. Such exceptions need the use of particular programming structures in order to be executed. What Exactly Is Exception Handling? Exception handling is a procedure or method in programming that is used to handle and execute anomalous statements in code. It also allows you to regulate the flow of the code/program. Various handlers that process the exception and execute the code are utilized to handle the code. For instance, dividing a non-zero number by zero always results in infinity, and this is an exception. Thus, it may be performed and managed with the aid of exception handling. To raise an exception in exception handling, a throw statement is utilized. When an abnormal state arises, throw is used to throw an exception. Wrapping the function in a try...catch block handles the thrown exception. If an error occurs, the catch block is performed; otherwise, just the try block instructions are executed. Thus, numerous forms of mistakes may occur in a programming language, interfering with the correct execution of the program. In programming, there are three categories of errors: a. Syntax errors. b. Runtime errors. c. Logical errors.

Getting Started with JavaScript I   ◾    115

syntax errors,

Types of Erros logical errors.

runtime errors,

Types of errors

Errors in Syntax Syntax mistakes, also known as parsing errors, occur during the compile process in conventional programming languages and during the interpret process in JavaScript.30 The following line, for instance, gives a syntax error because it lacks a closing parenthesis.

When a syntax error occurs in JavaScript, just the code contained inside the same thread as the syntax mistake is impacted, and the remainder of the code in other threads is run as long as it does not rely on the code containing the problem. Runtime Errors During execution (after compilation/interpretation), runtime errors, also known as exceptions, occur. For example, the following line results in a runtime error because, although the syntax is valid, it attempts to invoke a method that does not exist.

Exceptions also have an effect on the thread in which they occur, enabling other JavaScript threads to proceed normally. Logical Errors The most difficult form of mistake to locate is a logic error. These problems are not caused by syntactic or runtime issues. They arise instead when we make a mistake in the logic that drives our script and do not obtain the desired outcome. We cannot notice such issues since the sort of logic we want to include in our software is determined by our business requirements. Statement of try...catch...finally The most recent JavaScript versions introduced exception handling features. JavaScript has the try...catch...finally structure and the throw operator for handling exceptions. JavaScript syntax mistakes can be caught, but not programmer-generated or runtime exceptions. The try...catch...finally block syntax is as follows:

Getting Started with JavaScript I   ◾    117

Either the catch block or the finally block must come before the try block (or one of both). The catch block is executed if an exception is thrown inside the try block and is reported in the e variable. After try/catch, the optional finally block runs unconditionally. Examples Here’s an example of attempting to call a non-existent function, which results in an exception. Let’s see how it acts without try...catch−

                                       

Click following to see the result:

                                     

Let us now utilize try...catch to capture this error and provide a userfriendly message. If we wish to conceal this problem from a user, we may also suppress this message.

118   ◾    Conquering JavaScript

                             

Click following to see the result:

                                     

Finally, we may use a block that will always run unconditionally after the try/catch. Here’s an illustration.

                                   

Click following to see the result:

                                     

The throw Statement We may use the toss statement to raise either built-in or custom exceptions. These exceptions may later be recorded and appropriate action taken. Example The example below shows how to utilize a throw statement.

                                   

Click following to see the result:

                                     

An exception may be thrown in one code using a string, an integer, a Boolean, or an object, and then caught in another function using a try... catch block, as we saw above. The onerror() function To begin handling errors, JavaScript introduced the onerror event handler. When an exception occurs on the page, the error event is dispatched on the window object.

   

Getting Started with JavaScript I   ◾    121                                

Click following to see the result:

                                     

The onerror event handler returns three pieces of information that may be used to determine the specific nature of the error. • Error message: The same message that the browser would show for the specified issue. • URL: The URL of the file where the problem occurred. • Line number: The line number in the provided URL that resulted in the error. Here’s an example of how to get this information. Example

                                 

Click following to see the result:

                                     

We may present extracted data in whichever manner we believe is best. We may use the onerror method to display an error message if there is a difficulty loading an image, as demonstrated below. We may use onerror with a variety of HTML elements to show suitable error messages.

EVENTS IN JAVASCRIPT We will discuss events in JavaScript below: What Exactly Is an Event? JavaScript communicates with HTML through events, which are generated in response to changes made to a page by the user or the browser. After the website loads, something happens. When the user triggers an action, also known as an event.31 Any keypress, window close, window resize, etc., are also considered events. Developers may utilize these events to perform JavaScript programmed replies, such as closing buttons, displaying messages to users,

Getting Started with JavaScript I   ◾    123

validating data, and nearly any other sort of response conceivable. Events are a component of the Document Object Model (DOM) Level 3, and each HTML element has a collection of events that may be used to execute JavaScript code. onclick Event Type This is the most common event kind, which happens when a user hits the left mouse button. We may apply validation, warnings, and so on to this event type. Example Consider the following example.

                                   

Click following button and see result

                                     

onsubmit Event Type When we attempt to submit a form, an event called onsubmit happens. We may use this event type for form validation.

124   ◾    Conquering JavaScript

Example The following code demonstrates how to utilize onsubmit. Before sending form input to the website, we use the validate() method. If the validate() method returns true, the form is submitted; otherwise, the data is not submitted. Consider the following example.

                                               .......                          

onmouseover and onmouseout These two event types will assist us in creating great effects with images or even text. When we move our mouse over an element, the onmouseover event is triggered, and when we move our mouse away from that element, the onmouseout event is triggered. Consider the following example.

                   

         

Bring our mouse inside division to see the outcome:

                      This is inside division                  

Standard HTML 5 Events For our convenience, the standard HTML 5 events are given below. Script denotes a JavaScript function that will be performed against the event. Attribute

Value

Description

Offline

script

When the document is offline, this event occurs.

Onabort onafterprint onbeforeonload onbeforeprint onblur oncanplay

script script script script script script

oncanplaythrough

script

onchange onclick oncontextmenu ondblclick ondrag

script script script script script

An abort event is triggered. This event occurs after the document has been printed. This event occurs before the document is loaded. This event occurs before the document is printed. When the window loses focus, this event occurs. Triggers when media can begin playing but must pause for buffering. When media can be played all the way through without pausing for buffering, this event is triggered. When an element changes, this triggers. Triggers when the mouse is clicked. When a context menu is invoked, this event is triggered. Triggers when the mouse is double-clicked. When an element is dragged, this event occurs. (Continued)

126   ◾    Conquering JavaScript Attribute

Value

Description

ondragend ondragenter

script script

ondragleave

script

ondragover ondragstart ondrop ondurationchange

script script script script

onemptied

script

onended onerror onfocus onformchange onforminput onhaschange oninput

script script script script script script script

oninvalid onkeydown onkeypress onkeyup onload onloadeddata onloadedmetadata

script script script script script script script

onloadstart

script

onmessage onmousedown onmousemove onmouseout

script script script script

onmouseover

script

onmouseup onmousewheel onoffline

script script script

At the end of a drag operation, this triggers. When an element is dragged to a proper drop target, this event is triggered. When an element is moved over a valid drop target, this event occurs. Triggers when a drag operation begins. Triggers when a drag operation begins. When a dragged element is dropped, this event occurs. When the length of the media is modified, this event occurs. When a media resource element becomes unexpectedly empty, this event is triggered. When the medium has reached its finish, this triggers. When an error occurs, this function is triggered. When the window is focused, this event occurs. When a form changes, this event is triggered. When a form receives user input, this event is triggered. When the document changes, this event is triggered. When an element receives user input, this event is triggered. When an element is invalid, this event is triggered. When a key is pressed, this event occurs. When a key is pressed and released, this event occurs. When a key is released, this event occurs. When the document is loaded, this event occurs. When media data is loaded, this event occurs. When a media element’s duration and other media data are loaded, this event occurs. When the browser begins to load the media data, this event occurs. When the message is triggered, this function is called. When a mouse button is pushed, this event occurs. When the mouse cursor moves, this event is triggered. When the mouse cursor leaves an element, this event is triggered. When the mouse cursor passes over an element, this event is triggered. When a mouse button is released, this event occurs. When the mouse wheel is turned, this event occurs. When the document is offline, this event occurs. (Continued)

Getting Started with JavaScript I   ◾    127 Attribute

Value

Description

onoine ononline onpagehide onpageshow onpause onplay

script script script script script script

onplaying onpopstate

script script

onprogress onratechange onreadystatechange

script script script

onredo

script

onresize onscroll

script script

onseeked onseeking

script script

onselect onstalled

script script

onstorage onsubmit onsuspend

script script script

ontimeupdate

script

onundo

script

onunload onvolumechange

script script

onwaiting

script

When the document becomes online, this event occurs. When the document becomes online, this event occurs. When the window is hidden, this event occurs. When the window becomes visible, this event occurs. When media data is halted, this event occurs. Triggers when media data is about to begin playing Triggers when media data has begun playing Triggers when the history of the window changes. When the browser retrieves media data, this event occurs. Triggers when the playing rate of the media data changes. Triggers when the ready-state changes. When the document is redone, this event occurs. When the window is resized, this event occurs. When an element’s scrollbar is scrolled, this event is triggered. When a media element’s seeking property is no longer true and the seeking has stopped, this event is triggered. When media data is halted, this event occurs. Triggers when media data is about to begin playing Triggers when media data has begun playing Triggers when the history of the window changes. This event happens when the browser retrieves media data. When the seeking attribute of a media element is true and the searching has begun, this event is triggered. When an element is chosen, this function is triggered. When there is a mistake in retrieving media data, this event is triggered. When a document is loaded, this event is triggered. When a form is submitted, this event occurs. When the browser has been downloading media data but has stopped before the whole media file has been retrieved, this event is triggered. When the media’s playing position changes, this event occurs. When a document executes an undo, this event is triggered. When the user exits the document, this event occurs. Triggers when the volume of media is changed, as well as when the volume is set to “mute.” When media has stopped playing but is expected to restart, this event is triggered.

128   ◾    Conquering JavaScript

In this chapter, we discussed about the installation of Visual Studio Code and node js. We went through Vanilla JavaScript, Data Types and Operators, Functions, and Objects and Arrays. We also discussed Error Handling and Events.

NOTES 1 Choosing the Best JavaScript Editor From 7 Options: www.testim.io/blog/ best-javascript-editor-6-options/ Accessed on: 22 September 2022. 2 How to Setup Visual Studio Code for JavaScript: https://linuxhint.com/ set-up-visual-studio-code-for-javascript/#:~:text=Select%20all%20 the%20options%20you,Visual%20Studio%20Code%20will%20launch Accessed on: 22 September 2022. 3 How to Install Visual Studio Code on Linux: www.tecmint.com/installvisual-studio-code-on-linux/ Accessed on: 23 September 2022. 4 Installation of Node.js on Windows: www.geeksforgeeks.org/installationof-node-js-on-windows/ Accessed on: 22 September 2022. 5 Installation of Node.js on Linux: www.geeksforgeeks.org/installation-ofnode-js-on-linux/?ref=lbp Accessed on: 22 September 2022. 6 How to Create and Run Node.js Project in VS code editor?: www.geeksforgeeks.org/how-to-create-and-run-node-js-project-in-vs-code-editor/ Accessed on: 22 September 2022. 7 The Best VS Code Extensions for JavaScript Developers: https://livecodestream.dev/post/best-vscode-extensions-for-javascript/ Accessed on: 22 September 2022. 8 What Is “Vanilla JavaScript”?: www.javatpoint.com/what-is-vanilla-javascript Accessed on: 22 September 2022. 9 JavaScript Program to Print Hello World: www.programiz.com/javascript/ examples/hello-world Accessed on: 24 September 2022. 10 JavaScript—Syntax: www.tutorialspoint.com/javascript/javascript_syntax. htm Accessed on: 24 September 2022. 11 JavaScript Comment: www.javatpoint.com/javascript-comment Accessed on: 24 September 2022. 12 JavaScript Variable: www.javatpoint.com/javascript-variable Accessed on: 24 September 2022. 13 Javascript Data Types: www.javatpoint.com/javascript-data-types Accessed on: 24 September 2022. 14 JavaScript Operators: www.javatpoint.com/javascript-operators Accessed on: 24 September 2022. 15 JavaScript Operators: www.geeksforgeeks.org/javascript-operators/ Accessed on: 24 September 2022. 16 JavaScript If-else: www.javatpoint.com/javascript-if Accessed on: 24 September 2022.

Getting Started with JavaScript I   ◾    129 17 JavaScript—if...else Statement: www.tutorialspoint.com/javascript/javascript_ifelse.htm Accessed on: 24 September 2022. 18 JavaScript Switch: www.javatpoint.com/javascript-switch Accessed on: 24 September 2022. 19 JavaScript Switch Case—JS Switch Statement Example: www.freecodecamp. org/news/javascript-switch-case-js-switch-statement-example/ Accessed on: 24 September 2022. 20 JavaScript Loops: www.javatpoint.com/javascript-loop Accessed on: 24 September 2022. 21 JavaScript—For Loop: www.tutorialspoint.com/javascript/javascript_for_ loop.htm Accessed on: 24 September 2022. 22 JavaScript Objects: www.javatpoint.com/javascript-objects Accessed on: 26 September 2022. 23 JavaScript Array: www.javatpoint.com/javascript-array Accessed on: 26 September 2022. 24 JavaScript String: www.javatpoint.com/javascript-string Accessed on: 26 September 2022. 25 JavaScript Date Object: www.javatpoint.com/javascript-date Accessed on: 26 September 2022. 26 JavaScript Math: www.javatpoint.com/javascript-math Accessed on: 26 September 2022. 27 JavaScript—The Math Object: www.tutorialspoint.com/javascript/javascript_math_object.htm Accessed on: 27 September 2022. 28 JavaScript Number Object: www.javatpoint.com/javascript-number Accessed on: 27 September 2022. 29 JavaScript Boolean: www.javatpoint.com/javascript-boolean Accessed on: 27 September 2022. 30 JavaScript —Errors & Exceptions Handling: www.tutorialspoint.com/ javascript/javascript_error_handling.htm Accessed on: 27 September 2022. 31 JavaScript—Events: www.tutorialspoint.com/javascript/javascript_events. htm Accessed on: 27 September 2022.

Chapter

3

Getting Started with JavaScript II

IN THIS CHAPTER ➢ Asynchronous Development ➢ DOM Manipulation ➢ HTTP and Forms ➢ Working with APIs In the previous chapter, we covered Data Types and Operators, Functions, Objects and Arrays, Error Handling, Events, and in this chapter, we will discuss APIs and DOM.

HOW CAN WE BUILD AN ASYNCHRONOUS NODE.JS FUNCTION? In Node.js, write the asynchronous function with ‘async’ before the ­function name. As a consequence, the asynchronous method returns an implicit Promise. The async function aids in the asynchronous execution of promisebased code through the event-loop. A value is always returned by async functions. To wait for the promise, use the await function within the DOI: 10.1201/9781003356578-3

131

132   ◾    Conquering JavaScript

asynchronous function. The function is forced to wait until the promise produces a result.1 Install async from npm in Node.js using the command: npm i async

Using the require() function in our Node.js app, use async. Example 1 Write an asynchronous function in Node.js to compute the square of an integer. • Make a folder for our project. • To initialize the package.json file within the project folder, run the following command. npm init -y

• Use the following command to install async: npm i async

• Make a server.js file and add the following code to it. • Use npm start to execute the code. var async = require("async"); function square(k) {     return new Promise((resolve) => {         setTimeout(() => {             resolve(Math.pow(k, 2));         }, 2000);     }); } async function output(k) {     const ans = square(k);     console.log(ans);

Getting Started with JavaScript II   ◾    133 } output(10); var async = require("async"); function square(k) {     return new Promise((resolve) => {         setTimeout(() => {             resolve(Math.pow(k, 2));         }, 2000);     }); } async function output(k) {     const ans = await square(k);     console.log(ans); } output(10);

Example 2 Using await, write an asynchronous function to compute the sum of two integers within Node.js. To start a Node.js project, follow the steps outlined above. var async = require("async"); function square(j, k) {     return new Promise(resolve => {         setTimeout(() => {             resolve(j + k);         }, 2000);     }); } async function output(j, k) {     const ans = await square(j, k);     console.log(ans); } output(10, 20);

134   ◾    Conquering JavaScript

HOW DO WE WRITE AN ASYNCHRONOUS FUNCTION IN JAVASCRIPT? JavaScript is a synchronous, single-threaded language. The code is run one step at a time. However, in certain cases, JavaScript may seem to be asynchronous.2 Example



       

       

Getting Started with JavaScript II   ◾    135

Now, we can observe that after calling setTimeout(fd1, 100), our program does not wait for the timer to complete before proceeding to the next line. This happens because JavaScript adds the event to the event queue and continues running the program as usual if we wish to conduct an event. The engine checks the event queue on a regular basis to determine whether an event needs to be called or not. However, we may want our code to wait until a certain event or task is done before processing more instructions. Async, await, and promises are used to implement asynchronous functions. • async: The term “async” specifies an asynchronous function. Syntax async function Function_Name(){     ... }

• await: The “async” function includes “await,” which stops the “async” function’s execution. “await” can only use inside the “async” function. • Promise: A Promise is a value that acts as a proxy. It informs us about the asynchronous event’s success or failure. A Promise must include a resolve() or reject() call, or otherwise the Promise’s consumer would never know whether the Promise is fulfilled or not. If this occurs, the program will continue to wait for await and that code block will never be run again. There’s a lot more to Promise, but we can make Asynchronous work without knowing anything about it. Example Let’s recreate the same example using the Asynchronous function.

   

136   ◾    Conquering JavaScript    

       

Getting Started with JavaScript II   ◾    137

In the preceding example, the program waits for fd1() to finish before continuing. Until a Promise is obtained, the “await” command halts the execution of that code segment. Use resolve to fulfill the Promise (). It denotes that the Promise has been fulfilled. Similarly to resolve, we can use reject() to determine whether or not a Promise has been rejected. We don’t need to go into the reject() method right now since it’s mostly used for debugging and error purposes. Example We can include a value in resolve if we want the Promise to return one (variable).

       

       

Waiting for Multiple Promises What if we had to wait while a number of processes ran simultaneously? There are two methods that we can do this. Example We may write numerous await statements in a row.

       

       

140   ◾    Conquering JavaScript

Example The second option to wait for several Promises is to use Promise.all to execute the Promises in parallel (iterable object). Syntax: await Promise.all(iterable object);

       

       

Synchronous and Asynchronous in JavaScript Synchronous JavaScript As the name implies, synchronous means in a sequence, which means that each statement of the code is performed one by one. So, effectively, a statement must wait for the previous statement to be performed before proceeding.3 Let us look at an instance to better grasp this. Example

142   ◾    Conquering JavaScript

In the preceding code snippet, the first line of code, Hey, will be recorded first, followed by the second line, Mayank, and finally, the third line, after its completion How are you doing. As we can see, the codes operate sequentially. Every line of code waits for the one before it to be executed before it is run. Asynchronous JavaScript Asynchronous code enables the program to be run instantly, but synchronous code prevents continued execution of remaining code until the current one is completed. This may not seem to be a major issue, but when seen in context, it might result in the User Interface being delayed. Let’s look at an example of how Asynchronous JavaScript works.

In the preceding code snippet, the first line of code Hey will be logged first, followed by the second line Mayank, and finally, the third line will be recorded after its completion. How are you doing. As we can see, the codes operate sequentially. Every line of code waits for the one before it to be executed before it is run. Asynchronous JavaScript: Asynchronous code enables the program to be run instantly, but synchronous code prevents continued execution of remaining code until the current one is completed. This may not seem to be a major issue, but when seen in context, it might result in the User Interface being delayed. Let’s look at an example of how Asynchronous JavaScript works.

So, instead of performing the setTimeout function, the code first logs in Hey, then End, and then executes the setTimeout function. As usual, the Hey statement was logged in first. Because we execute JavaScript in browsers, there exist web APIs that manage these things for users. So, what JavaScript does is call the setTimeout method in such a web API, and then we continue to execute our code as normal. As a result, it does not obstruct the execution of any other code. Instead, it is pushed to the call stack and executed once all other code has finished. This is how asynchronous JavaScript works. Explain the Difference between Asynchronous and Deferred JavaScript In general, when we use a script element to load any JavaScript code, the browser pauses HTML processing and begins downloading the JavaScript file first.4 Until the browser has completely downloaded and processed the script, the HTML element’s script tag will not be activated. The browser waits for the script to be downloaded and run before continuing to analyze the remainder of the page. In current browsers, the script is often bigger than the HTML file, resulting in a greater download size and a longer processing time. This increases the page’s load time and limits the user’s ability to browse the website. Async and defer characteristics are used to fix this issue. Syntax: A standard script is supplied on the page as follows.

144   ◾    Conquering JavaScript

Asynchronous When the HTML parser discovers this element, it sends a request to the server to get the script. If the script has to be downloaded while the page is being parsed and displayed, the async functionality will do it in the background. When the script is downloaded, the HTML parsing is halted and the script is executed. When the operation is complete, HTML parsing will restart. The page and other scripts do not wait for async scripts, and they do not wait for them. It is ideal for both independent and externally located scripts.

Syntax:

Deferred The defer property instructs the browser not to interfere with HTML processing and to only run the script file once the HTML page has been completely processed. When a script with this attribute is discovered, the downloading of the script begins asynchronously in the background, and the scripts are only run once the HTML parsing is completed.

Syntax:

Asynchronous vs Deferred Asynchronous

Asynchronous prevents the page from being parsed.

Deferred

Deferred never obstructs the page.

Deferred scripts keep their relative order, Asynchronous scripts do not rely on one another. As a result, if a smaller script comes which implies that the first script will be second in the list, it will be loaded before the loaded first, followed by the others. prior lengthier script. Script execution begins with pause parsing. However, script execution begins only after parsing is complete but before the document’s DOMContentLoaded event.

Getting Started with JavaScript II   ◾    145

DOCUMENT OBJECT MODEL The document object is used to represent the whole HTML document. A document object is created when an HTML file is loaded into a browser. The html document is represented by the root element. It has characteristics as well as methods.5 We may add dynamic material to our web page using the document object. It is, as previously said, the object of window. So window.document  

is the same as document  

Across all platforms and languages, the W3C Document Object Model (DOM) provides an interface for dynamic access to and modification of a document’s content, structure, and style. Document Object Properties Let’s look at the document object’s properties that may be viewed and updated. text

anchor

textarea

checkbox document

form radio link select

reset

button

Document object properties

option

146   ◾    Conquering JavaScript

Document Object Methods We may use its methods to access and modify the contents of the document. The following are the most significant document object methods: Method

Description

write(“string”)

The specified string is written to the document.

writeln(“string”)

The specified string is written to the document, with a newline character at the conclusion. The element with the specified id value is returned. retrieves all entries with the specified name value. retrieves all items with the specified tag name. retrieves all entries with the specified class name.

getElementById() getElementsByName() getElementsByTagName() getElementsByClassName()

Document Object Accessing Field Value In this instance, we will get the value of the user’s supplied text. To access the value of the name field, we use document.form1.name.value. The root element here is document, which represents the HTML document. • form’s name is form11. • name is the name of the input text’s attribute. • the value property returns the value of the supplied text. Let’s look at a basic example of a document object that displays the user’s name along with a welcome message.                   Enter Name:              

Getting Started with JavaScript II   ◾    147

METHOD DOCUMENT.GETELEMENTBYID() IN JAVASCRIPT The function document.getElementById() retrieves the element with the supplied id. We used document.form1.name.value on the previous page to acquire the value of the input value. To access the value of the input text, we may use the document.getElementById() function instead. However, we must specify an id for the input field. Let’s look at a small document example.6 The getElementById() function returns the cube of the provided integer.             Enter No:
             

GETELEMENTSBYCLASSNAME() The getElementsByClassName() function is used to select or get items based on the value of their class name. This DOM function produces an array-like object containing all members of the supplied classname. When we use the getElementsByClassName() function on any element, it searches the whole document and returns just those elements that match the requested or provided class name.7 Syntax: var ele=document.getELementsByClassName(‘name’);  

The necessary parameter to be given here is name. It is the string that defines whether to match a single classname or many class names. Method getElementsByClassName() Example Let’s look at some instances to learn about and comprehend the method’s actual use.

148   ◾    Conquering JavaScript

Example It is a basic class implementation that, when the variable k is invoked, produces an array-like object.   The DOM Methods       This is a basic class implementation          

Similarly, we can use the getElementsByClassName() function to get element collections for various classes. Distinction between the Methods getElementsByClassName(), querySelector(), and querySelectorAll() • getElementsByClassName(): This method searches for items that match the supplied class name and provides a list of the elements that match. The items returned are a live HTML collection of elements. If the Document Object Model is changed, these live components will be updated. • querySelector(): This function returns a single element that matches the supplied classname. If no matching element is found, it returns null. The essential aspect to remember is that all of the methods mentioned above return either one element or a list, but the getELementsByClassName() function handles dynamic updates, while the other two handle static updates.

Getting Started with JavaScript II   ◾    149

METHOD DOCUMENT.GETELEMENTSBYNAME() IN JAVASCRIPT The function document.getElementsByName() retrieves all elements with the given name.8 The following is the syntax for the getElementsByName() method: document.getElementsByName(“name”)  

Example In this example, we’ll count the total number of genders. To retrieve all of the genders, we use the getElementsByName() function.             Male:       Female:                    

METHOD DOCUMENT.GETELEMENTSBYTAGNAME() IN JAVASCRIPT The function document.getElementsByTagName() retrieves all elements with the supplied tag name.9 The following is the syntax for the getElementsByTagName() method: document.getElementsByTagName(“name”)  

150   ◾    Conquering JavaScript

Example In this example, we’ll count the total number of paragraphs in the document. To do this, we used the document.getElementsByTagName(“p”) ­function, which returns the total number of paragraphs.      

This is the pragraph

     

We are going to count the total number of paragraphs by getElementByTagName() method.

     

Let’s look at a basic example

       count paragraph

Another Example In this instance, we’ll count the total number of h2 and h3 tags in the document.       This is the h2 tag       This is the h2 tag       This is the h3 tag       This is the h3 tag  

   

   

Getting Started with JavaScript II   ◾    151     This is the h3 tag       count h2       count h3  

THE INNERHTML IN JAVASCRIPT The innerHTML property is used to write dynamic html on an HTML document. It is typically used in web sites to produce dynamic html, such as registration forms, comment forms, and links.10 InnerHTML Property Example When the user activates the button, an HTML form will be generated. In this example, we’re dynamically creating the html form within the div with the id mylocation. This location is identified by using the document. getElementById() function.          

Example of a Comment Form Using innerHTML       First JS         Comment      

THE INNERTEXT IN JAVASCRIPT The innerText property may be used to display dynamic text on an HTML page. Text will be read as conventional text rather than html text in this case. It is usually used in web sites to produce dynamic content such as writing the validation message, password strength, and so on.11 Example of JavaScript innerText In this example, we’ll show the password strength when the key is released after being pressed.                   Strength:no strength        

5 METHODS FOR MAKING HTTP REQUESTS IN JAVASCRIPT Modern Javascript supports several methods for sending HTTP requests to distant services. Having so many alternatives for requesting and dynamically loading information in web applications, from the built-in XMLHttpRequest object to third-party libraries like Axios, has made it simpler than ever before.12 So, we’ll go through several methods for delivering HTTP requests in Javascript. Starting with the language’s native choices, we’ll look at the following five modules and send various forms of HTTP requests using them. • XMLHttpRequest • Fetch • Axios • SuperAgent • Ky XMLHttpRequest XMLHttpRequest is a Javascript native API that contains the mechanism of sending HTTP requests without the need to refresh a previously loaded web page (AJAX requests). Despite the fact that developers seldom use the XMLHttpRequest directly anymore, it is nevertheless the building component that functions behind many popular HTTP request modules. Understanding how to submit requests using the XMLHttpRequest method, for example, might assist us in dealing with unusual use scenarios if a third-party library does not support it. Here’s how we can use the XMLHttpRequest API to send GET queries and asynchronously receive data from a remote API:

154   ◾    Conquering JavaScript //creation of XMLHttpRequest object const xhr = new XMLHttpRequest() //open the remote server URL for the get request xhr.open(“GET”, “https://world.openfoodfacts.org/ category/pastas/1.json”) //send the Http request xhr.send() //the Event Handlers //triggered when response is completed xhr.onload = function() {   if (xhr.status === 210) {     //parse JSON datax`x     data = JSON.parse(xhr.responseText)     console.log(data.count)     console.log(data.products)   } else if (xhr.status === 404) {     console.log(“No records found”)   } } //triggered when network-level error occurs with request xhr.onerror = function() {   console.log(“The Network error occurred”) } // triggered on regular basis when client receives data //used to track the status of the request xhr.onprogress = function(e) {   if (e.lengthComputable) {     console.log(`${e.loaded} B of ${e.total} B loaded!`)   } else {     console.log(`${e.loaded} B loaded!`)   } }

As seen in this example, sending a GET request with XMLHttpRequest includes three steps:

Getting Started with JavaScript II   ◾    155

• Make an XMLHttpRequest. • Opening the indented type HTTP request. • Sending the request. Once the request is sent, we can handle its response using the event handlers supplied by the XMLHttpObject. We’ve utilized two event handlers in this case: onload, onerror, and onprogress. It is vital to remember that the onerror function only handles network-level requests problems. To discover HTTP problems, we must specifically examine the HTTP status code within the onload method. We may use XMLHttpRequest to send POST requests in a similar manner. // creation of XMLHttpRequest object const xhr = new XMLHttpRequest() // open the POST request xhr.open(“POST”, “/food”) // set the content-type header to JSON xhr.setRequestHeader(“Content-Type”, “application/ json”); // send the JSON data to remote server xhr.send(JSON.stringify(food)) // the Event Handlers // track the data upload progress xhr.upload.onprogress = function(e) {   console.log(`${e.loaded}B of ${e.total}B uploaded!`) } // trigger when data upload is finished xhr.upload.onload = function(e) {   console.log(“The Upload completed”) } // trigger when response is fully received xhr.onload = function() {   console.log(xhr.status) } // trigger due to the network-level error

156   ◾    Conquering JavaScript xhr.onerror = function() {   console.log(“The Network error occurred”) }

The primary difference between the previous GET and the present POST request is that when submitting JSON data, the content-type headers are explicitly specified. In addition, a POST request can generate an additional event type when compared to a GET request. They are upload events that may be accessed using the xhr.upload field. When the request body must convey a large quantity of data, these event handlers assist us in tracking the data upload process (e.g., images and files) Advantages of XMLHttpRequest

• All recent browser versions are compatible with the approach because it is natively supported. • This eliminates the requirement for external dependencies. • At the most basic level, it is possible to view and manipulate asynchronous HTTP requests. Disadvantages of XMLHttpRequest

• The code is rather verbose and lengthy. • There is no async/await or promise-based syntax support. • The majority of recent HTTP request packages give straightforward abstractions over the difficult XMLHttpRequest API. Fetch Fetch is a contemporary and streamlined native JavaScript API for making HTTP requests. It includes promise functionality and improves on the verbose syntax of the previously described XMLHttpRequest. Fetch has become one of the most common ways to send HTTP requests in JavaScript nowadays as an API designed with current application and developer needs in mind. As seen in this example, we can use Fetch to send HTTP requests from the client side by using a promise-based syntax.

Getting Started with JavaScript II   ◾    157 fetch(“https://world.openfoodfacts.org/category/ pastas/1.json”) .then(response => { // indicates whether response is successful (status code 200–299) or not if (!response.ok) { throw new Error(‘Request failed with the status ${reponse.status}’) } return response.json() }) .then(data => { console.log(data.count) console.log(data.products) }) .catch(error => console.log(error))

Fetch greatly decreases code complexity and verbosity by using simplified syntax and promises. Because the problems captured in the catch function belong to the network level, not the application level, we must utilize the ‘response.ok’ field in this implementation to determine if the response contains an HTTP error or not. The fetch function accepts a configuration object as the second parameter, allowing for easy customization of HTTP data like as headers, contenttypes, request method, and so on. The whole set of configuration options supported by Fetch may be seen in its official manual. Making POST requests using Fetch follows the same technique as in the previous example. In this case, we utilize the config object to indicate the request method and the data to be submitted. Let’s see how this works with async/await: async function postData () {     const food = {       name: “Rice”,       weight: 410,       quantity: 4     }       const response = await fetch(“/food”, {       method: “POST”,

158   ◾    Conquering JavaScript       body: JSON.stringify(food),       headers: {         “Content-Type”: “application/json”       }     })       if (!response.ok) {       throw new Error(`Request failed with the status ${reponse.status}`)     }     console.log(“Request is successful!”)   }  

Advantages of Fetch

• Provides a streamlined, native method for making HTTP requests in JavaScript. • Simple to understand and apply to any level of difficulty. • Allows us to create clearer, more succinct code by supporting promise-based implementation. • It improves upon XMLHttpRequest in many ways, including the ability to do no-cors requests and combine Request and Response objects with the built-in Cache API. Disadvantages of Fetch

• Some key XMLHttpRequest functionality, such as request abort and request progress monitoring, are missing. (However, a separate AbortController object may be used to govern request aborts and timeouts.) • Accepts a response even if there is an HTTP error. We must manually check for and handle HTTP problems. • Not compatible with Internet Explorer, but hopefully this is no longer an issue.

Getting Started with JavaScript II   ◾    159

Axios Axios is a well-known third-party program for performing HTTP requests in JavaScript. Under the hood, it collaborates with the native XMLHttpRequest API to provide a straightforward and comprehensive collection of functionality for handling specific challenges such as intercepting HTTP requests and delivering simultaneous requests. It, like Fetch, enables promises for dealing with asynchronous requests. When performing GET requests using Axios, we may compile the request using the specialized axios.get() function. We’ve presented an example of implementation here: axios.get(“https://world.openfoodfacts.org/category/ pastas/1.json”)   .then(response => {     // access the parsed JSON response data using the response.data field     data = response.data     console.log(data.count)     console.log(data.products)   })   .catch(error => {     if (error.response) {       //get the HTTP error code       console.log(error.reponse.status)     } else {       console.log(error.message)     }   })

Axios reduces the amount of effort required on our end to perform HTTP requests when compared to Fetch. The response.data property contains the interpreted JSON data. There is no need to explicitly check for status code before processing the response when using Axios since the catch method covers HTTP failures as well. Error.response checks, which remember the specific HTTP error code, allow us to classify incoming failures in the catch function. We utilize the specialized axios.post() function to send POST requests with Axios, as seen in the following example, which is built using async/await:

160   ◾    Conquering JavaScript async function postData () {     const food = {       name: “Rice”,       weight: 410,       quantity: 4     }       try {       const response = await axios.post(“/food”, food)       console.log(“Request issuccessful!”)     } catch (error) {       if (error.response) {         console.log(error.reponse.status)       } else {         console.log(error.message)       }     }   }

Axios simplifies this implementation once again by transforming Javascript objects to JSON without our intervention. These Axios methods use a last argument that specifies HTTP settings. Advantages Axios

• It has a basic, succinct, and simple-to-learn syntax. • Supports a diverse range of functionality not seen in many other accessible HTTP packages. These include intercepting HTTP requests, sending multiple requests at the same time, canceling sent requests, automated JSON data translation, monitoring request progress, and so on. • All major browser versions, including Internet Explorer, are supported. • Client-side XSRF protection is provided. Disadvantages Axios

• Because the module is not native, it adds an external dependence to the program.

Getting Started with JavaScript II   ◾    161

SuperAgent SuperAgent was one of the first third-party tools for performing HTTP requests in JavaScript. It, like Axios, implements the XMLHttpRequest API behind the hood and includes a complete set of functionality useful in a variety of request processing jobs. Both promise-based and callbackbased solutions are supported by the package. When sending HTTP requests using SuperAgent, we may use its specialized methods to launch a certain sort of request. As seen in this example, we can utilize the superagent.get() function to send GET queries. superagent   .get(“https://world.openfoodfacts.org/category/ pastas/1.json”)   .then(response => {     // get the parsed JSON response data     data = response.body     console.log(data.count)     console.log(data.products)   })   .catch(error => {     if (error.response) {       console.log(error.status)     } else {       console.log(error.message)     }   })

With the promise-based syntax, SuperAgent follows a similar approach to Axios for delivering GET requests. It automatically parses the response body into a JavaScript object without developer interaction. It also collects HTTP failures within the catch method, which are identified using the error.response field. In the event of a network issue, the columns labeled “error.response” and “error.status” will be blank. Similarly, we may send POST requests using SuperAgent. superagent   .post(“/food”)   .send(food)   .then(response => console.log(“Request is successful!”))

162   ◾    Conquering JavaScript              

.catch(error => {   if (error.response) {     console.log(error.status)   } else {     console.log(error.message)   } })

SuperAgent thinks the given data is in JSON by default and handles data transformation and content-type headers on its own. We utilize SuperAgent’s transmit() function to pass the data given with the POST request. Advantages of SuperAgent

• Offers a simple, promise-based approach for delivering HTTP requests. • It’s a robust and well-supported Javascript module. • Retries requests if a network or other transitory error occurs while making a request. • Allows for the extension of the package’s functionality through the use of a continually increasing list of plugins. These plugins provide functionality to SuperAgent such as mimicking fake HTTP calls, caching request and response data, queueing and throttling requests, and so on. • All major browser versions are supported. However, prior versions of Internet Explorer require the deployment of a polyfill to allow capabilities such as promise support. What does it matter at this point? Disadvantages of SuperAgent

• Adds an external requirement as the module is not native. • Monitoring request progress is not supported. Ky Ky is a new Javascript module that may be used to make asynchronous HTTP requests from a web application’s frontend. The native Fetch API is used as the foundation, but it has been enhanced with a clearer syntax and more functionality.

Getting Started with JavaScript II   ◾    163

Ky’s specialized HTTP methods have a straightforward syntax for making requests. Here’s an instance of a GET request sent using Ky and async/await. async function getData () {     try { const data = await ky.get(“https://world. openfoodfacts.org/category/pastas/2.json”).json()       console.log(data.count)       console.log(data.products)     } catch (error) {       if (error.response) {         console.log(error.response.status)       } else {         console.log(error.message)       }     }   }

POST requests can be sent in a similar manner: async function postData () {     try {       const response = await ky.post(“/food”, { json: food }) console.log(“The Request is successful”)     } catch (error) {       if (error.response) {         console.log(error.reponse.status)       } else {         console.log(error.message)       }     }   }

Advantages of Ky

• Provides a straightforward, lightweight, promise-based API for performing HTTP requests. • Supports request timeout, retry, and progress monitoring to address several restrictions in the native Fetch API.

164   ◾    Conquering JavaScript

• Hooks are provided for altering requests throughout their lifecycle: beforeRequest, afterResponse, beforeRetry, and so on. • All current browsers, including Chrome, Firefox, and Safari, are supported. Ky offers an alternate package, Ky-Universal, for Internet Explorer support; I’m not sure why they bother. Disadvantages of Ky

• In comparison to the other mature, diverse solutions covered in this essay, this is a very new package. This function adds an external dependence.

HTTP COOKIES A web cookie, also known as an HTTP cookie, is a little piece of data sent by the server to the online browser. The cookies may be stored by the browser and sent back to the server along with subsequent requests.13 Cookies are commonly used to detect repeated requests from the same site (browser). It assists the user in remaining logged in and tracking his data, such as user name and session. It’s also a good idea to keep track of the stateful information for the stateless HTTP protocol. If we are a developer, we cannot avoid cookies because they are necessary for session management and monitoring other user information. A cookie is as crucial nowadays as any other app functionality. Cookies facilitate various tasks for both the user and the programmer. Cookies have been around for a while and are still changing now. A cookie is just textual data about a web app. When a user visits a website, certain information is stored to the system’s local storage so that the app may recognize the user and display appropriate results if they visit again. When the user visits a website, the server requests the application’s home page, and when he performs a specific action, the server requests any other page of the application. So, if the user visits the 100th time, the request will be unique each time. Because server queries are so intense, saving data directly to the server is unfeasible; moreover, it may cause a server overload. Furthermore, if the user does not return, the information gathered will be outdated. As a result, in order to remember the user’s identity, the server transmits cookies with the response, which are saved to the system’s local storage. When the same client performs the same request again, the server will identify its identity and display the appropriate response.

Getting Started with JavaScript II   ◾    165

Cookies are unique to the server, thus even if the user has numerous cookies on their system, the server can identify its cookie. In this part, we shall cover the following cookie-related topics: • Cookies are used. • How Do Cookies Work? • Cookies generated by JavaScript. • Cookie Specifications. • Cookie Varieties. Utilization of Cookies The cookie is commonly used in the following ways: • Session Management: The cookie’s principal function is to handle user logins, shopping cart data, gaming scores, and anything else the server should remember the next time the user comes in. In general, session management enables the user to interact securely with the server via the application. Because the user continues to engage with the web application, each time they visit the website, they generate a new request. As a result, it makes it simple to follow their status and activities during the session. • Tracking Tracking is capturing user activity and evaluating their behaviors in order to tailor material for them. It tracks and analyzes their behaviors and interests, as well as the pages they visit. The time spent on a page or throughout the website during a session may be included in the tracking information. Because the user tracking contains sensitive information, the user should be aware of the hazards of accessing unsecured websites and, if feasible, avoid visiting such websites. • Personalization Cookies aid in the customization of user preferences, themes, and other settings. Most of the time, these settings are synced with a central database to personalize things for users the first time they log in. When the user signs in or restarts the program, the user customization saves information about the user’s preferences and settings for future use.

166   ◾    Conquering JavaScript

• Authentication Cookies are also essential for user authentication. When a user checks in, the server responds with the Set-Cookie HTTP header, which sets a cookie with a unique “session identifier.” The cookie is sent across the internet via the Cookie HTTP header the next time the same user requests the same website. As a result, the server can determine who made the request. How Do Cookies Work? Each time a user interacts with a website, a new request is made to the server, and each time he does any action within the program, a new request is sent to the server. Every new request submitted by a separate user was taken into account by the server. To identify requests from the same user, developers must include the cookie in the server’s response, which is kept in the system’s local memory. If the same user submits a request to the server, the server recognizes the user using cookies. The web browser is the client-side communication channel that sends requests from the client to the server. Once the cookie is added by the developers, the requests submitted by users are detected, and the server provides the answer based on the customization. Cookies are critical from the standpoints of both users and developers. It aids both parties in responding appropriately. Let’s look at how to make cookies with JavaScript. Cookies in JavaScript Let’s look at how to make cookies with JavaScript: Create Cookies When a request is received, the server may respond with one or more SetCookie headers. It will be saved in the system’s local storage. So, the next time when the browser sends a request to the server, it will also send the cookie along with the request. We may optionally set an expiration date or time period after which the cookie will be invalid and will not be transmitted. We may also apply some extra constraints to a specified domain and path to limit when the cookie is transmitted.

Getting Started with JavaScript II   ◾    167

To create, read, update, and remove cookies, JavaScript offers the document.cookie property. The syntax for creating a cookie is as follows: document.cookie=”cookiename=value”;  

An HTTP cookie can be generated in two ways. Cookies can be created on the client using the browser interface or added from the server in the file’s script section. To add from the client side, we may open the console and type the JavaScript code into the browser. Set-cookie headers can be included from the server side to generate one or more cookies. Let’s look at how cookies are created on both the client and server sides. Client Side To access the cookie from the client side, open the console in our browser and enter the following code: document.cookie=”mycookie=1”  

Using the web browser’s dev tool, we can also examine the cookies saved on the local system. To see if the cookie has been added, go to the dev tool’s application tab and pick the Cookies tab. Web Server Side To add the server cookie, we must create the cookie on an activity when the user visits the page. Consider the following scenario:                             Document           Set Cookie            

It will display a button component on our website page based on the preceding example. When we press the button, the requested cookie is created for our system storage. Similarly, we may construct the cookie with any other event listener. To set the cookie, we can alternatively add an onload event. Let’s look at few cookie properties: Properties of Cookies The cookie attributes are consistent across all sorts of cookies; the following are some of the typical cookie properties: Scope of Cookies The scope of a cookie specifies which URLs are transmitted with the cookie. Cookie scope is separated into two distinct attributes:

• Path The path is one of the properties that define a cookie’s scope. It defines a specified URL route in the HTTP header to transmit the cookie. To set the cookie to various routes, use the following code: document.cookie=”cookiefirst=1; path=/path1”   document.cookie=” cookiesecond=2; path=/path2”  

When we visit a website with the provided URL, such as example.com/path1, we will now submit a cookie header with the value “cookiefirst=1.” If we navigate to another URL, such as example.com/path2, we will submit a cookie header with the value “cookiesecond=2.” Except for the defined URLs, other requested routes will not transmit any cookie headers.

Getting Started with JavaScript II   ◾    169

• Domain The domain is the cookie’s second property. Domains function as a container for cookies. The cookie provides a unique domain name to itself, which assists the administrator in keeping the ­cookies ­particular and organized for each http request for web pages. An example of a domain-specific cookie is shown below: Domain=google.com will enable cookies for the domain google. com and its subdomains, including pasta.google.com. • Expires and Max-age A cookie’s “Expires” and “Max-Age” parameters define its lifetime or expiration date. They are classified as persistent cookies. With the exception of the term “permanent cookie,” the “Expires” property can remove a cookie on a certain date. Furthermore, the “Max-Age” characteristic deletes cookies after a given time. Session cookies, on the other hand, are destroyed when the ­current session expires. Some browsers allow us to choose when the current session will finish, which can be any length of time, including indefinitely. • SameSite The SameSite property enables us to set the cookie when a link within a page is clicked. We’ve spoken about how to establish http cookies for a certain URL, but what if we want to put the cookie on a link inside that direct URL? Using the SameSite, we may transmit cookies by clicking on a link from a redirected new page. We can instruct SameSite to transmit cookies in response to cross-site requests or if a user clicks on a link on a web page. Let’s have a look at an actual scenario where the SameSite property enables cross-site cookies. The flow chart below explains how cookies are transmitted and received while moving from one page to another. The user navigates to a URL (for example, google.com) They’ll get a first-party cookie. The user will go to google.com and click on the link that makes a retrieve request to another site, such as www.googleexample.com. Tutorialandexample.com will place a cookie with the domain name Domain=googleexample.com.

170   ◾    Conquering JavaScript

Google.com now stores a third-party cookie from googleandexample.com. With the following three values, the SameSite property defines whether third-party cookies are sent: • Strict The strict value for the SameSite property will only be transmitted through a first-party cookie context. Third-party cookies will not be considered. • Lax When a user hits a link with third-party navigation, the “Lax” value of a SameSite property is delivered. If the SameSite property is not explicitly specified on the third-party link, the default value is lax. • None If the SameSite property is set to “None,” cookies are transmitted in all contexts. We’ve spoken about cookies and their attributes; now let’s look at the many sorts of cookies: Varieties of Cookie Cookies are classified into the following kinds based on their usage and behaviors: First-Party Cookies First-party cookies are those that are transmitted to the system directly from the server of the website that we are viewing. The visited website stores these cookies directly on our computer. Most websites send cookies to their visitors in order to collect useful information and analytics in order to improve the user experience. Authentication is the greatest example of a first-party cookie. When a user registers in to an application, the server sends cookies to the client, which keeps them on the user’s local machine. We do not need to enter the login credentials again the next time you check in to the program. The website cannot identify the user without first-party cookies and will not automatically log us in or remember our choices from previous sessions.

Getting Started with JavaScript II   ◾    171

Third-Party Cookies The third-party domains to which we are redirected create third-party cookies. It is not created by the domain in which we are currently logged in. These cookies are typically used for tracking and can be retained even after the browser is closed. Ad tracking from websites is an excellent example of a third-party cookie. We may have noticed that after browsing a few products from various eCommerce sites, we will begin to see ads for those products. Because we may have been exposed to third-party cookies from a domain other than that specific website while browsing the products. When we close the browser or that specific website, a third-party cookie can be used to track our browsing details, such as which products you have seen and whether or not we have purchased them. After that, we’ll have to start receiving emails about those products and seeing advertisements from various ad agencies. Session Cookies Session cookies are transient cookies that are deleted when the user closes the browser tab. Session cookies are often utilized when a user inputs their login credentials and connects into an application. When session cookies are utilized, users must provide their credentials each time they attempt to log in to the application. The shopping cart management on an eCommerce site is a good example of a session cookie. Session cookies aid in the organization of a user’s shopping cart. If the site does not employ session cookies, users will have a more difficult time remembering the goods they have chosen. Secure Cookies The cookies include a Secure feature to prevent unwanted access from cookies given to a user as part of an HTTP response. When cookies are used in conjunction with the Secure property, all HTTP requests will contain the cookie only if it is communicated over a secure medium. In 2002, Microsoft Internet Explorer introduced HttpOnly cookies. Cookies with the HttpOnly flag can be included in a Set-Cookie HTTP header. The HttpOnly property decreases the possibility of users clicking on a malicious link that exploits cross-site scripting vulnerabilities.

172   ◾    Conquering JavaScript

In general, attackers attempt to inject malicious scripts into a trusted ­website in order to obtain cookies and other sensitive information stored on the local system. Zombie Cookies The zombie cookies’ names give us a hint. These cookies, like zombies, can come back to life after being killed. These cookies can be reactivated when the browser is closed or erased. Cookies from zombies can be stored anywhere other than the browser’s dedicated storage. In general, the zombie cookie can make a copy of the original cookie, store it somewhere else, and then reattach it to the user’s cookie storage. Few firms previously exploited the zombie cookie to track user activities and obtain personal information. Few states have prohibited the zombie cookie, which is considered an illegal violation of privacy.

FORM IN JAVASCRIPT We will learn, examine, and understand the JavaScript form in this session. We will also learn how the JavaScript form is implemented for various reasons.14 In this session, we will learn how to access the form, obtain elements as the JavaScript form’s value, and submit the form. Overview to Forms Forms are the foundation of HTML. In order to generate the JavaScript form, we need the HTML form element. The following sample code may be used to create a form:     Form of Login       LOGIN     USERNAME     PASSWORD  

 

Getting Started with JavaScript II   ◾    173        

In the program: • The form name tag is used to define the form’s name. The form is called “Loginform” in this case. This name will appear in the JavaScript form. • The action element specifies the action that the browser will do when the form is submitted. We haven’t done anything here. • When the form is to be sent to the server, the method to take action can be either post or get. Both techniques have their own set of properties and regulations. • The input type tag specifies the type of inputs that will be available in our form. We’ve set the input type to ‘text,’ which means we’ll enter data into the textbox as text. • Net, we’ve set the input type to ‘password,’ and the input value is password. • Next, we choose the input type ‘button,’ and when we click it, the form’s value is shown. Aside from action and methods, the HTML form element also provides the following helpful techniques. • submit (): The technique for submitting the form. • The reset () technique is used to reset the form values. Referencing Forms Now that we’ve established the form element with HTML, we need to connect it to JavaScript. To do this, we employ the getElementById () function, which refers to the HTML form element in the JavaScript code. The following is the syntax for utilizing the getElementById() method: let form = document.getElementById(‘subscribes’);  

174   ◾    Conquering JavaScript

We may make the reference using the Id. Submitting Form The onSubmit() function is then used to submit the form by sending its value. In general, we utilize a submit button to submit the value provided in the form. The submit() function has the following syntax:  

The action is executed shortly before the request is delivered to the server when we submit the form. It lets us to add an event listener to the form, allowing us to set multiple validations on it. Finally, a combination of HTML and JavaScript code is used to complete the form. Let us gather and use all of them to develop a Login form and a SignUp form, and then use both of them. Login Form     Form of Login       LOGIN     USERNAME     PASSWORD  

             

SignUp Form     SignUp Page       CREATE ACCOUNT                    
Name
Email
Set Password
Confirm Password
   
       

Getting Started with JavaScript II   ◾    177

VALIDATION OF JAVASCRIPT FORMS It is critical to check the user-submitted form since it may include incorrect information. As a result, validation is required to authenticate the user. Because JavaScript allows form validation on the client side, data processing is faster than server-side validation.15 JavaScript form validation is preferred by the majority of web developers. We can validate name, password, email, date, cell numbers, and other data using JavaScript. Example of Form Validation in JavaScript In this example, we’ll validate the name and password. The name cannot be blank, and the password cannot be less than seven characters long. On form submission, we validate the form. The user will not be sent to the next page unless the values entered are correct.                   Name:
      Password:
           

178   ◾    Conquering JavaScript

Password Retype Validation in JavaScript                   Password:
      Re-enter Password:
             

Number Validation in JavaScript Let us verify the textfield solely for numeric values. We’re using the isNaN() method here.             Number:
                 

Validation of JavaScript Using an Image Let’s look at an interactive JavaScript form validation example that shows the correct and incorrect image depending on whether the input is correct or incorrect.  

180   ◾    Conquering JavaScript                                  
Enter the Name:      
Enter the Password:      
       

Email Validation in JavaScript Using JavaScript, we can validate the email. To validate the email address, several criteria must be met, including: • The @ and. characters must appear in the email address. • Before and after the @, there must be at least one character. • There must be at least two characters following.(dot). Let’s look at a simple example of email validation.        

Getting Started with JavaScript II   ◾    181           Email:
                       

WORKING WITH JAVASCRIPT APIS An API is just a means of transferring data between interfaces. Assume we want to create an app that presents the user with real-time data retrieved from the server or even allows us to alter or add data to another endpoint. The API, or Application Programming Interface, makes this feasible.16 We’ll use a basic public API that doesn’t need authentication and lets us retrieve data simply querying the API with GET requests. https://randomuser.me/ is a website that supplies us with fake data for random users to work with. A request to https://randomuser.me/api/ will provide the result. The JSON answer that we receive is in the format shown below. {                                      

                                     

“results”: [     {         “gender”: “Mmale”,         “name”: {             “title”: “Mr”,             “first”: “Nitin”,             “last”: “Simka”         },         “location”: {             “street”: {                 “number”: 230,                 “name”: “Erakon Roadd”             },             “city”: “Jalandhar”,             “state”: “Punjab”,             “country”: “India”,             “postcode”: 121001,             “coordinates”: {                 “latitude”: “81.1327”,

182   ◾    Conquering JavaScript                     “longitude”: “104.4160”                 },                 “timezone”: {                     “offset”: “+7:00”,                     “description”:         “Ludhiana, Amritsar, Chandigarh, Moga”                 }             },             “email”: “[email protected]”,             “login”: {                 “uuid”: “bd0d135f-84df-4102-aa4f-5baaa41baf5c”,                 “username”: “redfrog722”,                 “password”: “abc”,                 “salt”: “q28gdiyN”,                 “md5”: “291987daea22bb91775226574925b271”,                  “sha1”: “a0463a26ea5c2ff4f3ad498fd01c 5994926e5021”,                 “sha256”: “6583eb74ca08bfac50b3b29aa52c9f02ea5d9d017fef0e5a5a 6fae4f5225f928”             },             “dob”: {                 “date”: “1998-10-01T23:10:09.403Z”,                 “age”: 40             },             “registered”: {                 “date”: “2015-02-02T02:26:52.904Z”,                 “age”: 7             },             “phone”: “(91)-234-7985”,             “cell”: “(51)-984-9443”,             “id”: {                 “name”: “SSN”,                 “value”: “847-09-2973”             },             “picture”: {                 “large”: “ https://randomuser.me/api/portraits/women/61.jpg”,                 “medium”: “ https://randomuser.me/api/portraits/women/61.jpg”,

Getting Started with JavaScript II   ◾    183   “                     }

              “thumbnail”: https://randomuser.me/api/portraits/women/61.jpg”           },           “nat”: “US”       }   ],   “info”: {       “seed”: “82a8d8d4a996ba17”,       “results”: 1,       “page”: 1,       “version”: “1.3”   }

Next, we’ll need an HTML file for the frontend, where you’ll show the obtained data. We can use the “div” tag (block-level) or the “span” tag (inline-level) as a placeholder for the data. We may obtain the needed “div/span” container where we need to insert the information by using the “id” property.



   





                                               
       
       

Getting Started with JavaScript II   ◾    189                                                                                                                                    
Age:
Gender:
Location:
Country:
   



If we want to learn more about APIs and delve further into them, visit Public APIs, which provides a large variety of publicly available APIs to help us on our API discovery adventure. To determine the type of answer sent by an API, Postman is a fantastic application that will meet all of our requirements. Another option is to use Postman APIs to perform the same action in the browser.

THE MOST WELL-KNOWN JAVASCRIPT LIBRARIES The most popular JavaScript libraries are listed here.17 jQuery jQuery is a traditional JavaScript library that is lightweight, quick, and feature-rich. John Resig constructed it during BarCamp NYC in 2006. jQuery is MIT-licensed free and open-source software. It makes HTML page manipulation and traversal, animation, event management, and Ajax easier. According to W3Techs, jQuery is used on 77.6% of all websites (as of 23rd February 2021). Features

• It offers a simple, minimalistic API. • It makes use of CSS3 selectors to manipulate style attributes and discover elements. • jQuery is small, needing only 30 kb to gzip and minify, plus it includes an AMD module. • It is simple to learn because its syntax is identical to that of CSS. • Plugins allow for more customization. • Versatility is provided through an API that works with different browsers, including Chrome and Firefox.

192   ◾    Conquering JavaScript

Use Cases

• CSS selectors are used to pick a node in the DOM based on certain criteria. These criteria contain the names of the elements as well as their properties (like class and id). DOM element selection using Sizzle (an open-source, multi-browser selector engine). • Effects, events, and animations are created. • Parsing JSON. • Development of Ajax applications. • Detection of features. • Asynchronous processing may be controlled using Promise and Deferred objects. React.js React.js (also called as ReactJS or React) is an open-source JavaScript frontend library. Jordan Walke, a software developer at Facebook, founded the app in 2013. It now has the MIT license; however, it was originally distributed under the Apache License 2.0. React was created to make creating interactive user interfaces as simple as possible. Simply create a basic display for each state in our program. Following that, it will render and update the appropriate component as data changes. Features • The React code consists of components or entities that must be rendered to a specific element in DOM using a React DOM library.

• It employs a virtual DOM by constructing an in-memory cache in a data structure, calculating the difference and efficiently updating the display DOM in the browser. • Because to this selective rendering, the app’s efficiency improves while developers save time recalculating the page layout, CSS styles, and full-page rendering.

Getting Started with JavaScript II   ◾    193

• It employs lifecycle methods such as render and componentDidMount to allow code execution at precise periods during the lifetime of an object. • It supports JavaScript XML (JSX), which blends JavaScript with HTML. It facilitates the visual presentation of components that contain nested elements, attributes, JS expressions, and conditional statements. Use Cases • Serving as the foundation for mobile or single-page apps.

• Rendering and managing a state for the DOM. • Creating effective user interfaces when creating web apps and interactive websites. • Easier debugging and testing. D3.js Another well-known JS framework used by developers for data-driven document editing is Data-Driven Documents (D3) or D3.js. In 2011, it was made available under the BSD license. Features

• It places an emphasis on web standards and provides modern browser capabilities without forcing you to use a particular framework. • A sophisticated data visualization tool is D3.js. • Support for HTML, CSS, and SVG is available. • Uses a data-driven method to modify the DOM. • A quick framework called D3.js makes a variety of dynamic behavior and datasets for animation and interactivity possible. • By reducing overhead, it permits more intricate graphics while still keeping high frame rates.

194   ◾    Conquering JavaScript

Use Cases

• Creating interactive and dynamic data visualizations. • DOM data binding and data-driven transformations on the data. A numbers array may be used to generate HTML tables, for example, and then D3.js can be used to generate an SVG bar chart or a 3D surface plot. • It may be used with a lot of modules because to its functional code. • D3 has a variety of tools for altering nodes, including declaratively changing styles or attributes, adding, sorting, or removing nodes, as well as altering text or HTML content. • To make animated transitions, complicated transitions using events, CSS3 transitions, and so on. Underscore.js Underscore is a JavaScript utility package that includes a number of functions for common programming tasks. Jeremy Askenas produced it in 2009 and released it under an MIT license. Lodash has now surpassed it. Features

• Its capabilities are comparable to those of Prototype.js (another famous utility package), although Underscore is designed for functional programming rather than object prototype extensions. • It includes about 100 functions that are classified into four kinds based on the datatypes they modify. These are the functions that can be manipulated: • Objects • Arrays • Arrays and objects both • Other features • Underscore works with Chrome, Firefox, Edge, and other browsers.

Getting Started with JavaScript II   ◾    195

Use Cases

• It offers functional tools like filters and maps, as well as specific functions like binding, rapid indexing, JavaScript templating, quality testing, and so on. Lodash Another JS toolkit that simplifies dealing with objects, arrays, strings, and numbers is called Lodash. Like Underscore.js, it was introduced in 2013 and uses functional programming. Features

• It makes it easier to write concise and manageable JavaScript code. • Mathematical operations, binding, throttling, decorating, constraining, debouncing, and other routine tasks are simplified. • Simpler string operations include camel case, trimming, and upper case. • Generation, modifying, compressing, and sorting of arrays. • Additional operations on collections, objects, and sequences. Use Cases Its modular approaches can assist us in

• Arrays, strings, and objects are iterated through. • Constructing composite functions. • Value manipulation and testing. Algolia Places Algolia Places is a JavaScript package that allows us to use address autocompletion on our website in a simple and widespread manner. It’s a lightning-fast and incredibly accurate tool that can assist improve our site’s user experience. Algolia Places uses OpenStreetMap’s outstanding open-source database to cover international locations.

196   ◾    Conquering JavaScript

Features

• It speeds up checkouts by filling many inputs at once. • We can easily utilize the nation or city selectors. • We may see results fast by presenting real-time link recommendations on a map. • Algolia Places can handle mistakes and present results appropriately. • It returns responses in milliseconds by automatically routing all inquiries to the closest server. Use Cases

• Allows us to include a map to display a certain place, which is quite handy. • It allows us to use forms more effectively. Anime.js One of the best JavaScript animation libraries is Anime.js, which we can use to create animations to our website or application. It was released in 2019 and is compact with a reliable yet straightforward API. Features

• DOM attributes, CSS properties, SVG, CSS transformations, and JS objects are all supported by Anime.js. • Works with a variety of browsers, including Chrome, Safari, Firefox, and Opera. • Its source code is simple to understand and apply. • Complex animation techniques like overlapping and staggered follow-through become simpler.

Getting Started with JavaScript II   ◾    197

Use Cases

• On attributes and timings, we may utilize Anime.js’ staggering mechanism. • Create layered CSS modifications with multiple durations over one HTML element at the same time. • Anime.js callbacks and controls functions are used to play, stop, trigger, reverse, and control events in a synchronized way. Animate On Scroll (AOS) For single-page parallax websites, Animate On Scroll is ideal. This opensource JS toolkit allows you to add nice animations to our sites that look great as we scroll down or up. It enhances our site design by allowing us to add fading effects, static anchor placements, and other features that will delight our users. Features

• The library can identify element locations and apply appropriate classes when they appear in the viewport. • It not only allows us to simply build animations, but it also allows us to adjust them in the viewport. • It works well on a variety of devices, including a mobile phone, tablet, and PC. • It has no dependencies because it is developed entirely in JavaScript. Use Cases

• Animate one element based on the location of another. • Animate items based on their position on the screen. • On mobile devices, disable element animations. • Create various animations such as fades, flips, slides, zooms, anchor placements, and so on.

198   ◾    Conquering JavaScript

Bideo.js Do we want to incorporate full-screen videos into the backdrop of our website? Try out Bideo.js. Features

• Using this JavaScript package, we can easily add a video background. • This feature looks great and works well on screens of all sizes and scales. • Videos can be resized depending on the browser used. • CSS/HTML makes it simple to implement. Use Cases

• To incorporate responsive full-screen background videos into a website. Chart.js Is our website or project relevant to the field of data analysis? Is it necessary to offer a large number of statistics? Chart.js is a fantastic JavaScript package to work with. Chart.js is a versatile and easy-to-use framework for designers and developers who want to quickly add stunning charts and graphs to their projects. It is open-source and licensed under the MIT license. Features

• Basic charts and graphs may be added in an elegant and straightforward manner. • As a result, responsive web pages are produced. • Loading is light, and learning and implementing is simple. • There are eight distinct sorts of charts. • Excellent for beginners. • Pages may be animated to make them more interactive.

Getting Started with JavaScript II   ◾    199

Use Cases

• When diverse datasets are employed, mixed chart types provide clear visual representations. • Plot sparse and complicated datasets on logarithmic, date, time, or user-defined scales. Cleave.js If we wish to format your text content, Cleave.js provides an intriguing approach. Its invention seeks to make it simpler to boost the readability of the input field by formatting the inputted data. To format text, we no longer need to mask patterns or use regular expressions. Features

• Improves user experience by providing consistent data for form submissions. • We may format credit card numbers, phone numbers, dates, times, and numerals in a variety of ways. • Custom blocks, prefixes, and delimiters should be formatted. • Supports ReactJS components, among other things. Use Cases

• Using CSS selectors, apply cleave.js to several DOM components. • To make changes to a given raw value. • To obtain the text field’s reference. • It is used in Vue.js, jQuery, and Playground with a redux form. Choreographer.js To efficiently animate complicated CSS, use Chreographer.js. It may even include more custom functions for non-CSS animations. Install its package using npm or add its script file to utilize this JavaScript library.

200   ◾    Conquering JavaScript

Features

• Its Animation class is in charge of managing individual animation data. • Each animation instance is configured through the animationConfig object. • There are two built-in animation functions: ‘change’ and ‘scale.’ • Scale is used to translate progressively measured values to a node’s style parameter. • The ‘Change’ command removes or adds style attributes. Use Cases

• Make instant scroll animations. • Create animations based on mouse movements. Glimmer Glimmer, which was released in 2017, has lightweight and fast UI components. It makes use of the robust Ember CLI and can be used as a component with EmberJS. Features

• Glimmer is a fast DOM rendering engine that may give exceptional render and update performance. • It is adaptable enough to function with our existing technological stack without needing us to rewrite code. Use Cases

• It may be used as a stand-alone component or integrated as a web component into existing systems. • Rendering of the DOM.

Getting Started with JavaScript II   ◾    201

• It aids in the differentiation between static and dynamic material. • When we want the functionalities of Ember but in a lighter package, use Glimmer. Granim.js Granim.js is a JS framework that allows us to build dynamic and fluid gradient animations. We may make our site stand out by using colorful backgrounds. Features

• Gradients can be used to cover pictures, work independently, slide beneath image masks, and so forth. • Gradient directions may be customized using percentage or pixel values. • Choose from diagonal, top-bottom, left-right, radial, and custom gradient directions. • Set the length of the animation in milliseconds (ms) with changing states. • Change the color and location of the gradient. • Image modification based on canvas position, source, scale, and so forth. • Other alternatives include setting callbacks, issuing events, gradient control methods, and so forth. Use Cases

• Making a simple gradient animation using three gradients of two colors. • Complex gradient animation with two gradients of three colors. • Gradient animation using a single backdrop picture, two colors, and a single blending mode.

202   ◾    Conquering JavaScript

• Using a single picture mask, create gradient animations beneath a given form. • Developing event-responsive gradient animations. fullPage.js fullPage.js, an open-source JS package, makes it simple to develop fullscreen scrolling webpages or one-page websites. It is simple to use and allows us to include a landscape slider inside our site sections. Features

• Provides several customization and setup possibilities. • JavaScript frameworks such as react-fullpage, angular-fullpage, and vue-fullpage are supported. • Allows for vertical as well as horizontal scrolling. • A responsive design that adapts to different screen sizes and browsers. • Page loads with auto-scrolling. • Lazy video/image loading. Use Cases

• To enhance the default functionality with the use of several extensions. • To build full-screen scrolling websites. • Making a one-page website. Leaflet Leaflet is one of the greatest JavaScript frameworks for incorporating interactive maps into our website. It is open-source and mobile-friendly, with a file size of roughly 39kb. Leaflet powers the interactive maps in the MapPress Maps for WordPress plugin.

Getting Started with JavaScript II   ◾    203

Features

• Performance improvements include mobile hardware acceleration and CSS support. • Tile layers, popups, markers, vector layers, GeoJSON, and picture overlays are all examples of unique layers. • Drag panning, pinch-zoom, keyboard navigation, events, and other interaction features. • Layer switcher, attribution, scale, and zoom buttons are all available on the map. • Browsers such as Chrome, Safari, Firefox, Edge, and others are supported. • Customization options include OOP, HTML and image-based markers, CSS3 controls, and popups. Case Studies

• Include a map with improved zooming and panning, smart polygon/ polyline rendering, modular design, and tap-delay mobile animation on our website. Multiple.js Several.js allows background image sharing across multiple items by utilizing CSS or HTML and does not require JavaScript coordinate ­ ­processing. As a result, it produces an eye-catching visual impact that encourages greater user involvement. Features

• Multiple backgrounds are supported. • Support for gradient opacity. • Many mobile and web browsers are supported.

204   ◾    Conquering JavaScript

Use Cases

• To distribute background images. Moment.js Moment.js assists us in successfully managing time and date while working with multiple time zones, API requests, local languages, and so forth. Dates and times can be streamlined by checking, parsing, formatting, or altering them. Features

• It supports a large number of worldwide languages. • Mutability of objects. • Several internal characteristics like as epoch shifting and accessing native Date objects, are available. • There are several suggestions for using its parser appropriately, such as strict mode, date formats, forgiving mode, and so on. Use Cases

• To include a time stamp in a published article. • Communicating with individuals from all around the world in their native tongue. Masonry Masonry is an outstanding JS grid layout framework. This library assists us in positioning our grid items based on the amount of vertical space available. It’s even utilized by some of the most popular WordPress picture gallery plugins. Consider how a mason fits stones when constructing a wall. Features

• The grid arrangement of masonry is built on columns and does not have a defined row height. • Optimizes web page space by removing unwanted spaces.

Getting Started with JavaScript II   ◾    205

• Sorting and filtering items while keeping the layout structure intact. • Effects of animation. • Dynamic components that alter the layout automatically for optimal structure. Use Cases

• To make image galleries with different image sizes. • List the most recent blog entries in many columns while keeping consistency, even if the summary lengths change. • To represent portfolio items such as photographs, designs, projects, and so on. Omniscient Omniscient.js is a JS package that provides React component abstraction for immediate top-down rendering with immutable data. Because it is efficient and has fascinating features, this library may help us construct our project smoothly. Features

• Reminds us of stateless React components. • User interface functional programming. • Component rendering from the top. • Immutable data is supported by Immutable.js. • Mixins provide tiny and composable components with shared functionality. Use Cases

• To give component keys. • Use auxiliary functions or constructs to communicate with parent codes. • Overriding elements. • Debugging and filtering.

206   ◾    Conquering JavaScript

Parsley Do we want to include shapes into our projects? If so, Parsley may be beneficial to us. It is a simple yet effective JS library for form validation. Features

• Its simple DOM API accepts input straight from HTML tags without requiring you to write a single line of JS. • Dynamic form validation is accomplished by dynamically detecting form alterations. • There are over 12 built-in validators, an Ajax validator, and various extensions. • We may modify Parsley’s default behavior and provide a more UI and UX focused experience. • Free, open-source, and extremely dependable, it is compatible with a wide range of browsers. Use Cases

• Making a basic form. • Performing difficult validations. • Creating forms with several steps. • Multiple inputs are being validated. • Taking care of promises and Ajax requests. • Creating excellent floating error labels by styling inputs. Popper.js Popper.js was intended to simplify positioning popovers, dropdowns, tooltips, and other contextual components that display near a button or other similar elements easier. Popper makes it easy to organize them, attach them to other site components, and make them work flawlessly on every screen size.

Getting Started with JavaScript II   ◾    207

Features

• A little library of roughly 3kb in size. • When we scroll inside the scrolling containers, the tooltip stays with the reference element. • Advanced customizability. • Uses a comprehensive toolkit to develop UIs, such as Angular or React, making integrations straightforward. Use Cases

• To create a tooltip from the ground up. • To neatly arrange these parts. Three.js Three.js can enhance our 3-D design experience. On contemporary browsers, it renders scenes using WebGL. If we are using IE 10 or below, try other CSS3, CSS2, and SVH renderers. Features

• Chrome 9+, Opera 15+, Firefox 4+, Internet Explorer 11, Edge, and Safari 5.1 are all supported. • Typed arrays, Blob, Promise, URL API, Fetch, and other JS capabilities are supported. • We may make a variety of geometrics, objects, lighting, shadows, loaders, materials, arithmetic components, textures, and so on. Use Cases

• To make a geometric cube, sphere, or other shape. • Making a camera or a scene. Screenfull.js To add a full-screen element to our project, use Screenfull.js. We will have no problems utilizing this JavaScript library because of its amazing cross-browser performance.

208   ◾    Conquering JavaScript

Features

• Make a page or element full-screen. • Hide cell phone navigation UI. • Using jQuery and Angular, add full-screen components. • Detects full-screen changes, mistakes, and so forth. Use Cases

• Including a full-screen feature on a website. • Screenfull.js in a document. • Toggling the full-screen mode and exiting. • Event management. Polymer Polymer, a Google open-source JavaScript toolkit, is used to create web programs with components. Features

• An easy method for creating custom components. • Properties computed. • Both one-way and two-way data binding are supported. • Gesture occurrences. Use Cases

• Using JS, CSS, and HTTP, you can construct interactive online apps using bespoke web components. • It is utilized by popular websites and services like as YouTube, Google Earth, and Play, among others. Voca The aim of Voca is to alleviate the agony associated with dealing with JavaScript strings. It includes handy functions for easily manipulating strings such as changing case, padding, trimming, truncating, and more.

Getting Started with JavaScript II   ◾    209

Features

• Because of its modular nature, the entire library or individual functions load rapidly while decreasing app construction time. • Provides utilities for cutting, formatting, manipulating, querying, and escaping strings. • There are no dependencies. Use Cases

• Voca may be used in a variety of settings, including Node.js, Webpack, Rollup, Browserify, and others. • To change the case of a topic to title case, camel case, kebab case, snake case, upper case, and lower case. • To uppercase and lowercase the initial character. • To enable an implicit/explicit chain sequence, construct chain objects to surround a subject. • To conduct various operations such as character counting, string formatting, and so on. We covered Asynchronous Development, DOM Manipulation, HTTP, and Forms in this chapter. We also talked about working with APIs and JavaScript libraries.

NOTES 1 How to Write Asynchronous Function for Node.js?: www.geeksforgeeks. org/how-to-write-asynchronous-function-for-node-js/?ref=lbp Accessed on: 28 September 2022. 2 How to Create an Asynchronous Function in Javascript?: www.geeksforgeeks.org/how-to-create-an-asynchronous-function-in-javascript/?ref=lbp Accessed on: 28 September 2022. 3 Synchronous and Asynchronous in JavaScript: www.geeksforgeeks.org/ synchronous-and-asynchronous-in-javascript/?ref=lbp Accessed on: 28 September 2022. 4 Explain Asynchronous vs Deferred JavaScript: www.geeksforgeeks.org/ explain-asynchronous-vs-deferred-javascript/?ref=lbp Accessed on: 28 September 2022.

210   ◾    Conquering JavaScript 5 Document Object Model: www.javatpoint.com/document-object-model Accessed on: 28 September 2022. 6 Javascript – document.getElementById() Method: www.javatpoint.com/ document-getElementById()-method Accessed on: 28 September 2022. 7 GetElementsByClassName(): www.javatpoint.com/javascript-getelementsbyclassname Accessed on: 28 September 2022. 8 Javascript – document.getElementsByName() Method: www.javatpoint.com/document-getElementsByName()-method Accessed on: 28 September 2022. 9 Javascript – document.getElementsByTagName() Method: www.javatpoint.com/document-getElementsByTagName()-method Accessed on: 29 September 2022. 10 Javascript – innerHTML: www.javatpoint.com/javascript-innerHTML Accessed on: 29 September 2022. 11 Javascript – innerText: www.javatpoint.com/javascript-innerText Accessed on: 29 September 2022. 12 5 Ways to Make HTTP Requests in JavaScript: https://livecodestream. dev/post/5-ways-to-make-http-requests-in-javascript/ Accessed on: 29 September 2022. 13 Http Cookies: www.javatpoint.com/http-cookies Accessed on: 30 September 2022. 14 JavaScript Form: www.javatpoint.com/javascript-form Accessed on: 30 September 2022. 15 JavaScript Form Validation: www.javatpoint.com/javascript-form-validation Accessed on: 30 September 2022. 16 Working with APIs in JavaScript: www.geeksforgeeks.org/working-withapis-in-javascript/ Accessed on: 30 September 2022. 17 The 40 Best JavaScript Libraries and Frameworks for 2022: https://kinsta. com/blog/javascript-libraries/ Accessed on: 01 October 2022.

Chapter

4

The Clearer Picture

IN THIS CHAPTER ➢ The various uses of JS • Frontend • Backend • Mobile • Gaming • Desktop ➢ Finding your Niche • Which framework to learn and when? • Combining JS skills with other programming languages Let us now spend some time discussing JavaScript ecosystem as a whole.

A JAVASCRIPT FRAMEWORK IS WHAT? A JavaScript framework is a group of prewritten programs designed to enable applications and give advantages that plain JavaScript cannot by itself. Consider a tent if the concept of frameworks is still unclear to us. We construct a frame to serve as the tent’s framework.1 The tent’s inside and outside may then be customized in anyway we choose. DOI: 10.1201/9781003356578-4

211

212   ◾    Conquering JavaScript

Naturally, JavaScript frameworks aren’t actual buildings like our tent, but the idea is the same. Let’s take a minute to address two frequently asked topics before moving on to the most well-known JavaScript frameworks. What Distinguishes a JavaScript Framework from a JavaScript Library? Libraries in JavaScript are collections of code created for certain use cases. For instance, the Day.js package is devoted to making use of dates in JavaScript, which may be challenging even for experienced developers. jQuery is a well-known JavaScript library that simplifies the syntax for DOM traversal, event handling, animations, and other typical operations. On the other hand, frameworks are designed to perform various tasks and serve as the foundation of a web application. Like Angular, several frameworks design the complete site tree. In other words, they support the full application frontend. Some, like Vue.js, allow for gradual usage, allowing our application to make restricted use of the framework. For particular use cases that our framework doesn’t handle, we’ll probably utilize libraries in our application. Remember those annoying dates with Day.js? This library is not required to be used in views that exclude dates. However, regardless of the functionalities we use, if our application is created using Angular, the page template is written in Angular’s syntax. In contrast, Day.js may be called where it is necessary and not called where it is not. Use a JavaScript Framework, But Why? Because frameworks are constructed on top of JavaScript, we can accomplish any function a framework does using standard JavaScript. But because the hard work has already been done, why go through all that bother again? This underlines the fundamental advantage of using a JavaScript framework: More capability without the need for us to produce new code. For instance, the virtual document object model is used by both React and Vue.js (DOM). Because it only updates altered HTML components, the virtual DOM is quicker at handling HTML elements. Contrarily, regular JavaScript will render the whole DOM once again regardless of the amount of the change.

The Clearer Picture   ◾    213

React and Vue.js are thus quicker for websites and programs that have a lot of interactive elements. Libraries and Frameworks for JavaScript In programming, frameworks and libraries are crucial. This raises the issue, nevertheless, which is superior: JavaScript libraries or JavaScript frameworks? One cannot replace the other nor is one better than the other. Nonetheless, a developer may choose which one to utilize based on the specifics of the project. Take into account the goals of the project you’re working on. What, for instance, is the scope of our project?2 This might help us remove libraries and frameworks that are inappropriate for smaller applications from our list of options. Overall, although both libraries and frameworks need a fundamental knowledge of JavaScript, frameworks often demand more JS expertise and experience, making the learning curve for libraries a bit less difficult. And which library ought to should we use first? React is a logical first library option since creating and maintaining complex user interfaces is a major component of frontend web or app development, which is where most web developers start. Additionally, organizations place a great value on React expertise. The React team also provides extensive documentation and has a sizable community. The fact that you begin with a JavaScript library like React JS or jQuery does not exclude us from subsequently learning JavaScript frameworks, however. On the contrary, if we start with one library, it will be a lot simpler to comprehend and ultimately go on to frameworks like Angular, Vue, or Ember JS. Although learning to code is a process, we must start. A programmer has access to the universal language known as JavaScript. Its libraries and frameworks are very beneficial to programmers working in the web development industry. A framework inverts program control, which is the primary difference between it and a library. It provides the developer with the necessary information. However, a library does not. A programmer instead calls the library as and when needed. Overall, JavaScript offers great aesthetics and functionalities and is utilized in the majority of modern apps. Due to its superior functionality and simplicity of use, it is favored by web developers all over the globe.

214   ◾    Conquering JavaScript

TOP 7 JAVASCRIPT FRONTEND FRAMEWORKS The best JavaScript frameworks for the contemporary web will be discussed first.3 1. React One of the most well-known open-source JavaScript frameworks is React, which was developed in 2013 by a Facebook software developer called Jordan Walke. On GitHub, the React community has received more than 180k stars. React is used and adored by around 40% of developers globally. Despite a minor decline in use satisfaction in 2020, React is still a popular option for new developers joining the IT industry. It is simpler to learn, has stronger community support, and is lightweight. Simform used React as well because of how lightweight it is to create a user-friendly component-driven frontend online application for the International Hockey Federation (FIH). How It Operates

• Developers may include HTML snippets into JavaScript files thanks to React’s usage of JSX. • The React library integrates seamlessly with state management, routing, and APIs. • The React library employs an in-memory cache to create a virtual DOM. The components’ prior and subsequent states are compared by the virtual DOM. Based on that, only components whose statuses have changed are rendered by the actual DOM. • Developers may nest by using the framework’s one-way data binding, which is a unidirectional flow of data. • When executing code, it makes use of lifecycle methods like componentDidMount. Real-life examples Popular websites like Facebook, Netflix, Asana, Pinterest, Airbnb, Reddit, UberEats, etc. have all been designed using React.

The Clearer Picture   ◾    215

Popular React Components

• Material UI: A beautiful UI design may be produced with the material UI set of react components. It has several features, including stylistic elements for making widgets like forms, navigation, and layouts. • React Semantic UI: Simple sentences are used by React Semantic UI to activate built-in functionality. Additionally, the interface has a wide variety of themes that provide developers total creative flexibility. • React Toolbox: It is a collection of React components created in SASS that follows Google’s guidelines for material design. To import SASS stylesheets, it makes use of CSS modules. The library offers adaptable and customizable solutions with easy integration with React webpack. Advantages

• Facebook supports communities. • Writing components without classes is possible. • Recognized for its reusable code components. • Suitable for beginners. Disadvantages

• There is insufficient and credible documentation. • Constant updates force developers to keep up with new developments. • Learning JSX syntax may be difficult. When Should We Utilize React? React is the most effective option for creating Single-Page Applications because of its Virtual DOM features (SPAs). Additionally, React has a strong community and is a great choice for creating complex apps.

2. Vue.js Vue.js is an open-source frontend framework created and maintained by Evan and his team that was first made available 7 years ago. These days, Vue.js is often used for lightweight frontend apps that must function on a

216   ◾    Conquering JavaScript

JavaScript framework. It came to the third place among frameworks in a Github poll done in 2021. By using this framework, close to 700k websites have been created. When developing code, Vue.js is a full framework that offers more flexibility. The framework is further renowned for its suitable size and quicker loading times. How It Operates

• Virtual DOM is used by Vue.js to provide state updates and modifications. • Both one-way and two-way data binding are supported by vue. js. Reactive two-way data binding is the term for this capability. It implies that React makes it simple to modify the data between a component class and its template. • The ecosystem of Vue.js is rich. We may still create hybrid mobile apps with Quasar Framework, NativeScript, or Ionic even if it lacks its own mobile framework. • JSX is also used by Vue.js. Vue.js can import and maintain customized components quickly by using JSX. • As it provides a variety of methods to apply transition effects, Vue. js is feature-rich with CSS transitions and animations. Users of Vue. js may make use of the transition wrapper, unique transition classes, JavaScript hooks, and other features. Real-Life Examples Popular businesses like Alibaba, 9gag, Xiaomi, and others have used Vue. js for all of their frontend needs. Popular Vue.js Components

• A Vue.js component library called Element UI has 500 active developers and strong community support. The component places a heavy emphasis on minute details, assisting both developers and designers in creating a beautiful and engaging user interface. • Unofficial Vue.js material design framework Vuetify enables you to build reusable, squeaky-clean components that are compatible with

The Clearer Picture   ◾    217

Server-Side Rendering, or SSR. Github now has 23k stars for it, and both the community and popularity are rapidly expanding. Over 400 people have contributed to the active Vuetify community, which has produced more than 20 plugins. • A UI kit based on the Bootstrap library is called Bootstrap Vue.js. Developers may use this kit with Vue.js to create responsive, mobilefirst apps using bootstrap version 4. The kit is jam-packed with a grid system, many UI elements, and themes. Advantages

• The framework is simple for new users. • Vue.js provides thorough documentation. • Two-way data binding is supported. • Is quite small and simple to incorporate. Disadvantages

• Lacks a wide variety of plugins to choose from. • The developer community is not very big. • No tech giant is supporting the framework. • Not appropriate for scaling. When Should We Utilize Vue.js? With Vue.js, we may use a framework that goes beyond a simple library and doesn’t complicate code. Vue.js is the answer if you’re searching for a forgiving design that yet keeps logic and view separate. It assists in developing SPAs or launching smaller initiatives in terms of apps. Vue.js is the finest alternative on the market if we want a variety of developer-friendly capabilities like tree-sharking, code-splitting, etc.

3. Angular Google created the TypeScript-based open-source web application framework known as Angular. This framework’s version 2 included fundamental components including dependency injection, asynchronous compiles, RxJS, etc.

218   ◾    Conquering JavaScript

It has become very popular among developers. Nearly 60% of engineers have actual experience working with the Angular framework, according to a poll by Ideamotive. Simform specialists also used Angular to create the FoodTruck Spaces online application. How It Operates

• A full-featured MVC framework is Angular. It helps in building an organized application. • The architecture provides data flow in both directions. Using the controller, this functionality allows Angular to link the DOM to the model data. We may listen to events and change the data between parent and child components concurrently using bi-directional data flow. • Despite its flaws, Angular’s environment is amazing. We may use the numerous out-of-the-box solutions it offers to build quick and effective applications. For instance, nothing has to be installed or configured in order to use server-side rendering with Angular. • All of the code components are very tested and reusable thanks to Angular’s hierarchical dependency injection functionality. • Due to its rapid mistake detection and useful feedback choices, Angular’s debugging is often less difficult. Real-Life Examples Numerous Google services have been created using Angular. Other well-known websites created using Angular include those from Forbes, LEGO, Autodesk, BMW, etc. Popular Angular Components

• The Angular component library Ngx-bootstrap is perfect for incorporating bootstrap components into your project. For improved efficiency and a responsive user interface, the bootstrap components are created using Angular. • Angular Material is a set of reusable UI components that draws inspiration from Google’s Material Design. This toolkit offers a wide range of UI design elements, responsive grid layouts, and different themes.

The Clearer Picture   ◾    219

Advantages

• The component-based design of Angular provides flawless model-toview synchronization. • Offers reusable, thoroughly tested components. • Angular has a sizable development community and is supported by Google. • Provides sophisticated features like dependency injection and directives. Disadvantages

• The structure doesn’t lend itself well to beginners. Users must get familiar with MVC before using the framework. • Restricted SEO abilities. • File sizes have increased significantly. When Should We Utilize Angular? Because it is a complete framework, Angular is appropriate for creating massive corporate applications. It also leverages MVC architecture, which enables smooth integration of sophisticated features.

4. jQuery Prior to the creation of contemporary JavaScript libraries and framework, jQuery dominated the IT industry. It is one of the first open-source JavaScript libraries and is lightweight and feature-rich, having been released in 2006 by John Resign. One of the best JavaScript frontend frameworks, according to experts. It is used by 95.5% of all websites that employ JavaScript, according to a W3Techs study. JavaScript scripts are recognized to be minimized by jQuery, which also provides strong assistance from its knowledgeable and mature community. How It Operates

• For its event handling skills, jQuery is well-known. Even user actions like mouse clicks and keyboard presses are condensed into little pieces of code for simpler administration.

220   ◾    Conquering JavaScript

• The syntaxes of jQuery and CSS are pretty similar. Beginners may thus get practical experience with the framework rather quickly. • The framework’s most recent iteration now comes with jQuery Mobile for creating scalable mobile apps. • It is a simple-to-use framework with a straightforward API that works with several browsers. • One of the lightweight frameworks supporting AMD modules is jQuery, which has a 30kb zip size for a blank project. By using AMD modules, you can manage our UI dependencies without using Download Builder. The module also helps us load the source code for jQuery UI using an exclusive AMD loader like RequireJS. Real-Life Examples Twitter, Microsoft, Uber, Pandora, SurveyMonkey, and other well-known companies have used jQuery in their apps. Popular jQuery Components

• A jQuery UI is a free library with a variety of UI elements for our next project. The library is an expansion of dynamic and interactive widgets that programmers may use to improve the user interfaces of their applications. Tree view, form widgets, color pickers, charts, RTL support, and other noteworthy elements are just a few. In addition, this library provides consistent performance across a range of browsers, platforms, and devices. • A jQuery-based widget library for jQuery mobile is called Wijimo. JQuery is used to power the tool, which results in greater performance. It offers more than 30 themes, support for RTL, video widgets, animation widgets, etc. Additionally, this widget is compatible with both online and mobile platforms. • A free plugin called Muuri allows us to build flexible layouts with jQuery. We have total control over the grid container’s location and dimensions thanks to the plugin. When working with jQuery to create an intuitive UI, developers may unleash their inner designers thanks to the freedom.

The Clearer Picture   ◾    221

Advantages

• All widely used web browsers are compatible with the framework. • Offer exemplary community assistance. • The learning curve for jQuery is not very severe. • Provides a huge selection of plugins. Disadvantages

• Because it contains all DOM events, effects, and AJAX components, the file size is enormous. • DOM APIs are dated. • Due to the lack of a data layer, DOM modification is a laborious and manual procedure. When Should We Utilize jQuery? jQuery is still the best option for delivering web-based and desktop JavaScript applications since it has cross-browser compatibility.

5. Svelte Svelte is a framework that is an open-sourced frontend compiler, while the majority of the frameworks on this list are complete frameworks or libraries. It was first shown in 2016 and quickly became well-liked by the developer community. More than 25k websites have been created using it as of right now. An application created using Svelte creates code to change DOM as it is only a compiler. It is one of the frontend frameworks that are lightweight as a result. How It Operates

• The MVC architectural concepts are used to segregate the template, logic, and view in the Svelte application. It enables numerous developers to collaborate on the same project at once.

222   ◾    Conquering JavaScript

• With Svelte, we can blend basic JavaScript with HTML, CSS, and TypeScript. • Svelte uses minimal resources since it doesn’t need anything extra to create a virtual DOM. It makes the total loading time of the program substantially faster. Real-Life Examples Many well-known companies have used Svelte to create their websites and benefited from its ease of use. A few examples are The New York Times, Absolute Web, Cashfree, Godaddy, and Razorpay. Popular Svelte Components

• Svelte Material UI is a collection of TypeScript-written Material UI elements. SASS is used to style the Svelte Material UI. Developers may create unique user interface components using a variety of widgets and tools provided by SMUI (Svelte Material UI). • Svelte-flow is a Flowbite-powered Svelte UI component that may help you design websites more quickly. Dark modes, buttons, modals, cards, a navbar, etc. are all included. • Carbon Components Svelte—It is the Carbon Design System, an open-source design tool developed by IBM. It has about 7,000 icons, 700 pictograms, 20+ charts, and other things. Advantages

• Code into vanilla JavaScript is converted. • The structure is quite light. • Provides support for component-based architecture. Disadvantages

• A little ecosystem. • There aren’t many Svelte tools on the market. • Is difficult to scale.

The Clearer Picture   ◾    223

When Should We Utilize Svelte? The USP of Svelte is simplicity. Svelte is best used for small-scale undertakings as a result. Its straightforward coding style makes it accessible to any beginner frontend developer.

6. Ember Ember is a free JavaScript framework that supports both MVVM and MVC architectures. It was first released in 2011. By using the capabilities provided by Ember, more than 70k websites have been created. One of the fastest rendering engines on the market, Glimmer, is the foundation around which Ember is based. Ember focuses primarily on creating web-based apps. However, Ember has developed over time and currently provides whole support for creating mobile-based apps. Ember is one of the most reliable frameworks and is ideal for creating scalable one-page apps. How It Operates

• Ember provides two-way data binding that instantly synchronizes display and model. • Through its server-side DOM rendering, Ember uses fastboot.js to enhance the efficiency of complicated user interfaces. • Ember’s community is one of the busiest ones around right now. • A large ecology exists in Ember. There is probably a plugin to make every function you ever find difficult to include easy. More than 1,500 add-ons are available for Ember to help anybody with their development endeavors. Real-Life Examples Ember was used by several well-known companies for their business requirements. Ember has been utilized by companies including Apple Music, Square, LinkedIn, Netflix, Twitch, and others. Apple Music is one of the notable instances of a desktop application built using Ember.

224   ◾    Conquering JavaScript

Popular Ember Components

• The process of transforming naming conventions into classes, methods, and templates is carried out by the well-known plugin Ember Resolve. Usually, this is beneficial when Ember has to resolve its dependencies. • Ember test helpers are a plugin that offers a number of utility methods to enhance your testing experience. DOM interaction helpers, routing helpers, rendering helpers, and other utility methods are included in the plugin. • Ember-concurrency is a condensed plugin for Ember.js that enhances the concurrency/async functionalities. We may use the task primitive it provides, which has several advantages including permitting cancellation and exposing the underlying data. Advantages

• Ember provides rendering on the server. • Both TypeScript and JavaScript are supported. • Ember features extensive and in-depth documentation. • It has a solid data layer that is incorporated. Disadvantages

• The structure may be a bit challenging for beginners. • There is no way to reuse components. • Provides no customization. • Not suggested for little tasks. When Should We Utilize Ember? Component-based design and the abundance of plugins at our disposal might be the ideal partners for creating complicated mobile apps or singlepage web applications.

7. Backbone.js Backbone.js is a JavaScript library that was released as an open-source project in 2010 by Jeremy Ashkenas. It is renowned for being portable.

The Clearer Picture   ◾    225

But for complete library compatibility, the framework largely relies on underscore.js and jQuery. Simform used the capabilities of backbone.js to create SenTMap, a sentiment analysis engine. How It Operates

• One of the key aspects of Backbone.js is the ability to divide business logic from user input logic. This aids programmers in creating an application that is properly structured. • Developers are urged by Backbone.js to turn data into models, DOM operations into views, and connect the two together via events. • The framework gives client-side web applications powerful APIs with enumerable methods. • Backbone.js automatically refreshes our application’s HTML if the architecture’s model changes. Real-Life Examples Backbone.js has been used by a number of well-known companies, including Uber, Pinterest, Reddit, Trello, and Tumblr, to fulfill application needs. Advantages

• There are more than 100 extensions offered. • The framework is simple for new users. • Very portable. • Data is kept in models rather than the DOM. Disadvantages

• There is no two-way data binding functionality. • At times, architecture seems to be complicated and hazy. • More boilerplate code must be written by us. • The developer community thinks that the framework is gradually getting outdated.

226   ◾    Conquering JavaScript

When Should We Utilize Backbone.js? Backbone.js may be used for larger projects and is best suited for basic single-page apps.

How Can We Choose the Ideal JavaScript Framework for Our Next Project? It is challenging to keep track of all the variations across frameworks. The harder part is deciding which one to employ for our project. Making the incorrect choice might be a terrible bet on our time and project money. Unfortunately, it is difficult to tell which framework is the greatest suit for us. Our company needs will determine the framework to use, but the following four considerations might aid in your choice. Team Proficiency The most common one is a framework, if there is such a thing. However, developers won’t be able to take full use of this framework if our current team isn’t at ease utilizing it. Choose a framework that our team has the greatest expertise with, or recruit remote workers to take advantage of market-leading frameworks. Backward Compatibility A frontend framework helps in coding the application, but the backend must also be taken care of. For an application to be completely functional, the frontend and backend must communicate smoothly. Choosing a frontend framework that complements your backend is a good idea if you have already established your backend. If not, we will have to deal with difficulties such as integration problems, compatibility problems, etc. Complexity Choose a framework based on MVC architecture if you’re creating a complicated web application with several sub-pages and capabilities. We will be able to divide your features into sections that can be developed concurrently by doing this. Our development time will be greatly shortened by doing this.

The Clearer Picture   ◾    227

However, using a lightweight framework to create complicated applications might be disastrous. A less robust framework cannot manage the complexity and will eventually experience several issues. Size and Functionality Ideally, a framework shouldn’t have a lot of features. Several frameworks may seem to be quite sophisticated yet are challenging to deploy. Focus on achieving maximum performance if we’re creating a straightforward system with few features. As a rule of thumb, you should aim for a happy medium between performance and size when designing a framework.

5 Backend JavaScript Frameworks The web is powered by JavaScript when it comes to web development. JavaScript is in charge of websites’ programmed behavior, including loading and reloading new page material without completely refreshing the page, animating page components, and verifying user input into online forms. HTML and CSS manage the style and data shown on a page.4 The popularity of JavaScript has led to the emergence of a wave of frameworks throughout time. For JavaScript developers, it feels like a new framework debuts every week, each claiming to be superior to the previous one. There is a constant need for these items since millions of websites depend on third-party JavaScript libraries and frameworks. What about the backend? We’ve previously covered some of the most well-liked frontend JS frameworks. Even while some frameworks are similar, it’s best to avoid mixing together front- and backend programming, particularly when using something as important as JavaScript. For instance, JavaScript is often used with server-side and other nonbrowser applications, which requires developers to approach their work fundamentally differently. 1. Next Although it first sounds a bit strange, the Next framework makes it incredibly simple to share JavaScript code across the project. This eliminates the need to write the same job in many languages of code. Nearly, the same component is used for displaying client-side markup and querying a datastore.

228   ◾    Conquering JavaScript

Everything about creating with Next becomes pretty intuitive once you master the fundamentals. ‘With Next, we get highly well-maintained documentation as well as the same setup simplicity as we do with projects like create-react-app. It is maintained by Vercel, a firm that was originally known as Zeit, and it contains a library of examples for almost every use case and integration that is currently in use. Their deployment platform is something we also like. Due to the fact that the API routes and pages we build are converted into lambda functions, Next was essentially built to be deployed with Now. In my opinion, developers may save a tonne of time by concentrating more on application problems rather than AWS console issues. Because we get a framework that handles server-side rendering, simple to configure API routes, and is generally a better create-reactapp, we believe we would prefer Next over Gatsby or other Node backend tools. They’re all beneficial in various ways, but because we tend to work alone on many projects, my choice for launching using Now seals Next for me. It is marketed as a fantastic framework for everything productionrelated, from TypeScript and built-in CSS support to code-splitting and packaging. Next.js is now up to version 9.5. The first edition was released in October 2016. 2. Express Express.js is a great option for developing online apps and server APIs, according to Kirill Onishuk, a full-stack web developer at OrangeSoft. Its quickness, simplicity, and flexibility provide all the capabilities required for creating both simple and complicated programs. Installing the necessary npm packages enables it to be readily extended, allowing for the solution of any issue. Express offers a layer on top of node.js that does not restrict its functionality, allowing us to use its features quickly as well. Because Express offers a wide variety of template engines, Onishuk said, ‘it is appropriate for creating apps with server rendering’ (for example, pug and handlebars). It has several HTTP service methods and intermediary handlers for API development.

The Clearer Picture   ◾    229

3. Gatsby Gatsby may be used without a server since the pages can be developed locally and then pushed to an object store and CDN, according to Up Hail’s founder Avi Wilensky (i.e., AWS S3 and Cloudfront). The design offers speedy performance while reducing expense and complexity. With a vast library of more than 2,000 plugins, Gatsby is also scalable. Gatsby, a React and GraphQI-based framework, works well for building relatively static webpages with services connected (via its plugins, of course). The fact that Gatsby does not do server-side rendering makes webpages created with it very quickly, but it may also be restrictive. 4. Node.js ‘At Riseapps, Node.js is the preferred JavaScript backend architecture. We choose this architecture mostly because it allows us full-stack JS development. This makes it easy to reuse code on both the frontend and the backend, which is a major benefit given how often we utilize React and Vue.js. A web application that uses JavaScript on bothends loads extremely rapidly and fluidly. ‘The applicability of Node for realtime applications, particularly those for communication, would be the next justification. A framework that makes software quickly responsive is essential as we develop several applications with calling and messaging features. Apps created with Node.js may also effectively manage numerous user requests. ‘At long last, this JS design enables the development of scalable apps. This framework’s nature makes the software it produces efficient and readily adaptable to changing needs. For developers of all stripes, Node.js provides a wide range of applications. In the context of AWS, where you may use it to launch EC2 instances, it is quite helpful.

230   ◾    Conquering JavaScript

It is used by businesses including IBM, Microsoft, Netflix, and Walmart as part of their infrastructure and web servers. In other words, you should study it if we want to work for a large organization that primarily relies on cloud infrastructure. 5. Meteor Another framework that resembles a platform a little more is Meteor. Christian Fritz, the company’s founder and CEO, provides an excellent summary: ‘Meteor has a package system, capabilities for building and deploying, and testing support. Even while it has certain features in common with other frameworks like next.js or gatsby, it is nevertheless unique in a number of important ways. The DDP protocol, which is exclusive to Meteor, is used for data synchronization. Simply described, DDP selectively synchronizes collections in the client-side minimongo database and the server-side mongo database. This eliminates the need for the developer to write API code for data transmission between the client and server, as I would if I were to use Express, and it does it in a very beautiful way: It uses reactive behavior on the client so that when new data comes, the page changes reactively using either React or another reactive framework. It only transmits patches, preventing the needless sending of repetitive data (Vue, Angular, Blaze). Although many users now utilize GraphQL to reduce the need to write API code, Meteor still stands out for its live and reactive characteristic of the data ‘just being there.’ This is ideal for any online application where users add to or modify material since it allows users to share their work in real time and smoothly with other users. ‘The other thing I haven’t seen in that form anywhere else yet is the possibility to create packages that have both a client and a server part. Account management is the finest illustration of how this functionality is important. For user management and authentication, a developer often has to choose two libraries—one for the frontend and one for the backend—and then figure out how to integrate them.

The Clearer Picture   ◾    231

There are several hazards and it typically needs the developer to understand a little bit more about both of the selected libraries than they would want. This is easy to do using Meteor. For example, if you install the ‘accounts-password’ package, you get a user database on the server with (hashed) passwords and the necessary UI with login/signup/forgot-password/etc. capabilities on the client, and all the communication is already taken care of. We may install further packages like ‘accounts-google’ for single sign-on with Google (and a similar package for Facebook or other social logins) just as easy. Because it is developed in Node.js and interacts with MongoDB, a well-liked cross-platform database engine, Meteor is very beneficial for developers creating business solutions.

THE EIGHT TOP JAVASCRIPT GAME ENGINES Scripting language JavaScript is cross-platform and interpretive. It is renowned for creating websites. It is also used in a lot of settings outside of browsers.5 Both client-side and server-side development can be done with JavaScript. This session will examine the top 8 JavaScript gaming engines that every JS developer should be familiar with. 1. PixiJS PixiJS is a 2D rendering library that is very quick and versatile. We can make interactive, aesthetically beautiful visuals using PixiJS, which also supports cross-platform apps. Without prior WebGL experience, programmers may use the Pixi renderer to take advantage of hardware acceleration (it also supports a Canvas Fallback). It does not, however, have a built-in physics engine. It is a completely free open-source library, and a very supportive community is what fuels its development. 2. Phaser The creation of cross-platform gaming apps is a breeze using Phaser. Amazingly, it employs both a WebGL and a Canvas renderer internally and can switch between them dependent on browser support. Canvas is used for devices that don’t support WebGL.

232   ◾    Conquering JavaScript

A sizable community of game creators using Phaser and a variety of plugins are both behind it. It is among the most popular gaming frameworks and engines right now on GitHub. For development, JavaScript or TypeScript may be utilized. 3. Babylon.js Babylon JS is a stunning, effective, and straightforward rendering engine. It provides programmers the ability to build nearly anything in your browser, from animated logos to fully interactive 3D games. Since it was created particularly for visualization, it isn’t really a rendering engine for games, but you can still create strong games with it. Due to its active and supportive developers, it has great community support. It has a playground so that you may experiment before moving further with development. 4. PlayCanvas WebGL Game Engine Without the requirement for a plugin, it leverages HTML5 and WebGL to run gaming apps and any other interactive 3D content on any mobile or desktop browser. This indicates that you will be using their platform to write code, test it, and set up your scenes by quickly exporting your games. In contrast to Babylon JS, it places more emphasis on the Game Engine than the Rendering Engine. The 3D rigid-body physics engine ammo.js makes it incredibly simple to add physics to your game. 5. Melon.js It is a highly effective, lightweight, and user-friendly HTML5 game engine that enables designers and developers to concentrate on content by including the well-liked Tiled map format. Its major goal is to provide a user experience without plugins (It needs nothing but an HTML5-capable browser to function). To guarantee minimal CPU demands, it uses lightweight physics. It is a free open-source project that is backed by a vibrant group of dedicated developers.

The Clearer Picture   ◾    233

6. GDevelop It is an open-source, fully functional game production tool with a primary emphasis on 2D game development, although it may be used to create any kind of game. Events is a tool that allows you to intuitively design the game logic without any prior knowledge of any particular programming language, and that is what distinguishes it from other game engines. The Web, Windows, Android, iOS, macOS, and Linux are just a few of the platforms on which GDevelop games may be published and played. It may be instantly exported to Android. 7. Kiwi.js For creating games that function in HTML5 browsers, an opensource game framework is very simple to utilize. Given that WebGL rendering has been increased, speed is its primary concern. For the purpose of distributing games to mobile devices as native applications, the Cocoon.js framework is used. 8. Three.js This project’s primary objective is to simplify WebGL use. You can work with WebGL with a lot less lines of code when using three.js. It supports Canvas 2D, CSS3D, and SVG renderers in addition to WebGL as the default renderer.

10 MAJOR JAVASCRIPT FRAMEWORKS FOR DEVELOPING MOBILE APPS JavaScript, which was formerly fundamental to the creation of dynamic webpages on the World Wide Web, is now a popular choice among app developers. Businesses and developers now have a streamlined option to create dynamic UI, with less lines of code, thanks to JavaScript frameworks for designing mobile applications. The amount of developers using JavaScript to create mobile applications has increased recently.6

234   ◾    Conquering JavaScript

There are hundreds of JavaScript frameworks to choose from for developing online, desktop, and mobile apps due to the language’s widespread use. Here are the top 10 JavaScript frameworks that let programmers create native and hybrid mobile applications that run on several platforms. 1. React Native In 2015, Facebook unveiled React Native, an open-source framework for creating native applications that can run on several platforms. Mobile applications developed using React and JavaScript are indistinguishable from those written in Objective-C, Swift, or Java. The React library, written in JavaScript, is used to construct user interface components for websites; React Native is an offshoot of this framework. When compared to the hundreds of other JS frameworks available, this one stands out due to its premium features, such as its declarative programming approach, virtual DOM, and reusable components to develop UI. In What Ways Is React Native Superior?

• To create scalable applications, developers may mix and match React Native code with native code written in Objective-C, Swift, or Java. • By contrast, developers who are well-versed in JavaScript will find learning React and creating React Native applications to be a breeze. • For the development of portable programs that can run on several platforms, check out this JavaScript framework. Because they share 80% of their code across the Android and iOS platforms, React Native apps save developers a tonne of time and effort when it comes to building complex mobile applications. 2. NativeScript NativeScript is a free and open-source framework for developing crossplatform native applications using Angular, Vue.js, TypeScript, or JavaScript. It enables web developers to use their existing skill set to create native mobile experiences.

The Clearer Picture   ◾    235

NativeScript allows developers to create native mobile applications using Vue CLI, VueX, and other Vue framework capabilities. NativeScript also combines with recent Angular full-stack capabilities including router support, code generation, interaction with the Angular CLI, and so on. Why Is NativeScript Used? NativeScript allows developers to use existing plugins from npm, CocoaPods (iOS), Gradle (Android), as well as hundreds of NativeScript plugins. A single codebase may be developed and distributed across different platforms (Android and iOS). Angular or Vue.js may be utilized for code sharing. Web developers may construct native mobile applications using their current web expertise (JavaScript, CSS, Native UI Markup).

3. Ionic Ionic is another well-known javascript framework for creating hybrid applications. Understanding the framework of an Ionic app is simple for developers who are familiar with web technologies and web app development. Users are unaware that hybrid applications are running in a full-screen browser called WebView. They may use native capabilities of mobile devices such as cameras and touch ID without connecting the core code to the device by using customizable native plugins. Why Is Ionic Used? A hybrid app codebase may be utilized across multiple platforms (Android and iOS), lowering development costs (as compared to native applications) and time to market. When developing hybrid applications with Ionic, developers may use Cordova plugins to access a mobile device’s hardware and software functionalities. Existing web development skills (HTML, CSS, and JavaScript) may be used to create mobile applications.

4. Apache Cordova Apache Cordova (formerly PhoneGap) is a hybrid app development platform that encapsulates HTML or JavaScript programs in a native container. A plethora of technologies, frameworks, and cloud services are available to improve Cordova’s speed.

236   ◾    Conquering JavaScript

Popular names include Visual Studio, Ionic, Framework7, Monaca, Mobiscroll, and others. Given the potential of Cordova, the contributors to this framework include tech titans such as Adobe, Microsoft, Blackberry, IBM, Intel, and others. Why Was Cordova Chosen? There is a large community of Cordova plugin developers. As a consequence, the framework enables developers to access a large variety of plugins, allowing them to access device functions and so expand the scope and size of the program. It is feasible to deliver code for several platforms (iOS, Android) with Cordova, making app development more cost-effective.

5. OnSenUI OnSen UI is a JS framework that allows you to create hybrid mobile applications using HTML, CSS, and JavaScript. Onsen UI is compatible with AngularJS and Angular 2+, React, Vue, and jQuery, allowing developers to transition between libraries and frameworks when creating interactive user interfaces. Why Use OnSen UI? OnSen UI includes a vast collection of sophisticated UI components that are particularly built for mobile applications. Monaca and OnSen UI get along swimmingly. Monaca provides a robust command-line tool and desktop interface to help with complex tasks.

6. jQuery Mobile With so many smartphones on the market, it is critical to be cautious while building a mobile application that not only loads quicker but is also customizable and usable across several platforms. When it comes to developing a faster-loading app, jQuery Mobile tops the list when compared to other frameworks. • Cross-platform apps may be created more quickly by developers. • It is a low-cost hybrid mobile app development.

The Clearer Picture   ◾    237

• HTML5 and CSS3 are utilized to create a more touch-friendly user interface. • Because it is a lightweight framework, the software loads quicker. • Navigation driven by Ajax with dynamic page transitions. • A consistent user interface across all platforms and devices.

7. Mobile Angular UI Mobile Angular UI is an HTML5 framework that uses AngularJS and Bootstrap 3 to create highly interactive mobile applications. If we like Angular, this is the Framework for us. This framework not only provides crucial mobile components such as switches, sidebars, and overlays, but it also assists the website in becoming responsive in the form of an application. • Aids in the quicker and easier binding of data. • Modifications will be reflected in the model immediately. • Reduces the load on server CPUs by facilitating caching and other tasks. • More rapid application prototyping.

8. Sencha Touch Sencha Touch allows you to tailor precisely how users interact with the program based on their preferences by adding a slew of features. Sencha Touch is a popular HTML-based framework used to design apps that run quickly on all platforms without the need to update the code for each one. • Provides apps with high-level responsiveness. • It works with the most recent versions of Android, iOS, and BlackBerry. • The program is loaded as quickly as possible.

238   ◾    Conquering JavaScript

9. Titanium Titanium, an ancient framework for hybrid mobile app development, gives straightforward and transparent access to most native capabilities. Developers may create native apps as well as hybrid and web apps using web technologies such as JavaScript and CSS. • Developers may quickly create apps that are compatible with Android, iOS, and other platforms. • Functional entities enable the development of high-performance applications. • Because it comes with an integrated environment, we can create rapid prototypes. • Open-source alternative that is very cost-effective. • Because it supports sophisticated web technologies, the code structure has been simplified. 10. Meteor Meteor is a platform that is free and open source. It is a popular JavaScript for mobile applications. This JavaScript framework not only allows for quick prototyping and cross-platform coding, but it also provides us control over our application. • JavaScript code may be modified without any programming knowledge. • Meteor is well-known for its speed and ease of deployment. • Removes bugs that most new programs seem to have. • Provides a lot of versatility between platforms and devices. • External libraries and a variety of plugins may be used.

THE BEST JS FRAMEWORKS FOR DESKTOP APPLICATIONS A cross-platform program is one that operates on many operating systems. This is incredibly handy for both the client and the developer: developing a cross-platform solution saves time and money, and makes the program simpler to maintain.7

The Clearer Picture   ◾    239

Desktop apps may also be cross-platform, but they need a unique methodology to account for all of the quirks of desktop PC operating systems. Are Cross-Platform Apps Interchangeable with Desktop Programs? The correct response to this question is ‘both’ and ‘neither.’ A cross-platform program, it seems, is a platform that works on several operating systems. This is incredibly handy for both the client and the developer: developing a cross-platform solution saves time and money, and makes the program simpler to maintain. Desktop apps may also be cross-platform (as discussed further in the article), but they need a unique methodology to account for all of the quirks of desktop PC operating systems. The cross-platform desktop app is a high-quality, quick system that satisfies the user and, as a result, provides considerable advantages to the client. The Advantages and Disadvantages of a Standalone Level vs a Cross-Platform App A standalone application is a software that runs locally on the device and does not need anything more than the required level to work. Because all logic is embedded inside the program, it does not need an Internet connection or any additional installed services or tools in most circumstances. A cross-platform application is one that adapts to and runs on several operating systems, as well as one that integrates online technology with tools for designing operating software for smartphones and desktop computers. Everything, however, relies on your goal: what is the objective of the application we are developing? Is the platform in need of upgrades, internet access, or hyperlinks? Can it stand alone as an introduction platform and so function without an online connection? Are Desktop Apps Supported by React and NodeJS? Yes will be the succinct response. But let us begin at the beginning. ReactJS is a free and open JavaScript library for building user interfaces. The method addresses the issue of partial updating of a web page’s content, which is faced in the creation of single-page apps. React is a powerful framework developed in JavaScript.

240   ◾    Conquering JavaScript

The open-source framework is used to create interactive interfaces for React desktop applications. ReactJS is ideally suited for handling the design layer of complicated apps, web apps, and even websites. Node.js allows us to execute JavaScript programs on the server and provide the results to the user. JavaScript has become a mainstream language with a significant developer community thanks to the Node.js platform. Node is a server-side framework that is powered by Google Chrome’s V8 JavaScript Engine. This open-source platform is also used to develop networking and backend applications. Node JS desktop apps are simple to use, high quality, and speedy. Top Five JS Frameworks for Desktop Applications (Desktop Apps) 1. Electron This is an open-source framework. GitHub built it 7 years ago for the editor of the JS desktop application Atom. This library will enable the development of a high-quality cross-platform desktop application. Electron makes use of web technologies such as JavaScript, HTML, and CSS. The Electron program has the benefit of allowing us to create desktop apps that function similarly to online applications while also allowing us to read and write data in our computer’s file system. The Electron framework was used to construct the desktop platform Skype for the Linux operating system.

2. NodeGUI This is another open-source framework for developing cross-platform desktop apps using CSS and JavaScript. It is possible to construct native apps with the aid of this framework. Here we will discover a collection of fee-based developer tools and widgets that may be used to construct built-in UI platform pieces. There is also a React-based variant.

The Clearer Picture   ◾    241

3. Proton Native This is a relatively ‘new’ program on the market. Proton Native allows you to create programs on the PC. This is comparable to what React Native did for mobile devices. We may use the framework to construct interfaces without interruption and manage the progress of cross-platform apps. This is what distinguishes Proton Native as one of the finest JS frameworks for creating apps for a variety of OS systems. Proton Native develops the program using just native tools, takes very minimal computer space, and does not use many resources. The framework employs the same syntax as React Native and is compatible with the React and Redux frameworks. Another benefit is that it is Node.js compatible. 4. NW.js This is also a good JavaScript framework for desktop apps. It is opensource Intel, which combines the Node.js framework with the Chromium engine, previously known as Webkit. With this high-quality combination, we can build an application on the NW.js framework that not only loads the local webpage in the program window but also connects to the operating system through the JavaScript API. This solution allows you to customize the size of windows, toolbars, and menu items. NW.js will also allow us to access files on our local PC. The framework supports all browser features and may secure our JavaScript source. NW.js is available for Linux, Mac OS, and Windows. 5. AppJS This is a simple-to-use yet very powerful tool for developing cross-platform apps. When developing an application, you do not need to learn a new language. If we know the fundamentals of HTML, CSS, and JavaScript, we can easily design applications for a smartphone. Because AppJS is built on Chromium, the developer has access to the most recent HTML5 APIs. AppJS may also be used to construct visually appealing apps ranging from word processors to 3D games. In the default mode, there are no GUI widget limits; therefore, the creation of user interfaces is now limited only by our creativity.

242   ◾    Conquering JavaScript

HOW TO SELECT THE BEST JAVASCRIPT FRAMEWORK FOR OUR PROJECT Many JavaScript frameworks are created and updated on a regular basis, making it difficult to stay up with the times and choose which framework is appropriate for our project. Before selecting any of these for our web application, evaluate the unique needs of our project as well as the framework’s strengths and limitations. IT businesses in Ukraine can assist with project creation and selecting the optimal framework.8 Before beginning project execution, it is typically required to undertake preliminary research to choose the best technology for our needs. Before beginning any project, it must be thoroughly analyzed and evaluated. However, there are several crucial factors by which we may estimate the choice of a particular technology for development in advance: Development Speed and Simplicity of Use, as well as Project Support The speed of development is determined by the technology utilized in our project. If your project already makes use of technologies such as TypeScript or JSX, Angular is a better fit. However, if we are beginning a project from scratch, Vue.js is the ideal choice because it adheres to standards. Trends These frameworks are well-liked and will take the lead in the development industry in the next few years. Vue, on the other hand, is fast gaining popularity, followed by the React framework. Scalability and Mobility If we’ve decided to move a project from one framework to another, Vue.js is the finest option. Because developers would most likely need to convert TypeScript or JSX code to standard JavaScript and HTML if they wish to rewrite Angular or React applications. The Frequency of Updates Another critical consideration is the frequency with which the framework is updated. Every 6 months, Angular is extensively upgraded. Vue is as reliable as it can be in this sense, with big changes every few years. This session will discuss the three most popular JavaScript frameworks, Angular, React, and Vue. They are the most well-known JavaScript frameworks nowadays.9

The Clearer Picture   ◾    243 Angular

React

Vue

If we are an extremely structured person who likes to keep everything distinct, Angular is for you. Each component and functionality has its own set of HTML, CSS, and TypeScript files.

If we want to have everything under the control, from the row of a table to the location of the buttons, and want to reuse components, then React is for us.

If we are a nice and clean person who prefers easy organization and does not want to navigate between files, the Vue with its extremely simple data binding is ideal for us.

If we don’t want to deal with the hassle of installing third-party packages, Angular’s built-in packages are ideal. This built-in package includes packages for routing and forms, among other things.

React allows us to install packages of our choosing for a variety of reasons. For instance, there are several packages available for routing, but whatever package we choose is determined by our expertise with the package. If the project is small to medium in scope and many components are reusable, we should select React for that type of project since component reusability and component-based thinking will enhance productivity significantly. The Redux framework may be used to manage data in React.

Vue includes some built-in packages as well, but we may easily add third-party packages based on our preferences.

If the project is fairly huge and there are many features to be created, then Angular is the way to go because it follows the MVC pattern, and managing the code for an Angular Project is quite simple. Data management is a key notion in Angular, and you can do it totally raw using RXJS, or we can utilize the NGRX framework and Akita as well.

Vue is utilized when the application is small to medium in size and speed and performance are the most important aspects of the project or application. In the case of Vue, we may handle the data via VUEX.

Which JavaScript Framework Should We Start With? That is dependent on our aim. To begin, decide whether we want to work on frontend or backend development. Are we interested in performing all of the functions of a web app and coding behind the scenes? Each JavaScript framework has its own official site where we may download and start using the product (for example, React.js or Node.js). Our framework classes will lead us through the following steps and how to use all of the capabilities.10

244   ◾    Conquering JavaScript

React.js React.js was the most extensively used web framework if you eventually want to focus on frontend programming. And it’s easy to see why React.js is a frontend favorite: it allows us to create scalable, dynamic, and interactive online apps. There is a considerable discussion regarding whether React.js is a ‘framework’ or a ‘library,’ which is a collection of previously published code that we may use to create our own code. Because both libraries and frameworks contain pre-written code that allows us to do anything, the small distinction may make our head spin. While both libraries and frameworks may be useful, frameworks often provide overall web programs with more structure. Node.js For those interested in backend programming, it’s ‘Node.js all the way.’ Node.js is a framework for developing desktop apps as well as a JavaScript runtime environment (which implies it runs a server in the language). Node.js can support asynchronous JavaScript code, which implies it can run programs while waiting for a longer-running job to finish.

JAVA VS. JAVASCRIPT JavaScript is a lightweight computer language that is utilized to make web webpages dynamic. It has the ability to inject dynamic text into HTML. The browser’s language is another name for JavaScript. JavaScript (JS) is not connected to or similar to Java. Both languages have a C-like syntax and are extensively used in client-side and server-side Web applications, but the similarities end there.11 JavaScript has the following features: • JavaScript was originally designed for DOM manipulation. Previously, websites were primarily static; but, with the advent of JS, dynamic Web sites were established. • In JS, functions are objects. They, like any other object, can have attributes and methods. Other functions can take them as arguments. • Date and time can be handled. • Although the forms are produced in HTML, it does Form Validation. • A compiler is not required.

The Clearer Picture   ◾    245

Example: This is the most basic JavaScript example.

Java is an object-oriented language of programming with a virtual machine platform that lets us develop compiled programs that run on almost any platform. ‘Write Once, Run Anywhere,’ Java promised. Java has the following features: 1. Platform Independence: The compiler turns source code to bytecode, which is subsequently executed by the JVM. This bytecode is platform-independent. 2. Object-Oriented Programming Language: Object-oriented programming is a way of structuring a program in which each object represents a unique instance of a class. The OOP concept is built on four pillars: • Encapsulation • Abstraction • Polymorphism • Inheritance 3. Simplicity: Java is a simple language because it lacks sophisticated features such as pointers, operator overloading, multiple inheritance, and explicit memory allocation. 4. Robust: The Java programming language is robust, which implies it is dependable. It is designed in such a manner that it makes every attempt to find faults as early as possible, which is why the java compiler can detect errors that other programming languages cannot. 5. Secure: Because we don’t have pointers in Java, we can’t access out-ofbound arrays; if we do, we get an ArrayIndexOutOfBoundException.

246   ◾    Conquering JavaScript

6. Distributed: Using the Java programming language, we may develop distributed applications. For developing distributed Java applications, Remote Method Invocation and Enterprise Java Beans are employed. 7. Multithreading: Multithreading is supported by Java. It is a Java feature that permits the concurrent execution of two or more portions of a program in order to maximize CPU usage. Example: Here we have a basic Java program as an example. // Import required classes import java.io.*; // the Main class class PFP {               }

             

// method of main driver public static void main(String[] args) {     // Print-statement     System.out.println(         “Welcome to Home”); }

The following is the distinction between Java and JavaScript

Java

VS

The distinction between Java and JavaScript

JavaScript

The Clearer Picture   ◾    247 Java

JavaScript

Because Java is a tightly typed language, variables must be declared before they may be used in the program. The type of a variable is verified at build time in Java.

JavaScript is a weakly typed language with permissive syntax and rules.

Java is a computer language that is object-oriented. Java programs may execute in any virtual machine (JVM) or browser.

JavaScript is a scripting language that is object-oriented. JavaScript code used to only run in the browser, but it can now run on the server thanks to Node.js. JavaScript Objects are built on prototypes.

Java objects are class-based, and we can’t write a program in Java without first establishing a class. The Java application has the file extension ‘.Java’ and converts source code into bytecodes that are then executed by the JVM (Java Virtual Machine). Java is a stand-alone programming language. Concurrency in Java is handled by threads. Multithreading is supported by Java. Java is mostly used for backend applications. Java consumes more RAM. To run the code, Java requires a Java Development Kit (JDK).

JavaScript files have the file extension ‘.js’ and are interpreted rather than compiled; every browser has a JavaScript interpreter for executing JS code. if it is incorporated into a web page at build time and combines with its HTML content Concurrency in JavaScript is handled by an event-based technique. Multi-threading is not supported by JavaScript. JavaScript is utilized for both the frontend and the backend. JavaScript makes use of less Memory. JavaScript may be executed in any text editor or browser terminal.

PYTHON VS. JAVASCRIPT We will discuss about the difference between Python and JavaScript below. What Is JavaScript? An interactive website can be written in JavaScript, a scripting language. In accordance with client-side programming principles, it executes locally within the user’s web browser, bypassing the requirement for server-side processing. JavaScript is also compatible with other technologies, such as REST APIs, XML, and more.12 These days, JavaScript also uses Node js and other modern technologies.

248   ◾    Conquering JavaScript

What Is Python? Python is an advanced, object-oriented language with a high level of usability. It’s great for creating apps quickly because of its pre-built data structures and dynamic binding and typing. Python’s module and package support further the system’s modularity and facilitates code reuse. Due to the low barrier to entry (line count), it is a rapid programming language. It’s perfect for newcomers because it prioritizes clarity and ease of use. Key distinctions between Python and JavaScript are outlined here. Differences of Most Significance • JavaScript is a scripting language that facilitates the creation of interactive web pages, whereas Python is a high-level object-oriented programming language that is suitable for quick application development due to its in-built data structures, dynamic binding, and typing. • Mutable and immutable data types exist in Python but not in JavaScript. • JavaScript requires UTF-16 encoding due to its lack of in-built functionality for handling raw bytes, but Python source code is ASCII unless a different encoding is specified. • Curly brackets are used in JavaScript whereas indentation is used in Python. • We may construct a property for a JavaScript object by composing its underlying attributes, and in the Python programming language, attributes are defined by use of the getter and setter methods. • JavaScript may be used to create a website or native app, but Python is better suited to more mathematically complex activities like data analysis, machine learning, and scientific computing.

The Clearer Picture   ◾    249

Features of JavaScript JavaScript’s primary capabilities are as follows: • It’s popular for both client and server-side development because of its portability between platforms. • Methodology that is well-suited to testing. • Quickly get started with coding and learn the language. • Gives us more options to rely on. Features of Python Python’s primary capabilities are as follows: • A breeze to pick up and keep in good shape • It has portability and uses the same interface regardless of the hardware platform it’s installed on. • The Python interpreter may be expanded using low-level modules. • Python’s robust framework and community make it a great choice for large-scale software projects. • Automatic garbage collection is a feature available in Python. • Tests and fixes may be performed in real time. • It allows dynamic type verification and provides access to high-level dynamic data types. • Python code is compatible with C, C++, and the Java programming languages. • Goroutines provide convenient support for several threads running at once. • Quick times for compilation • Simple-to-deploy, statically-linked binaries

250   ◾    Conquering JavaScript

Comparison between Python vs Java Script The primary distinction between Python and JavaScript is as follows:

JavaScript

VS

Python

The distinction between Python and JavaScript

JavaScript

Python

JavaScript does not understand the terms mutable and immutable.

Python supports both mutable and immutable data types.

Because JavaScript lacks built-in functionality for processing raw bytes, it should be encoded as UTF-16. JavaScript only supports floating-point integers.

Unless you provide an encoding format, Python source code is ASCII by default.

Curly brackets are used in JavaScript. JavaScript contains fewer modules such as date, arithmetic, regexp, and JSON. JavaScript objects contain properties that are made up of underlying attributes that allow us to specify a property. JavaScript employs an inheritance paradigm based on prototypes. JavaScript is a fantastic choice for mobile development in addition to frontend and backend programming. JavaScript may be used to create a website or a native application. TOBIE has a rating of 7. In the United States, the average annual income for a JavaScript developer is $114,856.

There are several numeric types in Python, such as int and fixed-point decimal. Python employs indentation. Python has a large number of modules. Getter and setter functions are used to define attributes in the Python programming language. Python employs a paradigm of classbased inheritance. Python is unsuitable for creating mobile apps. Python is used for data analytics, machine learning, and other mathintensive activities. TOBIE has a rating of 3. The annual compensation for a python developer is $120,255.

The Clearer Picture   ◾    251

JQUERY VS. JAVASCRIPT We will discuss about the difference between jQuery and JavaScript below: What Exactly Is jQuery? A free and open-source Javascript library for creating, navigating, and modifying the HTML DOM. A DOM is a tree-like structure used to represent webpage elements. jQuery allows web designers to quickly use JavaScript code on their websites. The sophisticated jQuery technique allows for the creation of powerful dynamic websites and online apps.13 jQuery’s syntax is intended to make things simple, such as • A document’s navigation • DOM element selection • Making animations • Event management • Creating Ajax apps Among all other libraries, jQuery is one of the most extensively used, with the following key features: • Selection of DOM elements • Sizzle allows for traversal and manipulation (the selector engine). • Developing a new programming style • DOM data structures and algorithms are combined. jQuery, on the other hand, enables developers to build plug-ins on top of the JavaScript library. Abstractions for low-level interaction and animations can also be created by developers.

252   ◾    Conquering JavaScript

The Distinction between jQuery and JavaScript Although jQuery is a component of JavaScript, the following variances may exist:

jQuery

VS

JavaScript

The distinction between jQuery and JavaScript jQuery

JavaScript

It is a library for JavaScript.

It is a dynamic and interpreted programming language for web development.

Only the relevant jQuery code has to be written by the user. It requires less time.

The whole js code must be written by the user. It takes longer since the entire screenplay must be written. Developers write their own code to handle cross-browser compatibility. Every browser has support for JavaScript. No other plugins are necessary. In JavaScript, jQuery is present. As a result, jQuery may or may not be used in the js code. The code might be difficult and lengthy. It is a programming method with weak typing. JavaScript, which introduced jQuery, is one of the most popular web design programming languages for developers. JavaScript creates DOM slowly.

Handling multi-browser compatibility concerns is not required. The header of the page must contain the URL of the jQuery library. Because it is a JavaScript library, it is dependent on JavaScript. It merely only has a few lines of code. It is a basic, quick, and easy method. jQuery is a web design method that has been optimized. DOM is created faster with jQuery.

JAVASCRIPT VS. PHP We will discuss about the difference between PHP and JavaScript below: What Exactly Is PHP? Adds support for the Hypertext Preprocessor. It’s the most popular web development language. It’s generally referred to be an open-source scripting language.14

The Clearer Picture   ◾    253

PHP code may be inserted in HTML documents. The code is written in-between the start and finish processing instructions. PHP is also a basic language for beginners. Although both PHP and JavaScript are utilized in web development, they serve quite distinct goals and perform very different jobs. PHP and JavaScript may even collaborate to accomplish a same objective in certain instances. When the two languages interact, JavaScript handles the frontend of the website while PHP handles the backend. However, when they operate separately, each may contribute significantly to web development. Most popular and trending websites, such as Facebook, Yahoo, and Flickr, are developed using a combination of JavaScript and PHP. The Distinction between JavaScript and PHP The following table compares and contrasts JavaScript with PHP.

JavaScript

VS

PHP

The distinction between JavaScript and PHP JavaScript

PHP

It is currently a full-stack programming language. It may therefore serve both client and server sites.

It is a scripting language for the server. It simply serves the website’s backend.

It is speedier, but it is more difficult to learn. It is an asynchronous language of programming that does not wait for input–output operations to complete. Every web browser, including Mozilla, Google Chrome, and many more, supports it. It contains less secure code. It requires an environment in order to access the database.

It is slower yet simpler to learn. It is a programming language that is synchronous. As a result, it waits for the input–output activities to complete. It is compatible with systems such as Windows, Linux, and Mac. IIS, Apache, and Lighttpd web servers all support it. PHP code is quite secure. It provides quick and easy access to the database. (Continued)

254   ◾    Conquering JavaScript JavaScript

PHP

The code is enclosed by          

App.jsx and main.js This is the first React component, sometimes known as the app entrance point. It will display “Hello, Everyone.”

App.js import React, { Component } from ‘react’;   class App extends Component{  

292   ◾    Conquering JavaScript    render(){         return(                           Hello Everyone                     );      }   }   export default App;  

Import this component and display it to our App’s root element so that it is visible in the browser. Main.js import React from ‘react’;   import ReactDOM from ‘react-dom’;   import App from ‘./App.js’;     ReactDOM.render(, document. getElementById(‘app’));  

Creation of .babelrc file Create a file named.babelrc and paste the code below into it.

.babelrc {       “presets”:[      “@babel/preset-env”, “@babel/preset-react”]    }  

Running Server After installing and configuring the application, we may start the server by using the following command. javatpoint@root:~/Desktop/reactApp>npm start  

It will display the port number that must be opened in the browser. After opening it, the output will be shown.

Frontend Development   ◾    293

Create the Bundle Now, produce the application’s bundle. Bundling is the process of integrating imported files into a single file, called a ‘bundle.’ This bundle may then be added to a website to load an application in its entirety. To construct this, we must execute the build command indicated below in command prompt. javatpoint@root:~/Desktop/reactApp> npm run build  

This command creates the bundle in the current folder (to which our application belongs) and displays it. 3. Use the Command create-react-app If we do not want to install react using webpack and babel, we may install react using create-react-app. The ‘create-react-app’ function is administered by Facebook. This is appropriate for novices who do not want to manually deal with transpiling technologies such as webpack and babel. This section demonstrates how to install React using the CRA tool. Install NodeJS and NPM NodeJS and NPM are the required development platforms for every ReactJS application. We may download NodeJS and the NPM package manager in the next chapter. Installation of React We may install React using the npm package manager using the command below. Do not stress about the potential difficulties of installing React. The necessary functionality is included in the create-react-app npm package. javatpoint@root:~/>npm install -g create-react-app  

Develop a New React Project After installing React, the create-react-app command may be used to build a new React project. Here, we pick the project name jtp-reactapp. javatpoint@root:~/>create-react-app jtp-reactapp  

294   ◾    Conquering JavaScript javatpoint@root:~/>npx create-react-app jtp-reactapp  

The above code will install react and generate a new project called jtpreactapp. This application includes the subfolders and files that will be shown by default. To begin, enter the src folder and make modifications to the required file. By default, files are stored in the src folder. For instance, we will open App.js and make the code modifications indicated below. App.js import React from ‘react’;   import logo from ‘./logo.svg’;   import ‘./App.css’;     function App() {     return (                                  

            Welcome Everyone.          

Get started, edit src/App.js and save to the reload.

         

                      Learn React                             );   }   export default App;  

Frontend Development   ◾    295

Running Server After installation is complete, we may start the server by using the following code: javatpoint@root:~/Desktop>cd jtp-reactapp   javatpoint@root:~/Desktop/jtp-reactapp>npm start  

COMPARISON BETWEEN ANGULARJS VS REACTJS We will discuss AngularJS and ReactJS below. AngularJS The open-source JavaScript framework AngularJS is used to create dynamic web applications. In 2009, Misko Hevery and Adam Abrons created AngularJS, which is currently maintained by Google.7 The most recent version of Angular as of March 11, 2019 is 1.7.8. It is mostly used for creating single-page applications and is based on HTML and JavaScript. It may be added to an HTML document using a        

Visit the VueJS home page at https://vuejs.org/v2/guide/installation.html and download the necessary version of vue.js. Production version and development version are the two versions available for use. As demonstrated in the accompanying screenshot, the production version is minimized but the development version is not. Debug mode and warnings will be supported by the development version while the project is being developed. By Using the CDN In our application, we may also utilize the Vue.js file from the CDN library. We may acquire the most recent version of Vue.js by using this URL in our application: https://unpkg.com/vue inside               {{ message }}              

In addition, we may get Vue.js via jsDelivr (https://cdn.jsdelivr.net/ npm/vue/dist/vue.js) and cdnjs (https://cdnjs.cloudflare.com/ajax/libs/ vue/2.4.0/vue.js). Example 2         Our first Vue app  

            {{ message }}              

By Using the NPM If we want to create a big-scale application with VueJS, NPM is advised. If we want to install Vue.js via the npm package, use the following line. It includes Webpack and Browserify in addition to other essential technologies that facilitate development. npm install vue  

By Using the CLI Command Line Additionally, we may use the CLI to install Vue.js and launch the server activation process. Using the CLI, run the following command to install Vue.js: npm install --global vue-cli  

The installation of Vue.js cli will take a little while. When finished, it will display the Vue.js CLI version. + [email protected]   added 238 packages from the 205 contributors in 346.282s  

Creating a Project with Webpack The command below may be used to start a Webpack project. Here, we’ll make a project called “myproject.” vue init webpack myproject  

We will be prompted to input Y/n at several points during this process. Type Y to continue.

Frontend Development   ◾    321

All requirements and the template will be downloaded automatically. We’ll notice a message following the successful creation of our project. Start the Project, Then the Server The project has now been started. Enter the project directory using the command below: cd myproject

The Server may be started by using the command: npm run dev

We can see that the Server is launched after executing the npm run dev command. Open Google Chrome or any suitable browser and execute localhost http://localhost:8080/#/ to launch our project.

UNDERSTANDING VUE.JS There are several ways to use and install Vue.js in our project, as we saw previous. This session will cover how to verify the Vue.js version, the benefits and drawbacks of utilizing Vue.js in our project, the first example, and an explanation of all the underlying concepts.17 Advantages of Using Vue.js Vue.js is among the most cutting-edge software frameworks for creating websites and single-page applications. The name suggests that the user interface (UI) or ‘view side’ of a project is where it is most often applied. Evan You (a former Google employee who was working on Angular at the time) created this framework so that rich client-side applications may be built with JavaScript. Let’s examine the advantages of integrating Vue.js into our project: The benefits of utilizing Vue.js include the following: Extremely Small in Size Small footprint is one of Vue.js’s main selling points. This interesting JavaScript plugin is only 18–21 KB, so it can be downloaded and used in no time at all.

322   ◾    Conquering JavaScript

Simple to Comprehend and Code The Vue.js framework has a very straightforward structure that is easy to grasp. It is one of the reasons for the framework’s popularity. We can simply develop in Vue.js if we are comfortable with HTML and JavaScript. Because of its basic structure, users may quickly include Vue.js in their web projects and construct apps. Integration with Existing Applications Is Simple Vue.js offers many components for everything and can be rapidly integrated with existing apps. It may be integrated with any JavaScript-based application. Nature Is Adaptable The flexibility of Vue.js also makes it simple to grasp for developers of React.js, Angular.js, and any other modern JavaScript framework. We have a significant amount of flexibility to use virtual nodes to create HTML files, JavaScript files, and pure JavaScript files. Components In Vue.js apps, we may construct reusable custom components. Documentation That Is Simple, Thorough, and Detailed Vue.js provides highly simple, extensive, and clear documentation, allowing developers with little knowledge of HTML and JavaScript to code with it. DOM Virtualization Vue.js employs virtual DOM, as do other existing frameworks such as ReactJS, Ember, and others. Virtual DOM is an in-memory tree version of the actual HTML DOM that may be modified without impacting the original DOM. Two-Way Communication Vue.js’s MVVM design allows for two-way communication, making HTML blocks relatively straightforward to manage.

Frontend Development   ◾    323

Companies That Use Vue.js Vue.js is gaining popularity as more and more well-known firms begin to employ it in real time. Several businesses are effectively utilizing Vue.js in the real world. Here are several examples: • Facebook: Facebook is the most successful corporation that uses Vue.js in their real-world projects. This framework is being used by Facebook for the marketing side of their Newsfeed. • Adobe: Adobe’s Portfolio product makes use of Vue.js. The organization has already moved its current software to the Vue.js framework, taking advantage of its ease of integration. • Xiaomi: Xiaomi is also employing Vue.js to construct its product catalog in order to give consumers a dynamic experience. • Alibaba: Vue.js has been adopted by Alibaba, one of China’s most important public corporations. Other famous firms that use Vue.js in their projects include: • Grammarly • Laracast • Behance • Netflix • Codeship • Livestorm • Gitlab • Euronews • Wizzair, etc.

324   ◾    Conquering JavaScript

Examine the Vue.js Version We Have Installed If we’re already familiar with Node.js and have the Vue.js CLI installed on our machine, we can use the Node.js command prompt to verify the version of our installed Vue.js: • Run the following command in the Node.js command prompt: vue --version  

• If it replies favorably, go to the next step in creating our new project. Vue.js version 2.9.6 is successfully installed in the preceding instance. To create a new project, use the following command: Syntax: vue create  

• To build an app called, use the vue create firstapp command. • We encountered an error stating that the vue create command is only compatible with Vue CLI 3, and we are using an earlier version. Now, use the command below to uninstall the previous version and install the new one. npm uninstall -g vue-cli npm install -g @vue/cli

• The outdated version of Vue.js is clearly removed. Install the newest version now. • The latest version of Vue CLI is now installed. The vue—version command may be used to determine the Vue CLI version. • We can see that the most recent Vue CLI version has been installed. Run the vue create firstapp command to make a new app named.

Frontend Development   ◾    325

INSTANCES IN VUEJS We must use the Vue method to create a new Vue instance in order to launch a Vue application. The main.js file’s default activation of the Vue instance occurs whenever we start a new Vue project. Another name for it is a root Vue instance.18 Syntax: var vm = new Vue({       // option     })    

The MVVM pattern informed the design of Vue’s application. To refer to our Vue instance, we must use the variable vm (short for ViewModel). When creating a Vue instance, we must include an options object. Let’s look at an illustration to see what the Vue constructor must provide. Indexs.html file:                                                 Firstname is: {{firstname}} Lastname is: {{lastname}}          {{mydetails()}}                            

326   ◾    Conquering JavaScript

Indexs.js file: var  vm = new Vue({       el: ‘#app’,       data: {          firstname : “Alisha”,          lastname : “Singla”,          address : “delhi”       },       methods: {          mydetails : function() {             return “I am "+this.firstname +” “+ this. lastname +” from “+ this.address;          }       }    })    

Let’s utilize a simple CSS file to enhance the output’s visual quality. Indexs.css file: html, body {       margin: 6px;       padding: 0;   }  

Example Explanation We can notice that we utilized a parameter named el in the example above. The id of the DOM element is carried by this ‘el’ argument. We have the id #app in the aforementioned example. The div element’s id is what is displayed in the Indexs.html file.  

Now, the logic of the aforementioned program will only have an impact on the div element and nothing else. We have defined the data object after specifying the id. We have specified certain values, including firstname and lastname, in the data object. The element contains a definition for this as well. For instance,

Frontend Development   ◾    327      Firstname : {{firstname}}      Lastname : {{lastname}}    

The Firstname: {{firstname}}value defines the first name of the data object’s stored data. When we run the program, the value assigned in the data object, Alisha, will be substituted inside the interpolation, i.e. ‘{{}}’. The same is true for the final name as the Lastname: {{lastname}} value provides the last name of the data object’s stored data. When you run the program, the value assigned in the data object, i.e., ‘{{}}’ Singla, will be substituted inside the interpolation. Following the definition of the data object, we have methods with a function named “mydetails” and a return value. It is also specified within the element as {{mydetails()}}  

As a result, we can see that within {{}} a call to the function mydetails is made. As we can see, the value returned in the Vue instance is printed within {{}}.

TEMPLATE IN VUE.JS In this, we will learn how to get an output on the screen in the form of an HTML template. Vue.js employs an HTML-based template syntax that allows Vue.js developers to declaratively connect the displayed DOM to the data of the underlying Vue instance. All Vue.js templates are valid HTML that can be processed by browsers and HTML parsers that support the standard.19 If we use the simple interpolation approach, i.e., double curly brackets, to display the HTML text on the web browser, the output will be incorrect. To fully grasp this notion, consider a simple example and examine the result. Indexs.html file:        

328   ◾    Conquering JavaScript       Vue.js Template                                             Firstname is: {{firstname}} Lastname is: {{lastname}}          {{htmlcontent}}                          

Indexs.js file: var vm = new Vue({       el: ‘#app’,       data: {          firstname : “Alisha”,          lastname : “Singla”,          htmlcontent : "This is the Vue.js Template Instance”       }     Let’s utilize a simple CSS file to enhance the output’s attractive appearance.

Indexs.css file: html, body {       margin: 6px;       padding: 0;   }  

In the above instance, we can see that the html content is not shown on the browser as we would like. The html content is shown in the manner we specify in the htmlcontent variable. This is not what we are looking for. We want it to appear in the browser as standard HTML text.

Frontend Development   ◾    329

To address this problem, we will need to employ the v-html directive. When we apply the v-html directive to the html element, Vue.js understands that it must output HTML content. Now, insert the v-html directive into the.html file and compare the results in the following instance. Syntax:  

Example 2 Indexs.html file:               Vue.js Template                                                      Firstname : {{firstname}}            Lastname : {{lastname}}                                      

Indexs.js file: var vm = new Vue({       el: ‘#app’,       data: {          firstname : “Alisha”,          lastname : “Singla”,          htmlcontent : "This is the Vue.js Template instance”       }    })  

330   ◾    Conquering JavaScript

In the above instance, we can see that the v-html directive correctly adds an HTML template to the DOM. Let’s look at how to add properties to the existing HTML components now. Attributes Should Be Added to HTML Elements Assume we have an image element in the HTML file and want to assign src, which is a Vue.js component. Consider the following: Indexs.html file:               Vue.js Template                                                      Firstname : {{firstname}}            Lastname : {{lastname}}                                                  

Indexs.js file: var vm = new Vue({       el: ‘#app’,       data: {          firstname : “Alisha”,          lastname : “singla”,          htmlcontent : "This is the Vue.js Template instance”,          imgsrc : “https://www.fiordalisa.ch/ wp-content/uploads/2017/12/IMG_40.jpg”       }    })  

Frontend Development   ◾    331

Example 3 Indexs.html:               Vue.js Template                                                      Firstname : {{firstname}}            Lastname : {{lastname}}                                                  

Indexs.js: var vm = new Vue({       el: ‘#app’,       data: {          firstname : “Alisha”,          lastname : “singla”,          htmlcontent : "This is the Vue.js Template instance”,          imgsrc : “https://www.fiordalisa.ch/ wp-content/uploads/2017/12/IMG_40.jpg”       }    })  

In this chapter, we covered installation, advantages, disadvantages, basic syntax of React, Express, and Vue.js.

332   ◾    Conquering JavaScript

NOTES 1 Frontend vs Backend: www.geeksforgeeks.org/frontend-vs-backend/#:~: text=The%20visual%20aspects%20of%20the,%2C%20Ruby%2C%20 Python%2C%20and%20. Accessed on: 11 October 2022. 2 The Best Guide to Know What Is React: www.simplilearn.com/tutorials/ reactjs-tutorial/what-is-reactjs Accessed on: 10 October 2022. 3 React Features: www.javatpoint.com/react-features Accessed on: 10 October 2022. 4 Pros and Cons of ReactJS: www.javatpoint.com/pros-and-cons-of-react Accessed on: 10 October 2022. 5 React Version: www.javatpoint.com/react-version Accessed on: 10 October 2022. 6 React Environment Setup: www.javatpoint.com/react-installation Accessed on: 10 October 2022. 7 Difference between AngularJS and ReactJS: www.javatpoint.com/reactjsvs-angularjs Accessed on: 11 October 2022. 8 Svelte vs React: Which JavaScript Framework Is Better?: www.turing.com/ blog/svelte-vs-react-which-javascript-framework-should-you-choose-in2022/#:~:text=Svelte%20is%20a%20free%20and,components%20to%20 design%20UI%20elements. Accessed on: 11 October 2022. 9 React JSX: www.javatpoint.com/react-jsx Accessed on: 12 October 2022. 10 Express.js Tutorial: www.javatpoint.com/expressjs-tutorial Accessed on: 12 October 2022. 11 Express.js: www.tutorialsteacher.com/nodejs/expressjs Accessed on: 12 October 2022. 12 Express.js: www.geeksforgeeks.org/express-js/ Accessed on: 12 October 2022. 13 The History of Node.js: www.section.io/engineering-education/history-ofnodejs/ Accessed on: 12 October 2022. 14 Node.js Basics: www.tutorialsteacher.com/nodejs/nodejs-basics Accessed on: 12 October 2022. 15 VueJS – Overview: www.tutorialspoint.com/vuejs/vuejs_overview.htm Accessed on: 12 October 2022. 16 Vue.js Installation: www.javatpoint.com/vue-js-installation Accessed on: 13 October 2022. 17 Getting Started with Vue.js: www.javatpoint.com/getting-started-withvue-js Accessed on: 13 October 2022. 18 Vue.js Instance: www.javatpoint.com/vue-js-instance Accessed on: 13 October 2022. 19 Vue.js Template: www.javatpoint.com/vue-js-template Accessed on: 13 October 2022.

Chapter

6

Backend Development

IN THIS CHAPTER ➢ Node.js ➢ MongoDB ➢ Server-side JS In the previous chapter, we covered frontend development, and in this chapter, we will discuss backend development.

WHAT IS BACKEND DEVELOPMENT? Server-side development is referred to as backend development. It focuses on databases, programming, and website design. It describes the operations that take place behind the scenes when a user performs any activity on a website.1 It might be logging into an account or completing an online transaction. Backend developers write code that allows browsers to interface with database information.

NODE.JS We will discuss introduction to node.js and its installation process below: What Is Node.js, and How Does It Work? Node.js is a fascinating combination of front- and backend technologies in the context of application stacks. Node.js is based on JavaScript, which DOI: 10.1201/9781003356578-6

333

334   ◾    Conquering JavaScript

is often used for the frontend, client-side of a web application; however, Node.js extends the capabilities of JavaScript so that it may run on the backend, server-side component of web application architecture or in a serverless architecture.2 The server-side processing is handled by Node.js’s native runtime environment. Node.js is similar to Java in that both languages have their own runtime environment in which to execute programs. Node.js is a runtime environment that is meant to be fast and lightweight, with features like non-blocking I/O and a package management that simplifies the process of creating applications. The Node.js package manager is known as npm. Its objective is to act as an index of libraries created by the Node.js developer community that can be readily shared and imported by other projects. These packages give useful answers to common functions and code, making it easier to construct new applications and improve existing ones. Why Should We Use Node.js? Node.js is a suitable option for a wide range of use scenarios. Node.js, as a predominantly server-side framework, lends itself to applications on the backend of the technological stack. Here are a few examples of why Node.js makes sense to utilize. Fast, Lightweight Applications with Real-Time Communication Understanding the size of your product is critical to selecting the appropriate technology to develop it with. Node.js’s flexibility and efficiency make it ideal for developing small, quick, and scalable apps. One example is real-time apps such as instant messaging and collaboration tools. This, along with Node.js’s quick synchronization capabilities, makes it suitable for event-based applications. WebSockets and WebRTC apps are examples of this. Serverless and Microservice Design Node.js is ideal for developing serverless and microservice-based applications due to its flexibility. These design choices are both highly popular for conserving resources and managing application lifecycles efficiently. Serverless architecture is popular due to its potential to reduce computing expenses by using only the resources required for the application to execute with no additional overhead. These are stateless and lightweight programs.

Backend Development   ◾    335

As a result, Node.js integration with serverless architecture is an excellent match. When the server demand is variable, there are npm packages for serverless design, and constructing a serverless Node.js application works well with an overall microservice architecture in C2C and B2C use cases. The Internet of Things Node.js excels at handling several connections at once. Because IoT is based on multiple devices generating little signals that must be handled rapidly, Node.js is an excellent backend for these types of applications, including serverless architecture and real-time communication capability. Processing of Audio/Video Node.js is considerably better at handling asynchronous input and output than other technologies. As a result, when paired with other media tools, Node.js may be used to process and handle multimedia data. A streaming configuration, for example, may be readily configured using Node.js. Quick Development Because Node.js is built on standard web languages, it is incredibly easy to use and has very short ramp-up times. New items may be developed swiftly and promptly brought to market. As a result, the quantity of engineering resources necessary to do so is lowered. This case study demonstrates how Node.js may assist in meeting tight deadlines. The product, an online marketplace for hail damage repair companies and customers, was supposed to go live before the peak season. When deciding between PHP and Node.js, we chose Node.js to match both functional needs and timeframes. We were able to cut development time by using isomorphic architecture. Code Integration with C++ Node.js may work in tandem with existing C++ libraries. This is due to the fact that the Node.js runtime is based on a C++ server that runs on the host node. As a result, Node.js can rapidly transport data between C++ and application code.

336   ◾    Conquering JavaScript

The Downsides of Node.js Heavy Calculation Activities Cause Performance Constraints Even today, the most significant limitation of Node.js is its inability to handle CPU-bound activities.3 But, in order to comprehend the underlying causes of this problem, we need some context. Let’s start with the fundamentals: JavaScript. Node.js, as we know, is a server-side runtime environment that runs JavaScript. JavaScript, as a frontend programming language, processes work on a single thread. Threading is not necessary since JavaScript tasks are lightweight and consume minimal CPU. Returning to Node.js, we now understand why it is deemed single threaded: It executes JavaScript in a single thread. A non-blocking input/output architecture means that Node.js responds to the client call to start a request and processes the job as soon as the callback is fired, as the task is ready. Node executes JS code on an event basis on its single thread while processing jobs asynchronously. That is referred to as an event loop. The issue arises when Node.js gets a CPU constrained task: if a big request arrives in the event loop, Node.js will set all available CPU to handle it first, before answering other requests queued. Because of the sluggish processing and overall latency in the event loop, Node.js is not recommended for intensive computing. However, with the 10.5.0 upgrade in 2018, multithreading was added as an experimental capability in Node.js. A new feature called the worker threads module allows you to employ extra threads from a thread pool to carry out CPU-bound activities. However, this is only possible on machines with several cores, because Node.js still enables us to use one core for one thread. This means that hefty parallel tasks can be run on a separate thread. This functionality is still experimental in Node.js version 12; however, it has been greatly improved. Callback Hell Is a Problem Because of its asynchronous nature, Node.js mainly relies on callbacks, which are routines that execute when each job in the queue is completed.

Backend Development   ◾    337

Keeping a multitude of queued jobs in the background, each with its own callback, may result in callback hell, which has a direct influence on code quality. Simply described, it’s a “situation in which callbacks are nested within other callbacks several levels deep, possibly making understanding and maintaining the code challenging.” However, this is sometimes interpreted as an indication of poor coding standards and a lack of knowledge with JavaScript and, in particular, Node.js. Tooling Immaturity Although the core Node.js modules are relatively stable and mature, many tools in the npm registry are either of poor quality or are not fully documented/tested. Furthermore, the register isn’t well-structured enough to provide tools depending on their ranking or quality. As a result, without understanding what to look for, it may be difficult to identify the ideal option for our needs. The fact that the Node.js ecosystem is primarily open source also has an effect. There Is a Growing Need for Skilled Experts Contrary to popular perception, not all JavaScript developers are also Node.js engineers. Mastering server-side JavaScript coding takes considerable work and an experience in backend development. The number of Node.js engineers is much smaller than the overall number of JS professionals due to the steep learning curve. As the buzz around Node.js grows, so does the need for skilled individuals in this industry. As a result, with millions of JavaScript engineers available, it may be difficult to locate a knowledgeable Node.js expert for our project. We definitely don’t want to limit our search to just one nation in this scenario. In the IT business, sourcing technical expertise from other countries has long been the standard.

338   ◾    Conquering JavaScript

Where Can We Use Node.js? Following are some examples of when Node.js has shown to be a valuable technological asset.4 • Applications that are I/O bound • Applications for Data Streaming • Data Intensive Real-time Applications • Applications based on JSON APIs • Applications on a Single Page Where Should We Not Use Node.js? Node.js should not be used for CPU-intensive applications.

SETUP OF THE NODE.JS ENVIRONMENT If we still want to set up our Node.js environment, we will need the two following software on our computer: (a) a text editor and (b) the Node.js binary installable.5 Text Editor This is where we will type our program. Some editors are Windows Notepad, the OS Edit command, Brief, Epsilon, EMACS, and vim or vi. On various operating systems, the name and version of the text editor may change. Notepad, for example, will be used on Windows, while vim or vi may be used on both Windows and Linux or UNIX. Source files are files that we produce with your editor that contain program source code. The source files for Node.js apps are usually suffixed with “.js.” Before we begin programming, make sure we have a text editor and enough expertise to develop a computer program, store it in a file, and then run it. Node.js Runtime The source code in the source file is only JavaScript. Our JavaScript code will be interpreted and executed using the Node.js interpreter.

Backend Development   ◾    339

The Node.js distribution is available as a binary installable for SunOS, Linux, Mac OS X, and Windows operating systems that support the 32-bit (386) and 64-bit (amd64) x86 CPU architectures. The section that follows will show us how to install the Node.js binary distribution on different operating systems. Get the Node.js Archive Visit https://nodejs.org/download to obtain the most recent installable archive file for Node.js. The versions that are available on various OS as of the time this guide was written are listed below. OS

Windows Mac Linux SunOS

Archive Name

node-v6.3.1-x64.msi node-v6.3.1-darwin-x86.tar.gz node-v6.3.1-linux-x86.tar.gz node-v6.3.1-sunos-x86.tar.gz

Installation on SunOS, Mac OS X, Linux, and UNIX Install and extract the node-v6.3.1-osname.tar.gz archive into /tmp according to the OS architecture for our computer, and then move the extracted contents into the /usr/local/nodejs directory. For instance: $ cd /tmp $ wget http://nodejs.org/dist/v6.3.1/node-v6.3.1linux-x64.tar.gz $ tar xvfz node-v6.3.1-linux-x64.tar.gz $ mkdir -p /usr/local/nodejs $ mv node-v6.3.1-linux-x64/* /usr/local/nodejs

Add the PATH environment variable to the path /usr/local/nodejs/bin. OS

Mac Linux FreeBSD

Output

export PATH=$PATH:/usr/local/nodejs/bin export PATH=$PATH:/usr/local/nodejs/bin export PATH=$PATH:/usr/local/nodejs/bin

Setup on a Windows Computer To install Node.js, use the MSI file and follow the on-screen instructions. The installer by default makes use of the Node.js package located at C:\

340   ◾    Conquering JavaScript

Program Files\nodejs. The C:\Program Files\nodejs\bin directory should be added to Windows’ PATH environment setting by the installation. Any open command windows must be restarted for the modification to take effect. Executing a File Will Verify Installation Create a main.js file with the following code on our computer (Windows or Linux). /* Hello, Everyone! program in node.js */ console.log(“Hello, Everyone!”)

To view the outcome, run the main.js file using the Node.js interpreter now. $ node main.js

FIRST APPLICATION OF NODE.JS Let’s first look at the components of a Node.js application before building a real “Hello, Everyone!” application. The following three crucial parts make up a Node.js application: • Import required modules: Use the need directive to load the necessary Node.js modules. • Create server: Create a server that responds to client requests in a manner similar to the Apache HTTP Server.6 • Read request and return response: The server constructed in a previous stage will read the HTTP request sent by the client, which can be a browser or a console, and deliver the response. Creation of Node.js Application Step 1: Import the necessary module. The following is how we load the http module using the need directive and save the resulting HTTP instance into an http variable: var http = require(“http”);

Backend Development   ◾    341

Step 2: Create a server Using the newly formed http instance, we execute the http.createServer() function to create a server instance, and then we bind it to port 8081 by using the server instance’s listen method. Send it a function with request and response arguments. Make the example implementation return “Hello Everyone!” every time. http.createServer(function (request, response) {     // Send HTTP header     // HTTP Status: 200 : OK     // Content Type: text/plain     response.writeHead(200, {‘Content-Type’: ‘text/ plain’});         // Send response body as “Hello Everyone!”     response.end(‘Hello Everyone!\n’);  }).listen(8081);    // Console will print message  console.log(‘Server running at http://127.0.0.1:8081/’);

The aforementioned code is sufficient to build an HTTP server that listens on the local machine’s port 8081, or waits for a request. Step 3: Testing Request & Response. Let’s combine steps 1 and 2 in a file named main.js and launch our HTTP server as seen below. var http = require(“http”); http.createServer(function (request, response) {    // Send HTTP header    // HTTP Status: 200 : OK    // Content Type: text/plain    response.writeHead(200, {‘Content-Type’: ‘text/ plain’});        // Send response body as “Hello Everyone!”    response.end(‘Hello Everyone!\n’); }).listen(8081);

342   ◾    Conquering JavaScript // Console will print message console.log(‘Server running at http://127.0.0.1:8081/’);

Execute “main.js” now to launch the server in the manner shown below. $ node main.js

MongoDB We will discuss introduction to MongoDB and its installation process below: What Is MongoDB MongoDB is a free document-oriented database that can hold a big amount of data while also allowing us to deal with it extremely efficiently. It is classified as a NoSQL (Not simply SQL) database since data in MongoDB is not stored and retrieved in the form of tables. MongoDB is a database that was created and operated by MongoDB. Inc under the SSPL (Server-Side Public License) and was first published in February 2009. It also offers official driver support for all prominent programming languages such as C, C++, C#, etc.7 Programming languages such as Net, Go, Java, Node.js, Perl, PHP, Python, Motor, Ruby, Scala, Swift, and Mongoid are just a few examples. As a result, we may write an application in any of these languages. Nowadays, numerous firms, like Facebook, Nokia, eBay, Adobe, and Google, utilize MongoDB to store massive amounts of data. How Does It Work? Now we’ll look at what goes on behind the scenes. As we all know, MongoDB is a database server that stores data in databases. In other words, the MongoDB environment provides you with a server on which we may launch MongoDB and build several databases. The data is kept as collections and documents due to the NoSQL database.

Backend Development   ◾    343

As a result, the database, collection, and documents are linked as follows:

Documents

Documents

Documents Collection

Databases

Collection

Documents

Documents

Documents

Working of MongoDB • Collections exist in the MongoDB database in the same way that tables exist in the MYSQL database. We are permitted to build several databases and collections. • We now have papers within the collection. Because we are schemaless, documents do not have to be comparable to one another, and the data we want to store in the MongoDB database is included inside documents. • The fields are used to build the documents. Fields in documents are key-value pairs, similar to columns in a relational database. The fields’ values can be of any BSON data type, such as double, string, and Boolean. • The data in MongoDB is saved in the form of BSON documents. BSON is an abbreviation for binary representation of JSON documents. In other words, the MongoDB server turns JSON data in the backend into a binary version known as BSON, which is then stored and searched more effectively. • It is possible to store nested data in MongoDB documents. Because of data layering, complex data associations may be built and stored in a single document, making data management and retrieval considerably faster than using SQL. To get data from tables 1 and 2, we must use complicated SQL joins. The BSON document can be up to 16MB in size.

344   ◾    Conquering JavaScript

MongoDB Data Modeling As we saw in the introduction, MongoDB data has a flexible structure.8 Unlike SQL databases, which require you to define the schema of a table before entering data, MongoDB’s collections do not impose document structure. This kind of adaptability is what makes MongoDB so effective. Keep the following points in mind when modeling data in Mongo. • What are the application’s requirements?—Examine the application’s business requirements to determine what data and the sort of data it requires. • As a result, ensure that the structure of the document is determined appropriately. What are data retrieval patterns?—If we anticipate a high volume of queries, consider including indexes in our data model to boost query performance. • Are there frequent inserts, updates, and deletions in the database? To increase the overall efficiency of our MongoDB system, reconsider the usage of indexes or add sharding if necessary in your data modeling strategy. What Distinguishes MongoDB from RDBMS? The following are some significant differences between MongoDB and RDBMS:

MongoDB

It is a document-oriented, non-relational database. It is appropriate for storing hierarchical data. Its schema is dynamic. The CAP theorem is at its core (Consistency, Availability, and Partition tolerance). It performs significantly better than RDBMS in terms of speed.

RDBMS

The database is a relational one. It is not appropriate for storing hierarchical data. It already has a schema. It focuses on the characteristics of ACID (Atomicity, Consistency, Isolation, and Durability). It performs worse than MongoDB in terms of speed.

Backend Development   ◾    345

MongoDB Features Include • Schema-less Database: MongoDB offers a nice feature called schema-less databases. A schema-less database allows several types of documents to be stored in a single collection. That is to say, in the MongoDB database, several documents of varying field counts, content types, and sizes may coexist in the same collection. It is not required for one document to be comparable to another, as in relational databases. MongoDB’s interesting feature gives databases a lot of flexibility. • Oriented to Documents: As MongoDB, all data is kept in documents rather than tables like in RDBMS. In these documents, data is kept in fields (key-value pairs) rather than rows and columns, making the data far more flexible than in RDBMS. And each document has a distinct object id. • Indexing: Every field in the documents in the MongoDB database is indexed with main and secondary indices, making it easier and taking less time to obtain or search data from the pool of data. If the data is not indexed, the database must search each document individually with the supplied query, which takes a long time and is inefficient. • Scalability: MongoDB offers horizontal scalability via sharding. Sharding is the process of distributing data over numerous servers. A huge quantity of data is partitioned into data chunks using the shard key, and these data pieces are distributed evenly across shards that exist across many physical servers. It will also add additional machines to an already active database. • Replication: With the aid of replication, MongoDB enables high availability and redundancy by creating several copies of the data and sending these copies to a separate server so that if one server fails, the data may be accessed from another server. • Aggregation: It allows us to conduct actions on aggregated data to obtain a single or calculated output. It is analogous to the SQL GROUPBY clause. It offers three types of aggregations: aggregation pipelines, map-reduce functions, and single-purpose aggregation techniques.

346   ◾    Conquering JavaScript

• High Efficiency: MongoDB has superior speed and data permanence when compared to other databases due to capabilities such as scalability, indexing, and replication. MongoDB Has the Following Advantages • It is a NoSQL database with no schema. • When working with MongoDB, we do not need to design the database schema. • The join operation is not supported. • It gives the fields in the papers a lot of leeway. • It contains a variety of data. • It has a high level of performance, availability, and scalability. • It effectively supports Geospatial. • It is a document-oriented database that stores data as BSON documents. • It also allows for multiple documents ACID transitions (string from MongoDB 4.0). • There is no need for SQL injection. • It is simple to integrate with Big Data Hadoop. MongoDB Disadvantages • It stores data in a large amount of memory. • We may not save more than 16MB of data in the documents. • Data nesting in BSON is similarly limited; we cannot nest data more than 100 layers.

GETTING STARTED WITH MongoDB Terminology A MongoDB Database may be thought of as a container for all collections.9

Backend Development   ◾    347

• As MongoDB, documents are stored in collections. It’s quite similar to relational database management system tables. • There are fields in this document. It’s like an RDBMS tuple, except the schema may change on the fly. Even within the same collection, documents need not contain a uniform set of fields. How to Get Started After installing MongoDB, we can find all of the installed files under C:\ ProgramFiles\MongoDB\ (default location). There are a number of executables in the C:\Program Files\MongoDB\ Server\3.2\bin directory and a brief summary of them is as follows: mongo: A command-line tool for interacting with databases. mongod: This is the database, mongod. configures the server. mongodump: It removes the database’s binary data (BSON) mongoexport: The document is exported using mongoexport in the JSON and CSV formats. mongoimport: To add data to the database. mongorestore: To restore everything that you’ve exported, use mongorestore. mongostat: Database statistics

We may now start the MongoDB server. Open a Command Prompt and go to the location of the MongoDB executables (C:\Program Files\MongoDB\ Server\3.2\bin\, however this path may change in the future). Simply typing “mongod” will result in an error stating that the path \data\db does not exist. This signifies that the default storage path C:datadb was not discovered. So we may create the directory C:datadb manually or with the mkdir program. We may also alter the default path by using the “mongod” command with the switch –dbpath . After creating this directory, rerun the “mongod” command to start the server on port 27017. We must now launch our customer. In order to modify the directory to the MongoDB path, create a new terminal. Once we type “mongo,” our client will start up and attempt to connect to the server.

348   ◾    Conquering JavaScript

To communicate with and manage the databases, use this CLI. This shell resembles a JS console somewhat. We may experiment with various JS commands to see how it works. Now that our customer is operational, we can begin working on the database. We can see that the active database is called “test.” We may switch to different databases, such as “local,” by saying “use ,” and you can examine the databases by typing “see dbs.” There are no collections currently in existence. By entering the command “display collections,” this may be viewed. Start by entering some information into our database. By using the method db.createCollection(name, { size : …, capped : …, max : … }), we can create a collection. However, we have constructed a json file (with employee data) that was generated at random, and we would import it into our database by entering mongoimport --jsonArray --db test --collection employeedata < C:\mongoJson\employeedata.json

This might import the Employee data json file that is referenced by the path in the database “test” collection titled “employeedata.” We may now type “display collections” in the shell to confirm that the collection has been imported. Count(), find(), and findOne() are a some of the very basic querying techniques we may employ with our document. As we can see, each document contains a field named “_id” that was absent from the data imported. The explanation is because every document in MongoDB is guaranteed to have a unique “_id” by default, which is a 12-byte hexadecimal integer. Even though changing this “_id” field is possible, doing so is not advised. Indexing: If our query returns more than one document, we may utilize indexing. For example, db.employeedata.find() retrieves all of the documents in the collection, but if we just want the 7th one, use db.employeedata.find() [6] to get it. [Note: Indexing begins at 0 here.] Projections: Assume we want just certain specified information for a query rather than the whole set of details in the document. We can do these using projections.

Backend Development   ◾    349

Simply set the required fields to 1 after our query object, and the rest will be presumed to be 0. However, keep in mind that the “_id” field is always expected to be 1 implicitly, and if we don’t want to see the unsightly “_id” field, we must specify this in our projection by “_id: 0” Queries

1. Determine the company’s personnel count for “PEEKS FOR PEEKS.” > db.employeedata.find( { company= “PEEKS FOR PEEKS” } ).count()

2. Display all of the employees called “Sanjana Jain” in detail > db.employeedata.find( { name: “Sanjana Jain” }

All of the papers that match the supplied name would appear here. 3. Display the “Harshit Gupta” employee’s age, gender, and email address but not their “_id.” (Presume there is just one worker with the name Harsh Sharma.) Employing projections > db.employeedata.find( { name: “Harsh Sharma” }, { _id:0, age:1, gender:1, email:1 } )

The results of questions may also be saved in variables, which can then be used to create intriguing inquiries. 4. List every female employee’s name in print. > var femaleEmp = db.employeedata.find( { gender: “female” } ) for ( var x = 0 ; x < femaleEmp.count() ; x++){ print ( femaleEmp[i].name) } > db.employeedata.find( { gender: “female” }, { _id:0, name:1 } )

350   ◾    Conquering JavaScript

HOW CAN MongoDB BE INSTALLED ON WINDOWS? MongoDB is an open-source document-oriented database that can hold a big amount of data while also allowing you to deal with it extremely efficiently. It is classified as a NoSQL (Not Only SQL) database since data in MongoDB is not stored and retrieved in the form of tables.10 This has been a broad introduction to MongoDB; now we will learn how to install MongoDB on Windows. MongoDB may be installed in two ways: as a msi package or as a zip archive. We’ll go through how to install MongoDB using msi in this section, so pay attention to each step: Step 1: Download MongoDB Community Server from the https://www. mongodb.com/try/download/community2 MongoDB Download Center.]

Download MongoDB We may choose any version, Windows, and package based on our needs. For Windows, we must select: • Version: 4.2.2 • OS: WindowsOS • Package: msi

Backend Development   ◾    351

Step 2: Once the download is complete, open the msi file and go to the starting page by clicking the next button:

Installation Step 2 Step 3: Go ahead and click the next button after accepting the end-user license agreement.

Installation Step 3

352   ◾    Conquering JavaScript

Step 4: To install every function of the application, choose the entire option. Use the Custom option if we wish to install only particular software features and choose the installation location in this case:

Installation Step 4 Step 5: Choose “Run service as Network Service user” and note the directory’s location. Select Next. Step 6: To begin the installation process, press the Install button: Step 7: After selecting the install option, MongoDB is installed: Step 8: To complete the installation procedure, click Finish now: Step 9: Go to the place where MongoDB was installed on our machine in step 5 and copy the bin path. Step 10: Next, open System Properties, (j*k) }; function Rectangle(l, b) {     console.log(“A rectangle with l = “ + l + “ and b = “ + b);     if (l   Advanced system settings  > Environment Variables. Then, add Android Home and Android SDK to the “New...” screen appears. 3. Install the necessary components by selecting them from Tools Android > SDK Manager > SDK platforms and installing them. 4. Permit the installation to continue, then click Finish when it is complete. 5. To create an Android emulator, a virtual Android device, pick the device type under Tools > Android > AVD Manager > Create Virtual Device. 6. Choose the Android emulator’s API level.

7. Enter the device’s name and configure its settings by selecting Show Advanced Settings.

8. Begin using the emulator.

FUTURE SIGNIFICANCE OF REACT NATIVE IN THE DEVELOPMENT OF MOBILE APPS Facebook’s introduction of the React Native framework for mobile app development has sparked wonderful enthusiasm in the app community. To ensure the success of their projects, business and technical professionals must fully grasp the significance of React Native.

JavaScript for Mobile Usage   ◾    381

The engineers at Facebook and Instagram manage the famous JavaScript framework ReactJS, which has a native counterpart called React Native. React Native has gained tremendous popularity within the developer community in just 2 years. It has received so many stars that it is currently GitHub’s fourteenth most popular project of all time. These days, the react native development firm is using this technology. According to Google trends, more people have searched for ‘React Native’ than for ‘iOS development’ or ‘Android development.’5 Software developers are working hard to produce mobile apps that perform fast and efficiently in the present digital environment, where speed, efficiency, and rapid tools are vital for every mobile application The engaging user experience and straightforward development have convinced mobile app developers to use JavaScript, HTML5, CSS, or React Native to build the app. The leading mobile app development companies view React Native as the future of app development for a variety of reasons. These factors include: 1. Cross-Platform Support Given that the bulk of React Native APIs are cross-platform, one component will work on both iOS and Android. We can build complete, completed applications that function, look, and feel natively without writing a single line of platform-specific code. We do, however, occasionally need to be platform-specific. For instance, the effects of design are different on iOS and Android. React offers remedies for such circumstances with its platform module and platform-specific file extensions. The platform module’s capacity to recognize the OS being used by the app allows for the definition of platform-specific implementations. By employing platform-specific file extensions, we may designate files for various platforms. React automatically chooses the appropriate date based on the operating system that the app is running on. 2. Open Source We are all aware with the idea that open-source projects are made up of a huge number of contributors that work tirelessly to improve the projects.

382   ◾    Conquering JavaScript

Similar to this, there is a huge developer community that is always striving to enhance functionality, fix issues, and make React Native simpler to use. Every time we wish to design anything that is typical of mobile apps, there is a strong possibility that React Native members have already done it. 3. Reduced Development Time React Native modifies the mobile app development life cycle. Since it is open source, a lot of individuals in the community identify with it. Many different mechanisms can be combined with it. The state management tool Redux was used, which also greatly improved development. When there is a single shared data layer for iOS and Android, it goes more quickly and has a lower failure rate. 4. Code Push and Live Updates When developing native mobile applications, employing React Native has several advantages, including Live Updates. Developers may transmit the updates directly to the user’s phone without going via the app store update cycle. This is now possible since JavaScript is so widely used. Live updates for IOS are authorized more gradually. But if we update all of our users’ applications at once, we can be confident that you won’t have to deal with problems with older versions. The live updating feature of Microsoft We can publish changes to our React Native project using the Code Push SDK thanks to integration with React Native. The only thing that can be changed is the JavaScript file and the assets, which is a drawback. The standard App Store or Play Store update procedure will need to be followed for any update that affects the Native OS side. 5. UI and Performance It’s common practice to create hybrid mobile applications using JavaScript, HTML, and CSS. These applications will maintain their excellent performance without having their functionality altered because of Reacts’ independence from the user interface.

JavaScript for Mobile Usage   ◾    383

6. Employ the Same Code When Creating Apps for Different Platforms The usage of React Native by mobile app developers allowed them to create applications for several platforms using the same code. The main shortcoming is recovered in this way. What could be more advantageous for developers than the ability to create cross-platform applications utilizing and mastering only one set of tools? 7. Reduces the Time It Takes to Write Code The ability to reuse previously created code is truly a huge deal in the world of software development. We can get to that precise capacity with the help of React Native. We don’t mean to imply that React Native allows you to ‘write once and use everywhere.’ As a developer, we must create new code to create a user interface (UI) that adheres to the standards and best practices of each platform so that it seems and feels natural. The nicest aspect is that there is some shared UI code that can be utilized on both platforms. 8. Quickly Accessible Resources It is easy and quick to locate developers that can construct mobile apps using React Native with an emphasis on efficiency since React Native uses JavaScript, one of the most well-liked and quickly growing computer languages. 9. A Single Framework for Various Platforms React Native enables full codebase replication between iOS and Android (or just a portion of it). In practice, certain changes may require a complete rewrite, and other features will be included as in-app packages. The react native developer community actively supports the framework by releasing new tools as open source. 10. Quick Reloads By introducing Hot Reload, React Native increases productivity and decreases total development time. It allows a developer to continue working on new versions and UI changes while the app is still running.

384   ◾    Conquering JavaScript

11. A Better Environment for Development Developers are more effective in the React Native environment. By removing the time-consuming rebuild and deployment from the iteration cycle, a pleasant development experience is generated. React native uses the Flexbox layout engine for mobile apps on both platforms. This suggests that just one layout engine has to be understood in order to design for both iOS and Android. 12. Includes Two Important Ecosystems iOS and Android have very distinct ecosystems. The creation of these platforms is challenging and challenging. Therefore, making native apps for them is said to be the greatest nightmare of developers. Similar to building iOS applications, Swift or Objective C expertise is essential. On the other hand, developing Android applications necessitates a thorough knowledge of Java and the Android SDK. We will also have to put up with the inconvenience of keeping up with the most recent features that these two important ecosystems have to offer. But with modern technology, no issue persists indefinitely. Why Is React Native so Popular? Because of its excellent performance, improved user experience, and wide range of accessibility, React Native is receiving high praise from the industry. Facebook supports the sophisticated backend development language, ensuring its endurance throughout actual development. React Native exclusively focuses on UI, in contrast to MeteroJS and AngularJS. The user interface of React Native apps is incredibly responsive. Our app will load faster and have a smoother feel thanks to React Native and the native environment of the device. Additionally, React Native works with third-party plugins. Download a third-party plugin and attach it to a native module in order to include Google Maps features into our project. In addition to making the life of mobile app developers easier worldwide, Facebook’s React Native is a mobile framework that helps them create ground-breaking applications for their customers. Additionally, our app effortlessly makes advantage of the device’s features like rotation, zoom, and compass.

JavaScript for Mobile Usage   ◾    385

Building React Native Apps 1. Skype Using React Native When the Skype app first started having a lot of issues, it was announced that a new application using React Native development was being introduced. Skype had a complete redesign, down to the icons, so that both old and new capabilities could benefit users of the application’s cuttingedge appearance. Microsoft announced that React Native would not only be considered as a platform for the PC version of Windows but also for the creation of mobile applications after realizing the effectiveness of React Native. Additionally, Microsoft acquired the astonishing benefits of React Native from the GitHub repository. 2. React Native Facebook Ads Before React Native began supporting social networking sites, it began with Facebook advertisements as a mobile app for Android users under Facebook’s wing. It might deal with problems caused by the numerous business logic needs required to handle variations in time zones, ad formats, date formats, currency conventions, currencies, and many other things. Other developers were inspired to try and implement React Native technologies that were freshly released or incorporated into Facebook advertisements. 3. Using React Native, Facebook As a simple feature, Facebook intended to make its online version available to its customers on mobile so they could enjoy a smooth user interface when using their smartphone applications. Facebook intended to use a single team to create its mobile application offerings. React Native was therefore used in the creation of Facebook’s mobile app for both iOS and Android users. The development team for React Native verified and examined the new features’ tested performance. This crucial modification determines whether the user will abandon or continue using the program. It is but one example of how changes were made using React Native, but many other aspects were also extensively used by users.

386   ◾    Conquering JavaScript

4. Tesla Using Native React Tesla, the most well-known manufacturer of electric vehicles in the world, has joined the react-native community in order to create an application for its electric vehicles and Powerwall batteries. They did it by using Facebook’s trending structure as a guide. The Tesla app has a few restricted functions that allow for smartphone-based car operation, including the ability to analyze a vehicle and pinpoint its precise location. Although their application development is not entirely known, clients have given the concept a positive response. 5. Using React Native with Instagram Instagram is one among them while discussing react native app development services. It started with transforming the basic view to an excellent UI to overcome the hurdle of integrating react-native into their existing project. Due to the elegant user interface, it does not require a separate navigation infrastructure. Even though the development team encountered several challenging jobs when integrating React Native app features into Instagram, they were able to steadily boost the app’s velocity. Approximately 80%–90% of the codes are exchanged between iOS and Android, which is a huge time saver for an app development team. 6. Shine with React Native One of the top native React apps for users who are stressed out, unmotivated, or lack motivation is Shine. It provides relaxing articles, encouraging quotations, and mottos. When users log in from their day, the app’s inspirational and spiritual audio made by specialists helps them deal with daily stress. This software was initially made available to iOS users with a focus on the American market because Apple phones had a significant market share. They quickly created the app for Android, which is why they used React Native because the technology makes it simple to transfer code from iOS to Android.

JavaScript for Mobile Usage   ◾    387

Benefits of React Native App Development React Native has several advantages for creating mobile apps. 1. More Flexibility Any team member may hop right to the work that was left before and continue performing it thanks to the type of interface utilized by each native development service. With this team, flexibility is growing and the processes for updating and upgrading the mobile app are greatly facilitated. 2. It Saves Time and Money Businesses may now have apps for both the Android and iOS platforms thanks to React Native, which also saves time for the developers. This is so because they may save time and effort by developing just a single app that will work on both the Android and iOS markets. As a result, money that would have been spent on creating different apps is also saved. 3. Excellent Performance The central processing unit (CPU), which powers the majority of OS operations, is employed here, but React Native apps also make use of the GPU, the graphics processing unit, to aid improve speed. However, due to the programming language’s specialization for mobile devices, React Native apps run almost as quickly as native apps created specifically for the Android or iOS platform. 4. Immediately Changed Views Reacts Native’s live or hot reloading feature enables developers to examine their changes in real time in a live preview window while simultaneously viewing their changes in the code. Additionally, the developers benefit greatly from this since they receive real-time feedback as each step is completed. 5. Movable React Native is claimed to give a lot of flexibility to the procedures being used, making this one of the biggest advantages of adopting it for mobile app development. These properly export applications from React Native and transfer them to Android Studio or XCode before continuing.

388   ◾    Conquering JavaScript

Cons of React Native We discussed a few advantages of React Native above, but we all know that anything that has advantages also has disadvantages. The disadvantages (drawbacks) of React Native are therefore listed below.6 1. Insufficient Framework Every new update or release, as we all know, brings with it a number of significant changes that might eventually be difficult for the developers to handle. React Native is the speedier and newer alternative in this situation, but in an effort to move quickly, the framework tends to lose its commitment to credibility and, as a consequence, becomes too immature for any type of iOS and Android apps. 2. It Is Difficult to Define the User Interface Choosing React Native for your app development is not worth it at this moment if your mobile application requires capabilities like animation, numerous screen transitions, and interactions. 3. Complicated Debugging Debugging procedures and how React Native-developed mobile applications are challenging to troubleshoot. Most of the credit for this goes to the programming languages Java, JavaScript, and C/C++.

CREATE A MOBILE APPLICATION USING REACT NATIVE Businesses have been forced to consider moving their business models from traditional platforms to digital platforms as a result of the fast changing environment across the globe. Businesses are beginning to create extremely efficient corporate apps that function flawlessly on iOS and Android. However, their ability to invest in mobile app development is constrained by the rising cost of app development. However, given that mobile applications have grown so prevalent across all industries from communication to retail, healthcare, and entertainment businesses have realized how difficult it would be to compete in the next decades without having a strong online presence. Although there is an app for nearly everything, which provides a seamless user experience and guarantees easy user navigation, businesses are still unsure about which technology to utilize to develop successful solutions.

JavaScript for Mobile Usage   ◾    389

The Leading Cross-Platform Framework, React Native React Native is a cross-platform framework built on JavaScript that has been extensively used to develop mobile apps that look and feel native on iOS and Android. React Native, although being introduced by Facebook in 2015, has swiftly risen to prominence as the leading open-source framework. After powering several applications like Skype, Instagram, Facebook, and others, it eventually became well-known as the greatest app development option. It was the ideal platform for app creation because of the advantages of reusability of scripts, rapid testing capabilities, and running apps on both iOS and Android platforms. Why Should We Use React Native When Developing Mobile Apps? Undoubtedly, 42% of developers worldwide like React Native, however when it comes to investing in an app development project, many organizations are perplexed as to why React Native is the top option. Here are a few justifications for using React Native for app development. Saves both Money and Time The main benefit of using React Native for app development is the time, money, and effort it saves. Developing two native apps for several platforms will cost us more money than utilizing React Native and a single codebase to create an app. Therefore, using React Native, developers can easily release the same update for both iOS and Android platforms without the added work of utilizing a distinct codebase, saving money on paying mobile app developers to create two native apps. High Quality Businesses’ top priorities are almost usually related to the app’s performance. Additionally, React Native apps are just as good as native Android and iOS apps. React Native uses GPU to do computations, as opposed to other crossplatform frameworks that use CPU. This is a key factor in the better performance of React Native apps.

390   ◾    Conquering JavaScript

Over-the-Air Updates React Native’s ground-breaking OTA update capability enables developers to make changes to the backend while users are actively using the app. Once completed, the modifications will appear immediately in the app. In other words, consumers frequently have the option to update an app without visiting the app store. The entire process of upgrading the app is made simple and quick thanks to React Native’s functionality. The Main Advantage Is Open-Source Software For those who want to personalize the lovely application, React Native offers a wide range of freely available native-like UI capabilities. Since React Native enables developers to smoothly export scripts from Android Studio to Xcode, developers do not have difficulties porting React Native projects from one platform to another.

NATIVESCRIPT We will discuss about the introduction, setup, scope, benefits of NativeScript below: What Is NativeScript? An open-source framework called NativeScript is used to build native mobile apps for iOS and Android. This framework is JIT compiled. On the JS virtual computer, NativeScript code is executed.7 Both the Android and iOS platforms employ the V8 engine runtime. For development, NativeScript makes use of XML, JS, and CSS. It has a web-based IDE called PlayGround. This PlayGround includes a userfriendly working interface, straightforward project management, hot reloading, and device debugging. NativeScript enables programmers to build native, cross-platform applications fast and effectively while reducing the expenses of testing, development, and training. Therefore, Native applications will remain powerful and rich for years to come, making them better and simpler to use. Why NativeScript Is Preferred for the Creation of Android Applications These days, developers may choose from a wide range of frameworks to create stunning and scalable mobile applications.

JavaScript for Mobile Usage   ◾    391

Developers may take advantage of both smartphone features and their web development expertise thanks to the widespread adoption of the hybrid app development idea in the market. This is where NativeScript enters the picture because of all the advantages it offers businesses searching for an Android app development solution. As the name implies, Native Script enables JavaScript developers to create flawlessly native apps.8 Surprisingly, the length of time it takes to build an app as a whole is cut without sacrificing quality. Additionally, programmers can utilize alternative frameworks like TypeScript and Angular. Applications created using Native Script run incredibly well, have a great user experience, and can connect to several devices. Here are all the key justifications to use Native Script in the event that we are considering doing so for our projects. What Is NativeScript? What Are Its Main Advantages and Disadvantages? A well-known open-source frontend framework called Native Script is used to create native and cross-platform mobile apps that have outstanding performance and user experience features. When it was introduced in 2014, it soon gained a reputation for great usability and platform-specific programming capabilities. The most important benefit of using Native Script is providing users with an engaging native user experience across platforms like Android, iOS, and the web. Android developers can benefit from the simple access to native Android features through native Android APIs to build a usercentric app regardless of the niches. Advantages of Native Apps

1. Native Apps Provide Quickness Because they are native to the platform, native apps operate more quickly. There are many preloaded elements. Since they leverage the built-in features of the device, they are quick because the user data is fetched from the web rather than the complete application.

392   ◾    Conquering JavaScript

2. The Use of Native Apps Offline Even without internet access, native apps function. Therefore, native apps are usable while we’re stranded in a place with poor or no connectivity, like an airline, underground tunnel, or metro. 3. Native Applications Offer a Recognizable Interface and Feel The default apps on their device have been enhanced with native applications. Because the program is similar to other apps already installed on the smartphone, when a user does several actions, they rapidly know the natural flow of the application. Native apps have an advantage in this situation because mobile applications that attempt to mimic the appearance and feel of native apps frequently wind up succumbing to the phenomenon known as the ‘uncanny valley effect,’ which was named by robotics professor Masahiro Mori. 4. Native Apps Maintain aspect ratios the width to height ratio of various screens is known as an aspect ratio. It is a significant element that affects how good an image is. Changing the size and form of the device causes many apps to break and function incorrectly. The orientation, size, and resolution of an app can be more precisely controlled with native apps. Layout features are available to developers as they create native apps. A native app keeps the aspect ratio on its own regardless of the screen it is running on after setting the screen size. Both iOS and Android have tools called Constraint Layout and Auto Layout that assist in keeping the aspect ratio on their respective devices. Along with maintaining aspect ratios, these capabilities offer various DPI (dots per inch) for each screen to preserve the visual quality. Limitations with Native Apps

1. Lengthy Downloading Process Native applications are ready to use only after consumers download them from the app store (Google Play or Apple App Store).

JavaScript for Mobile Usage   ◾    393

This entails a number of steps going to the app store, selecting the program, accepting its terms and conditions, and then eventually installing it. Many folks don’t have the time and patience to follow all the steps to download an app. We lose 20% of consumers at each level in an app funnel. 2. Absolute Rigidity There is little freedom for developers when choosing the platform on which to build native applications. One platform at a time, with separate development for Android and iOS, is required of developers. We’ll often need to employ two teams of developers if you’re recruiting app developers for our native app idea: one for Android and one for iOS. 3. Costly Development Native app developers are hard to find since the coding they utilize is fairly difficult. As a result, native app development takes longer to complete and costs more money. It also costs more money and takes longer to build native applications since they need distinct codes for each platform. Additionally, the expense of maintaining native applications is relatively expensive. Upkeep accounts for 15%–20% of total app development costs. For instance, a simple native app that costs $25,000 would need roughly $5,000 in upkeep. The maintenance expenses of a native app will increase along with its development expenditures. 4. Development That Takes Time Because each platform, like iOS and Android, has a unique set of codes, it takes longer to develop for each platform because it’s like creating for two new applications. A high-quality native app has to be developed in roughly 18 weeks. Depending on how difficult the project is, the time grows. Setups for NativeScript Environment How to install NativeScript on our computer is described in this section.

394   ◾    Conquering JavaScript

Prerequisites We require the following requirements before beginning installation:

• Node.js • Android • iOS Verify Node.js Node.js is a JavaScript runtime engine constructed on top of Google Chrome’s internal JavaScript engine, v8. NativeScript utilizes Node.js heavily for different purposes like building the beginning template application, compiling the application, etc. It is required to have Node.js on our PC. Hopefully, we have installed Node.js on our system. If it is not installed then visit the website, https://nodejs.org/ and get the latest LTS package and install it. To test if Node.js is correctly installed, enter the below command on our terminal: node --version

The version was visible. The most recent ‘LTS’ stable version of node is 12.14.0. CLI Setup We may construct and develop NativeScript applications using the NativeScript CLI, a terminal/command line program. NativeScript CLI is installed on our computer via the Node.js package manager npm. Run the command shown below to install NativeScript CLI. npm install -g nativescript

setupcli The most recent version of the NativeScript CLI, tns, is installed on our system. Enter the following command into our terminal now. tns

JavaScript for Mobile Usage   ◾    395

cli Without any further setup, we can construct and develop applications using tns. However, we were unable to deploy the program on actual hardware. Instead, we may use the NativeScript Playground iOS and Android app to launch the program.

Setting Up the NativeScript Playground Application Search for NativeScript Playground on the Google Play Store or the iOS App Store. Click the install button when the program is displayed in the search results. The NativeScript Playground app will be installed on our device.9 Without actually publishing the program to a real device or emulator, we may test our apps on Android or iOS devices using the NativeScript Playground application. This will speed up the process of developing the application and provide a simple approach to get it going. Setup for Android and iOS Let’s learn how to set up the system to create and launch iOS and Android apps on either a real device or an emulator. Step 1: Dependency on Windows Run the command below as administrator at our Windows command prompt. @powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((new-object net.webclient).DownloadString('https:// www.nativescript.org/setup/win'))"

Following this command, downloaded scripts install their dependencies and are configured. Step 2: Dependency on macOS We must check whether Xcode is installed before we can install on macOS. NativeScript requires the use of Xcode. If Xcode isn’t already installed, go to https://developer.apple.com/ xcode/, download it, and then install it. In our terminal, run the following command to begin.

396   ◾    Conquering JavaScript sudo ruby -e "$(curl -fsSL https://www.nativescript. org/setup/mac)"

The script will install the necessary prerequisites for developing for both iOS and Android after running the aforementioned command. Close our terminal and restart it after it’s finished. Step 3: Android reliance The following requirements should be set up, hopefully: • JDK 8 or higher • Android SDK Build-tools 28.0.3 or higher • Android Support Repository • Google Repository • Android SDK • Android Studio If the following requirements are not set up, go to https://developer. android.com/studio/install and install it. Finally, add the environment variables JAVA_HOME and ANDROID_HOME. Step 4: Verify dependencies Everything is finished at this point. This dependence may be verified using the command provided below. tns doctor

Top NativeScript Usage Cases For years, feature-rich and performant apps have employed Native Script across all platforms. The key selling point of the framework continues to be its customary capacity to influence native user experience. Let’s quickly review some of the most prominent and well-known use cases of Native Script from various angles. • Popular social networking platforms including Facebook, Twitter, WhatsApp, and a number of others employ Native Script.

JavaScript for Mobile Usage   ◾    397

• NativeScript is used by several popular GPS map and location apps, including Field Trip, Banjo, Glimpse, and others. • Numerous popular news and entertainment applications, like Buzzfeed, Reddit, SmartNews, Feedly, and others, also employ Native Script. • Native Script Live is used by a number of well-known gaming applications, including Drop7, Crossy Road, Real Racing 3, Robot Unicorn Attack 2, and others. Live feed apps, including Livestream, Broadcast me, Periscope, and numerous more, also utilize Nativescript. • NativeScript is used by streaming music and video applications like Apple Music, iHeartRadio, and others. • Native Script is also used by popular chat and social messaging apps like Skype, Snapchat, Messenger, and others.

Key Benefits of Developing Android Apps Using NativeScript NativeScript has established itself as a go-to framework for creating robust, captivating, and high-performing native Android apps throughout the years. For their Android app projects, developers may take use of a number of fantastic benefits provided by Native Script. Let’s quickly review the main advantages of utilizing Native Script while creating Android apps. Performance of Native Apps Accessing the native UI through a specific Android API is the main benefit of utilizing NativeScript for Android programming. NativeScript, in contrast to many other frameworks, can access native UI without using WebViews or a middle JavaScript bridge. NativeScript is likely to begin running native code in all areas of the app as soon as the developers have specified the native feature and capability. As long as this natural UI building ability is present. The user interface may be further modified by Android developers to suit the needs of a certain device. This is crucial for a complex and varied device ecosystem like Android because Native Script, like other native Android programming languages

398   ◾    Conquering JavaScript

like Kotlin or Java, can enable fast app performance and a completely platform-specific user experience without compromising the code’s reusability. The user interface and user experience characteristics stay naïve when the same code is reused across different platforms. Reusable Program We can easily utilize and reuse the same codebase across iOS, Android, the web, and other platforms when using NativeScript. Additionally, Native Script includes a number of native Android capabilities that programmers may employ right away in their app projects. By integrating with a variety of other top JavaScript frameworks, including React, Angular, Vue, and others. While preserving the platform-specific user experience, Native Script can assist with platform-specific code reuse. The Very Low Learning Curve By utilizing the Native Script framework, any app developer may quickly hone and expand their programming talents. Native Script enables us to get a head start while learning to develop Android features from scratch if we are just getting started with the platform. We may create a whole Android app with the aid of some basic understanding of popular web development languages like JavaScript, CSS, and Android UI. Along with facilitating simple access to platform-specific APIs for iOS and Android. The framework is renowned for its simplicity in integrating with other frameworks and SDKs. Every plugin, template engine, and API that Android developers utilize in their various app projects are supported by the framework. The Android SDK is also fully supported by it. The ability to integrate with various technologies guarantees that developers have the greatest amount of flexibility and creative freedom to create a distinctive and interesting user experience. Substantial Community Support The team behind the creation of Native Script was made up of professionals with years of expertise in creating native apps for various platforms.

JavaScript for Mobile Usage   ◾    399

They are familiar with the difficulties experienced by developers working on the iOS and Android platforms. Additionally, the framework has widespread support from the developer community. Last but not least, the company that created Native Script offers enterprise-level assistance for projects that include developing mission-critical apps.

COMPARISON BETWEEN NATIVESCRIPT AND REACT NATIVE It’s not easy to pick one framework from two JS-based frameworks. Both provide benefits that are relatively comparable due to being cross-platform. However, React Native truly shines in particular industries. The performance, learning curve, popularity, and development community of the two frameworks, as well as other important characteristics, are briefly compared here.10 Performance of NativeScript and React Native Both frameworks offer native app performance to start. Both take a long time to load. But this is where React Native takes center stage. NativeScript renders pages slowly. To be really honest, delayed rendering is unacceptable in a society when every second matters. This is the very situation when React Native is useful. React Native uses native SDKs to render apps while rendering dynamic components. All because of the Virtual DOM, this transforms React Native into a very fast framework. Learning Curves for NativeScript and React Native NativeScript and React Native cannot be handled by a developer with only JS skills. Let’s consider this. Initially, NativeScript will be simpler for developers with an Angular background. Programmers with a React background, on the other hand, will find the shift to React Native easier. It is important to remember that JavaScript is used by both systems. For frontend developers, this is a fantastic chance. At these times, it is somewhat simpler to perceive these frameworks. Choosing React Native means that all we need is JavaScript, whereas NativeScript provides assistance through its declarative coding approach.

400   ◾    Conquering JavaScript

Development Community for React Native vs NativeScript React Native has a larger developer community than NativeScript, which is utilized by 11% of programmers, with 42% of programmers. React Native is also very popular since tech behemoths like Instagram and Tesla selected it over PhoneGap or NativeScript to create their applications. The importance of considering community support is vital while deciding on the best structure. Even though it may seem odd, NativeScript has existed for a lot longer than React Native. React Native was published on March 26, 2015, whereas NativeScript was first made available in 2014. Although the 1-year gap may appear to be an advantage, NativeScript is increasingly being replaced with React Native. React Native records 533k downloads on npm weekly, compared to around 7k downloads per week for NativeScript as of the publication date. Speaking of contributions, React Native beats out NativeScript with more than 2,200 contributors on GitHub. NativeScript has 208 contributors. On GitHub, React Native is really utilized by 720k developers, whereas NativeScript is used by greater than 3.5k. These margins show the developer community’s widespread acceptance of React Native, which has an effect on the amount of third-party libraries, replies, and bug solutions on StackOverflow. Overall, React Native triumphs in this case. Popularity of NativeScript vs React Native Both NativeScript and React Native were developed using JavaScript. The competition is never far apart. According to a 2019 StackOverflow study, JavaScript was the most widely used technology. React.js has surpassed Angular.js/Angular and Vue.js when it comes to web frameworks. It appears that developers favor React.js more. React Native is simultaneously used by 10.5% of all respondents. In addition to becoming more popular than NativeScript, React Native also attracts more attention.

JavaScript for Mobile Usage   ◾    401

Which Should We Use between React Native and NativeScript? It may be difficult to decide between these two well-known technologies because each has advantages and drawbacks of its own. The best technology for us will mostly rely on the needs of our project. The proper times to utilize NativeScript and React Native have been determined, nevertheless. Select NativeScript if

• We want to create a cross-platform program. • Using the free and built-in plugins and templates, we want to create extendable APIs. • Instead of creating complex, inaccessible, and distracting user interfaces, we don’t require webViews. • Avoid performance problems at all costs. Select React Native if

• We want to quickly develop an MVP. • We want to create real-time apps that communicate updates in real-time. • We want to make mobile apps with a certain UI. • Without third-party plugins, our platform must be created. In this chapter, we covered advantages, disadvantages, scope, popularity and comparison of React Native, and NativeScript.

NOTES 1. Why Is JavaScript Considered One of the Best in Mobile App Development for 2022?: www.linkedin.com/pulse/why-javascript-considered-onebest-mobile-app-?trk=pulse-article_more-articles_related-content-card Accessed on: 17 October 2022. 2. Should You Use JavaScript for Mobile Development?: www.kambda.com/ should-use-javascript-mobile-app-development/ Accessed on: 17 October 2022.

402   ◾    Conquering JavaScript

3. Benefits of Using JavaScript for Mobile App Development: https://medium.

com/@rohithaelsa/benefits-of-using-javascript-for-mobile-app-development-e1e71aa94e21 Accessed on: 17 October 2022. 4. React Native Environment Setups: www.javatpoint.com/react-native-environment-setup Accessed on: 19 October 2022. 5. Future Scope of React Native for Mobile App Development: https://richestsoft.com/blog/future-scope-of-react-native-for-mobile-app-development/ Accessed on: 17 October 2022. 6. The Pros and Cons of Native Apps: https://clutch.co/app-developers/ resources/pros-cons-native-apps Accessed on: 18 October 2022. 7. NativeScript Tutorial: www.tutorialspoint.com/nativescript/index.htm Accessed on: 18 October 2022. 8. Why Nativescript Is Preferred for Android App Development: www.cisin. com/coffee-break/technology/know-why-nativescript-is-preferred-forandroid-app-development.html Accessed on: 18 October 2022. 9. NativeScript – Installation: www.tutorialspoint.com/nativescript/nativescript_installation.htm Accessed on: 19 October 2022. 10. NativeScript vs React Native for Native App Development in 2022: www. bacancytechnology.com/blog/nativescript-vs-react-native Accessed on: 18 October 2022.

Chapter

8

JavaScript for Desktop Apps

IN THIS CHAPTER ➢ Electron.js In the previous chapter, we covered JS for mobile usage, and in this chapter, we will discuss the usage of JS for Desktop Apps. The design of desktop programs has improved in recent years, with more and more apps taking on the appearance and feel of today’s cuttingedge websites. Electron is the technology that has allowed desktop programs to go to this next level. It’s a breeze to use, loads quickly, and streamlines production. Previously, JavaScript was the preferred language for creating websites and online applications, in large part because JavaScript frameworks like React, Vue, and Angular were so well-liked. However, with the advent of Node.js in 2009, JavaScript gained the ability to operate outside the browser. Because of this, we can now utilize JavaScript for a lot more than simply websites, including the development of desktop apps using Electron.js.

DOI: 10.1201/9781003356578-8

403

404   ◾    Conquering JavaScript

Electron is a runtime that provides a wide range of native (operating system) APIs, allowing us to write desktop apps in pure JavaScript. We may think of it as a fork of the Node.js runtime tailored specifically for desktop programs as opposed to web servers.

HOW CAN WE USE DESKTOP APPLICATIONS? The term ‘desktop application’ refers to software designed to be used only on personal computers. These programs are installed for one single function and serve no other reason. Microsoft Word, which we use to write and edit documents, is an example of a desktop program. Web browsers, Visual Studio Code, and Adobe Photoshop are further examples of widespread desktop apps. Desktop apps are distinct from online programs in that they need installation prior to use and, in some cases, may not even require an active internet connection to function. However, web applications need constant connectivity to the internet and can only be accessed by going to the URL where the app is located. The following are some examples of frameworks used while creating desktop applications: 1. Java Java is an object-oriented, class-based programming language that was created with the goal of requiring as little from the underlying implementation as feasible. As a result, generated Java code may run on any systems that accept Java without the need for recompilation, allowing application developers to ‘write once, run everywhere’ (WORA). 2. JavaFX As stated on their website, it is a Java-based, open-source, nextgeneration client application platform for desktop, mobile, and embedded devices. 3. C# C# is a general-purpose, multi-paradigm programming language that supports a wide range of programming paradigms, including strong typing, lexically scoped, imperative, declarative, functional, generic, object-oriented, and component-oriented.

JavaScript for Desktop Apps   ◾    405

4. .NET .NET is a free, open-source, and cross-platform development environment that may use to create a wide variety of software. When using.NET, developers have access to a wide variety of tools and frameworks for creating applications for the web, mobile devices, desktop computers, video games, and the Internet of Things.

WHAT IS AN ELECTRON? Electron is a free and open-source software environment for creating desktop software. The project, originally known as ‘Atom shell,’ is built and supported by GitHub.1 With it, we can create desktop apps that run on several platforms with only HTML, CSS, and JavaScript. This implies that a same set of codes may be used to create desktop programs for several platforms, including Windows, MacOS, and others. It was built using Node.js and Chromium. Many well-known programs, including the Atom text editor, Visual Studio Code, WordPress for desktop, and Slack, were developed using Electron. Installation Use the NPM package manager to add Electron to our project. npm install electron --save-dev

If we intend on working with electron applications extensively, we may install it globally with this command: npm install electron –g

WHICH APPS USE ELECTRON? Electron provided several advantages to numerous businesses.2 1. WebTorrent Desktop Application Let’s face it: We all love torrents, whether they’re downloaded on our phones or our computers. However, this sort of software still seems

406   ◾    Conquering JavaScript

obsolete and out of date, which is why the folks at WebTorrent decided to take action—adopting Electron JS as their primary development tool. WebTorrent is the first torrent client that works in the browser, is entirely built-in JavaScript, and leverages WebRTC for peer-to-peer transmission. WebTorrent connects the user to a decentralized browser-tobrowser network that provides efficient file sharing without the need for plugins, extensions, or installs. Why Is Electron Used by WebTorrent for Desktop? Electron enters the fray with the WebTorrent desktop client, making it as light, ad-free, and open source as possible. It also helps with streaming and functions as a hybrid client, connecting the program to all of the prominent BitTorrent and WebTorrent networks.

2. WordPress Desktop Application WordPress, as the undisputed monarch of content management systems, needed a dependable and automatic desktop version. It joined the list of desktop applications utilizing Electron JS—as an open-source framework that enables users to manage WordPress content—thanks to Electron JS. We’ve all heard about WordPress and how to use it in our browsers. WordPress for desktop, on the other hand, is something altogether new: desktop software built on the Electron framework that delivers a seamless cross-platform experience, enabling users to concentrate on their content and design without being distracted by browser tabs. Why Does the WordPress Desktop App Make Use of Electron? WordPress for desktop is a desktop program that uses Electron as a foundation and JavaScript with React as the primary language in this new desktop technology.

3. Ghost Electron Application We are not alone if you have never heard of Ghost. Ghost is essentially an open-source platform that allows users to create and manage contemporary web publications. Ghost is entirely hackable and has a significant influence on the future of online media, from blogs to magazines and journals. This is mostly due to the easier and more focused authoring experience, which is clearly a result of the JavaScript desktop framework, among other technologies.

JavaScript for Desktop Apps   ◾    407

Why Does the Ghost Desktop App Make Use of Electron? In that spirit, Ghost for desktop is a desktop program built with Electron JS that enables authors to maintain many blogs at the same time while focusing on their content. If we’re a writer, we’re surely aware that basic things like keyboard shortcuts may be difficult to implement in a browser. The Ghost desktop program, on the other hand, makes it simpler than ever. Ghost for desktop is one of the Electron-based applications that provide a better user experience by using JavaScript and Node.js on both the backend and frontend.

4. The Electron App Beaker Browser Are we looking for a dependable peer-to-peer web browser? If so, we’ve just discovered it. Beaker Browser is a collaborative browser for hackers. Beaker Browser, originally developed as a hackable product, transforms the Web to an open-source format and allows hackers, modders, and creative types to make the most of their digital abilities. Why Is Electron Used by Beaker Browser? The Electron framework makes it much simpler to construct Beaker. It assisted the Electron design process with minimum iterations and in the best manner possible as a toolset for developing browsers. In a word, Beaker Browser is an open-source online browser and a solution that enables social hacking simpler and more effective than ever before.

5. Pexels Electron App Pexels is a lifesaver for many authors, designers, and publicists. As a site with thousands of royalty-free stock pictures, it clearly needed to be improved. That is how the Pexels desktop app, developed using Electron JS, came to be. Why Does the Pexels Desktop App Make Use of Electron? With just one click, this software makes it simpler than ever to copy a snapshot to your clipboard. The picture may then be pasted into any software and used as a stock image for an article, infographic, or social media post. There are no downloads, therefore there are no issues, and finding new photographs is simple due to the Pexels desktop software.

408   ◾    Conquering JavaScript

6. Slack Desktop Application Slack desktop app for macOS is another amazing program that makes use of this JavaScript technology. Why Does the Slack Desktop App Make Use of Electron? It was created using the Electron framework, which is clearly noticeable due to its speedier performance and frameless appearance, as opposed to the browser experience. Slack for desktop is the software of choice for many organizations seeking for an improved organization or a more focused workplace. Although Slack for desktop uses a mixed method, the majority of their assets and code are loaded remotely, using the Chromium rendering engine and the Node.js runtime and module system.

7. WhatsApp Electron Application WhatsApp, the most downloaded chat software, is another prominent desktop program that uses ElectronJS. Why Does the WhatsApp Desktop App Make Use of Electron? The Electron framework helped WhatsApp developers cover everything at once and wrap the desktop experience of WhatsApp behind a more streamlined and revolutionary framework—the Electron. This resulted in less labor and more contribution.

WHY DO SO MANY BUSINESSES CHOOSE ELECTRON TO CREATE CROSS-PLATFORM DESKTOP APPS? There are many important reasons why businesses choose Electron to create desktop apps: Electron enables developers to create desktop programs using JavaScript specifically, developers leverage web technologies such as HTML, CSS, and JavaScript. Electron allows developers to create cross-platform programs that run on Mac, Windows, and Linux—it removes the requirement for developers to be skilled in technologies required to develop for these platforms natively. What Is the Significance of This? At the highest level, we can see Mac, Windows, and Linux. That’s already quite a lot. On a deeper level, though, such systems come in a variety

JavaScript for Desktop Apps   ◾    409

of  flavors. Each has unique characteristics, and each one that is still in use should be considered during product creation. Furthermore, each platform has its own peculiarities. To meet this development challenge, we must employ professionals, which might take a long period. Furthermore, developing three distinct applications is a time-consuming procedure. From a commercial standpoint, in many circumstances, that is not a realistic answer.

BENEFITS OF ELECTRON Nowadays, most developers choose Electron to create cross-platform apps due to the following remarkable benefits3: Single Codebase Electron offers a versatile abstraction for native operating system functionality. As a result, developers may keep a single codebase for their cross-platform application, which will work on the majority of popular platforms. Quick Feature Delivery Creating user interfaces in Electron using HTML and CSS is simple; these web technologies allow us to construct any custom GUI element. Furthermore, Node.js offers a vast ecosystem of libraries, allowing us to easily add native-like capabilities. Framework Maturity Because Electron was first launched about 8 years ago, it has a large user base and community. There are also useful built-in features such as auto updates. Reputable firms like Microsoft use Electron to develop cross-platform apps. Electron was used to build applications such as Visual Studio Code, Teams, and Skype. Electron Has Several Unresolved Concerns While the Electron framework is generally amazing, it has numerous key speed concerns.

410   ◾    Conquering JavaScript

Electron includes Chromium and Node.js in the final application package, thus even if we write a basic and lightweight app by carefully selecting frontend libraries and frameworks, our project will become bloated. Chromium and Node.js are large projects, and their modules will need more resources than usual on our machine. In other words, Electron-based apps will need a large amount of physical memory and disc space. Furthermore, because of their high resource usage, Electron programs rapidly deplete our laptop’s battery. Electronbased cross-platform apps often become bloatware as a result of the severe performance difficulties discussed above. This disadvantage may be hidden from the common user by powerful hardware. However, if users begin running many Electron apps, they will quickly notice this hidden performance disadvantage.

ALTERNATIVES FOR ELECTRON Several alternatives, such as Electrino and DeskGap, appeared as remedies to Electron’s performance difficulties some time ago. Both efforts attempted to decrease the size of the final bundle by utilizing the operating system’s webview rather than Chromium. Unfortunately, the developed Electron framework could not finish these two projects. However, there are two popular lightweight Electron alternatives: Tauri and Neutralino.js. Both projects attempt to address Electron’s performance problem by replacing Chromium and Node with better, lighter alternatives. Instead of Chromium, both projects utilize the well-known webview library to render HTML and CSS. The webview library renders using the current web browser component. It will, for instance, utilize gtk-webkit2 on Linux systems, Cocoa Webkit on macOS, and Edge/MSHTML on Windows.

DRAWBACKS OF ELECTRON.JS FRAMEWORK There are some disadvantages to using electron.js, which are listed below4: Excessive Volume Electron programs use their own version of the Chromium browser. This browser is quite large and comprises millions of lines of code. In fact, since the Chrome browser is the same size as an operating system, it takes up a lot of hard disk space on a computer.

JavaScript for Desktop Apps   ◾    411

However, given that current computers often offer users with 2 terabytes of memory space, the huge number of electron applications isn’t a major concern. Electron.js Framework Consumes a Lot of Resources The Electron.js framework consumes ROM and system resources, as well as battery power fast if utilized on a laptop. Indeed, the Electron application is optimized to function on many systems, and since the platforms vary, application optimization necessitates more energy. Because native apps are platform-specific, their resources are superior. Specific Customer Needs Electron.js apps typically operate the same on all platforms, but programmers may struggle if users have a different design for each device. In reality, developers must devote more effort to creating unique features to each platform, which will inevitably raise expenses. Most crucially, this will not work; as a result, application owners must plan ahead of time for their product identification.

SIGNIFICANCE OF USING THE ELECTRON.JS FRAMEWORK The Electron JS framework is used by developers to create high-quality cross-platform apps. But why do you believe programmers choose this framework over other tools? First and foremost, this framework supports all accessible platforms, making it very user-friendly for developers. In addition, developers will be able to create Cross-Platform apps using the Electron.js framework and other JavaScript frameworks. Another reason for the Electron framework’s success is that its apps are genuinely web applications. In other words, Electron.js is a web technology that allows us to simply convert a desktop program to a web version.

DISTINCTION BETWEEN THE MAIN AND RENDERER PROCESSES By establishing BrowserWindow instances, the main process generates web pages. The web page is rendered in its own renderer process by each BrowserWindow instance.

412   ◾    Conquering JavaScript

The related renderer process is ended when a BrowserWindow instance is destroyed. The main process is in charge of all web pages and their associated renderer processes. Each renderer process is isolated and is solely concerned with the web page that is executing in it.

HELLO EVERYONE CODE IN ELECTRON For our project, we built a package.json file. Now we’ll use Electron to build our first desktop app.5 Make a new file named main.js. Fill in the following code: const {app, BrowserWindow} = require('electron') const url = require('url') const path = require('path')   let win   function createWindow() {    win = new BrowserWindow({width: 700, height: 500})    win.loadURL(url.format ({       pathname: path.join(__dirname, 'index.html'),       protocol: 'file:',       slashes: true    })) }   app.on('ready', createWindow)

Make a new file named index.html, this time in HTML. Enter the code below into it.

                Hello Everyone!        

JavaScript for Desktop Apps   ◾    413           Hello Everyone!       We are using the node ,       Chrome ,       and Electron .    

Use the following command to launch this app: $ electron ./main.js

HOW DOES THIS APP FUNCTION? We made a primary file as well as an HTML file. Two modules are used in the main file: app and BrowserWindow. The app module manages our application’s event lifecycle, while the BrowserWindow module creates and manages browser windows. We built a createWindow function that creates a new BrowserWindow and associates it with a URL. When we launch the program, this is the HTML file that is rendered and shown to us. In our html file, we utilized a native Electron object process. This object extends the Node.js process object, retaining all of its functionality but adding many more.

BUILDING UIs WITH ELECTRON Electron applications’ user interfaces are constructed using HTML, CSS, and JS. As a result, we can use all of the existing tools for frontend web development here as well. To create the applications, we may utilize technologies like Angular, Backbone, React, Bootstrap, and Foundation.6 We may handle these frontend dependencies using Bower. Bower should be installed via $ npm install -g bower

414   ◾    Conquering JavaScript

Bower now provides access to all available JS and CSS frameworks, libraries, plugins, and so forth. For example, to get the most recent stable version of bootstrap, use the following command: $ bower install bootstrap

This will download the bootstrap component from bower components. We may now use this library in our HTML. Let’s build a basic page using these libraries. Let us now use the npm command to install jquery. $ npm install --save jquery

This will also be needed in our ‘view.js’ file. We already have a’main.js’ file as seen below. const {app, BrowserWindow} = require('electron') const url = require('url') const path = require('path') let win function createWindow() {    win = new BrowserWindow({width: 700, height: 500})    win.loadURL(url.format ({       pathname: path.join(__dirname, 'index.html'),       protocol: 'file:',       slashes: true    })) } app.on('ready', createWindow)

JavaScript for Desktop Apps   ◾    415

Open our index.html file and add the following code:

                Hello Everyone!                                  This page use Bootstrap and jQuery!                    Click                    

Create a view.js file and add the click counter logic to it. let $ = require('jquery')  // jQuery loaded and assigned to $ let count = 0 $('#click-counter').text(count.toString()) $('#countbtn').on('click', () => {    count ++    $('#click-counter').text(count) })

Use the following command to launch the app: $ electron ./main.js

416   ◾    Conquering JavaScript

We may create our native app in the same way that we create webpages. If we do not want users to be limited to a certain window size, we may utilize responsive design to enable them to use our app in a flexible way. In this chapter, we examined desktop apps built using electron.js, as well as their merits and downsides, as well as how to install electron.js.

NOTES 1 Building Desktop Apps with Electron and Vue: www.smashingmagazine.com/2020/07/desktop-apps-electron-vue-javascript/ Accessed on: 19 October 2022. 2 7 Famous Electron App Examples (JavaScript Desktop Apps): https:// brainhub.eu/library/electron-app-examples Accessed on: 19 October 2022. 3 Why You Should Use an Electron Alternative: https://blog.logrocket.com/ why-use-electron-alternative/ Accessed on: 19 October 2022. 4 Introducing the Electron.js Framework, Its Advantages and Disadvantages: https://ded9.com/introducing-the-electron-js-framework-its-advantagesand-disadvantages/ Accessed on: 20 October 2022. 5 Electron – Hello World: www.tutorialspoint.com/electron/electron_hello_ world.htm Accessed on: 20 October 2022. 6 Electron – Building UIs: www.tutorialspoint.com/electron/electron_building_uis.htm Accessed on: 20 October 2022.

Chapter

9

Appraisal

WHAT EXACTLY IS JAVASCRIPT? JavaScript was first developed with the intention of “bringing online pages to life.” Scripts are what you name the programs written in this language. They may be written directly in the HTML of a web page and will execute themselves as soon as the page loaded. Scripts are sent in plain text format and run in that format. They may be run without any further preparation or compilation being necessary. JavaScript is a programming language that is executed on the client side of the web and may be used to create and program how web pages react when a certain event takes place. JavaScript is a popular choice since it is both accessible and strong as a programming language. It is most often used to control the behavior of web pages. JavaScript is not ‘Interpreted Java,’ despite the widespread belief that this is what it is. JavaScript is a dynamic programming language that supports prototype-based object building. This is the gist of what JavaScript is. Because learning this language requires familiarity with a significant number of novel ideas, the fundamental grammar was designed to be conceptually comparable to Java and C++. Constructs of the language such as if statements, for and while loops, switch and try... catch blocks have the same functionality in each of these languages (or nearly so). The programming language JavaScript may operate in both a procedural and an object-oriented mode. In contrast to the syntactic class declarations that are prevalent in compiled languages such as C++ and Java, DOI: 10.1201/9781003356578-9

417

418   ◾    Conquering JavaScript

objects in JavaScript are formed programmatically. This is accomplished by adding methods and attributes to objects that are otherwise empty at the time of execution. After the construction of an item, that item might serve as a model (or prototype) for the construction of more items of the same kind.

JAVASCRIPT’S PAST AND ITS FUTURE JavaScript was first developed by Brendan Eich in 1995 for use with Netscape Navigator, which was the most popular web browser at the time. JavaScript made it possible for web developers to create more dynamic websites by allowing for the modification of visual components on the screen in real time in response to the actions of site visitors. There were a number of name changes made over JavaScript’s first half year of existence. It was at first known as Mocha, and afterward as LiveScript, before finally being given the name JavaScript. In spite of its name, the programming language JavaScript has no connection to the Java programming language. This is a fun fact. The cooperation that existed between Netscape and Sun Microsystems, the company that was responsible for developing Java, led to the creation of the term. These days, JavaScript is used for a far wider variety of purposes than only as a programming language for the web. Because it is a powerful and adaptable language that can be used in a number of different ways, you may write in JavaScript as you choose, whether you like imperative programming, a more object-oriented style, a functional approach, or even an event-driven model.

WHAT MAKES JAVASCRIPT UNIQUE? At a minimum, JavaScript has the following three wonderful qualities: • Complete incorporation of HTML and CSS. • Things that are simple can be accomplished with ease. • All of the main browsers provide support for it, and it is turned on by default. JavaScript is the only technology available for browsers that combines all three of these features.

Appraisal   ◾    419

This is what sets JavaScript different from other languages. Because of this, it is the tool that is used the most often for the creation of browser interfaces. Having stated that, JavaScript may be used in the creation of servers, mobile apps, and other types of software. Languages That Are “Superior” To JavaScript There are certain people for whom the syntax of JavaScript is not suitable. The preferences of various individuals might vary greatly. This is to be anticipated given the fact that each person’s projects and needs are unique to them. Therefore, in recent times a variety of new languages have emerged; in order for these languages to operate in a browser, they must first be transpiled, or converted, to JavaScript. These days, modern technologies make the translation process incredibly quick and easy to understand, which enables programmers to write code in one language while having it automatically converted ‘under the hood.’ These languages are some examples: • CoffeeScript is often referred to as the ‘syntactic sugar’ of JavaScript. It does this by introducing shorter syntax, which in turn enables us to create code that is more clear and exact. Ruby developers, on the whole, are fond of it. • TypeScript is focused on implementing ‘strict data typing’ to facilitate the creation and maintenance of complicated systems. Microsoft is the company that created it. • Data type is likewise added by Flow, but in a different manner. Facebook was the developer behind this. • Dart is a standalone programming language that operates in non-browser settings (like mobile applications), but it can also be transpiled to JavaScript for use in browsers. Its engine runs natively on the Dart platform. Designed and built by Google. • The use of Brython, which is a transpiler for Python to JavaScript, makes it possible to write apps in Python alone, without the need for JavaScript.

420   ◾    Conquering JavaScript

• Kotlin is a cutting-edge programming language that is terse, safe, and current. It may be used to target either the browser or Node. There are further ones. Even if we utilize one of these transpiled languages, to fully grasp the situation, we still need to be well-versed in JavaScript. In Comparison to Other Languages, JavaScript When it was initially released, JavaScript was nothing more than an additional Turing-complete option that had been introduced to Netscape’s browser. The majority of programmers laughed it off as a game, something that might be used to assess the accuracy of the information in the form or to add irritating popup windows. They missed the opportunity to seize the potential. Before it pushed forward-thinking features like lambdas and functions as first-class objects into the mainstream, not many people recognized the significance of the language’s innovative characteristics. It has been almost 20 years since then, and throughout that time, everything has changed. JavaScript serves as the basis for the vast majority of people’s interactions with the computer world, which takes place via web apps. Programmers are increasingly turning to Node.js for greater performance as well as the ability to execute the same code on the server as they do on the client. As a result, even server applications are increasingly built in JavaScript. The following is a quick comparison of JavaScript with some of the other main programming languages, written as a bulleted list for ease of reading. JavaScript Contrasted with C

• Compilation of C takes place in advance. Just-in-time (JIT) compilers are used to understand JavaScript during runtime, and the language is also sometimes built at this point. • C is statically typed. JavaScript is a dynamically typed programming language. • The C programming language needs its users to create and release chunks of memory. This is taken care of automatically by JavaScript. • When moving C code to a new processor, it is necessary to recompile the code. There is no need for JavaScript to be.

Appraisal   ◾    421

• Through the use of pointers, C is built to facilitate direct interaction with the memory of the computer. This ability is hidden behind JavaScript. • C is a programming language that is often used for embedded computers and applications that call for high levels of performance, such as operating systems. In the beginning, JavaScript was only included in web pages, but now it is being used in Node.js server applications, which is a relatively new use for the technology. • C provides users with explicit control over threads, but JavaScript encourages users to juggle several jobs by partitioning activities into asynchronous functions that are executed when data is available. C provides users with this level of control, whereas JavaScript does not. The Contrast between Java and JavaScript

• Compilation of Java results in bytecode, which is an intermediate form that is later executed by a JIT compiler. In the past, JavaScript was only ever executed via an interpreter; however, these days, a JIT compiler is often used. • To put it simply, Java is not a dynamically typed language, while JavaScript is a dynamically typed programming language. • In contrast to JavaScript, Java is a tightly typed programming language. • Java is built to serve massive applications and provides a strong namespace for these programs. JavaScript doesn’t supply it directly, therefore programmers have synthesized it. • Java was originally used in browsers as well as servers, although nowadays, it is mostly used on servers. Previously, JavaScript could only be executed in browsers; however, it is now very often employed on the server side. • Java and JavaScript both support a wide variety of other languages. Cross-compilers are able to translate a wide variety of languages such that they may be executed on Java’s JVM or JavaScript engines.

422   ◾    Conquering JavaScript

• Java 8 has included a method for embedding JavaScript, allowing the programming language to take use of numerous of JavaScript’s advantages. • Java provides the programmer with direct control over the threads. The call-and-response function structure of JavaScript helps to conceal a significant portion of this. When Compared to C#, JavaScript Is

• The C# programming language is reduced down to a form called bytecode, which is an intermediate form that is later executed by a JIT compiler. Once upon a time, the only way to process JavaScript was via interpretation. These days, however, a JIT compiler is often used. • JavaScript is dynamically typed, in contrast to the statically typed nature of C#. • JavaScript is not highly typed, in contrast to C#, which is. • JavaScript has different libraries that can cover this capability, one of which being Underscore.js. While C# has LINQ, a powerful.NET component that offers native data querying capabilities, JavaScript has independent libraries that can cover this feature. • The computer language C# provides precise control over the threads. The call-and-response function structure of JavaScript helps to conceal a significant portion of this. • Overloading of operators and conversions is available in C#. JavaScript does not. JavaScript Compared to the Programming Language Python

• The initial purpose of JavaScript was to provide support for HTML sites inside browsers. Python was designed to be executed through the command line in order to enable server environments (and desktops). • The communities that speak both languages are now much bigger. The field of social research has seen significant adoption of Python

Appraisal   ◾    423

as a data processing language. There are now instances of JavaScript on servers and in other places. • JavaScript denotes sections of code with brackets shaped like curly braces. Indentation and whitespace are used by Python. • Python’s argument blocks for methods may be as flexible as the user wants them to be, but JavaScript requires that every parameter be defined. • The execution of JavaScript code is often triggered by events such as clicks of the mouse or keystrokes. Calls made to functions are acknowledged by Python. • The processing and analysis of data are the primary emphases of many Python libraries, while the manipulation of HTML in a browser is the primary focus of many JavaScript tools. When Compared to PHP, JavaScript Is

• Both of these scripting languages were initially interpreted at runtime, but nowadays, a JIT compiler is often used to do the necessary transformations. • Both have variables that may be written dynamically. • In the beginning, PHP was created to be used on servers to compile HTML pages, whereas JavaScript was meant to run inside of browsers on client computers. At this time, JavaScript is also capable of constructing HTML files on the server. • PHP is almost never used for anything other than putting together HTML. The ever-more-complex interfaces in the browser and server-side stacks that integrate business logic and databases rely on JavaScript as their basis. • PHP is a programming language that is designed to get data from databases and format it using HTML. It is a very straightforward language. JavaScript is evolving into a language that may be used for a wider range of applications, including general computing and interaction with browsers.

424   ◾    Conquering JavaScript

JavaScript Compared to the Programming Language Ruby

• In the past, operating JavaScript was restricted to the client’s browser, whereas Ruby was executed on the server in conjunction with the Rails framework. • The Ruby on Rails framework provides an inspiration for many of the principles that are used in JavaScript while it is executing in Node.js on the server. • Ruby and JavaScript are both examples of dynamically typed programming languages. • In Ruby, the term ‘end’ is used to denote the end of a block, while curly brackets are used in JavaScript. • Ruby takes more of its syntax from Perl and Smalltalk, whereas JavaScript takes a significant portion of its syntax from Java and C. • Ruby is mainly confined to server applications that use its Rails framework; nevertheless, some administrators like Ruby for their server-supporting command-line programs. On the other hand, JavaScript is transitioning to become a general-purpose programming language. As can be seen, JavaScript diverges significantly from a good number of the other common programming languages. Its first version was created in only 10 days, but it included a number of forward-thinking improvements that allowed it to survive into the present decade. These innovations let it survive into the current decade. There are many problems, yet, it seems that it will continue to be a key language for frontend developers for as long as it is the only language that all browsers understand. Opportunities for Professional Development in JavaScript Frontend Web Developer It entails the construction of a user-facing and visually appealing portion of a website. This position will mostly include working with HTML, CSS, JavaScript, and a basic backend. You probably have a good understanding

Appraisal   ◾    425

of several ideas that go beyond the fundamental technologies, such as performance testing or regression testing. The following is a list of the duties of a Frontend Developer: • Develop new software applications from the idea to conclusion, including frequent testing and maintenance. • In order to construct normal programs and libraries for the future applications. • Ensure that the technical capabilities of the UI/UX design are met. • Before sending any user inputs to the backend service team, it is imperative that all of those inputs be checked for authenticity. • Collaborate with the other members of the team as well as the investors. Designer and Developer of Web Applications Developing software applications that run on the web, such as interactive online forms, shopping carts, word processing and spreadsheet programs, video and picture editors, file converter tools, scanning programs, and email software. Desktop programs that are cross-platform are often created on platforms such as Adobe AIR, whereas ELECTRON makes use of JavaScript. In the process of developing interactive web pages. It would be preferable to use a JavaScript framework such as jQuery that extends your JavaScript capabilities in order to make this JavaScript simpler. This role is distinct from that of a Frontend Developer since there is less emphasis placed on design and more on the principles behind programming.

Developer Skilled in JavaScript It is the responsibility of a JavaScript developer to connect this newly generated element with the services that are already in place on the backend. In most cases, the developer will get assistance from the backend web designer, who is liable for the whole of the server-side application logic. Together with other frontend web developers who focus on the application’s HTML and aesthetics, a JavaScript developer often collaborates on projects with these

426   ◾    Conquering JavaScript

colleagues. Programming and application development are the responsibilities of a JavaScript developer. In addition to that, he is accountable for • Creating new features for, and improving, the primary frontend website platform. • Developing new functions that are focused on the end user. • Helping out with frontend work on other programs (HTML/CSS/ JavaScript in Ruby and Python application), along with the designing and programming of new frontend applications for a variety of different platforms. • Performing code analysis, analysis of requirements, analyses of system risk and software dependability, and identification of code metrics. UX/UI Designer It is the process of analyzing and investigating how people use a certain website. The next step is to test the outcome of the system after implementing improvements that will make it better. A rich earning potential may be attained by possessing knowledge of both user experience designing and JavaScript. They are also quite proficient in the design tools of choice; however, their skill set may simply include HTML and CSS. In addition to being familiar with JavaScript, the employee should have expertise in interface design. The people who are responsible for the user interface might also be referred to as visual designers. DevOps Engineer This position helps to close the communication gap between IT and developers. In addition to that, they are investigating things like server software, version control, deployment, build procedures, and testing servers and processes. The following is a list of the tasks of a DevOps Engineer:

• Putting out updates and addressing any technical problems that may have arisen. • Developing tools to reduce the number of errors that users encounter while also enhancing their overall experience.

Appraisal   ◾    427

• Developing software to work in coordination with existing backend systems inside the organization. • Carrying out an investigation into the underlying causes of production problems. • Developing scripts in order to automate the process of visualization. • Developing processes for debugging the system and doing general maintenance on it. Developer Who Works on All Layers It is comparable to the work done on the frontend and the backend. The company is looking for persons with very high levels of expertise, since this is a very prestigious position. For the position of Full Stack Developer in JavaScript, the following responsibilities and competencies are required:

• Create a blueprint for the whole structure of the web application. • Collaborating with the technical team to develop new features via design and testing. • Having experience in developing for both mobile and desktop platforms is advantageous. • The skills and understanding to secure sensitive information. • Should have prior knowledge with languages used for backend development (Example: JavaScript, Ruby, PHP, Python, Java, .NET, etc.). • A history of collaboration with graphic designers and experience translating concepts into visual components. What Is the Most Appropriate Framework for JavaScript? An abstraction, a web development framework enables software to offer broad functionality and be tailored in specific ways with the addition of user-written code. These modifications may be made in a variety of ways. One definition of a JavaScript framework is an application framework written in JavaScript that may be customized by developers for their own needs. Because frameworks are more malleable for use in web design, the vast majority of website developers choose to work inside them. Frameworks

428   ◾    Conquering JavaScript

simplify and streamline the process of working with JavaScript, opening up possibilities such as making apps more responsive to the device being used. Therefore, Vanilla js is considered to be one of the greatest frameworks for JavaScript. Vanilla js Plain JavaScript is what’s referred to as Vanilla js, and you’ll notice that developers utilize Vanilla js to produce JavaScript code that doesn’t need the assistance of any libraries. You will see that Vanilla js is a scripting language that does not impose any restrictions or guidelines on the developers about the manner in which the data in the application may be defined. There is a possibility that apps written with vanilla.js may not always provide the most optimal outcomes for the application. You will see that Vanilla js is very popular among developers. This is because it is widely acknowledged as one of the simplest frameworks, making it accessible to developers of all levels. Why Do We Believe That Frameworks Written in JavaScript Are so Awesome? They alleviate your burden by simplifying the difficult and convoluted code. They allow you to ship code more quickly and boost the pace of your work. They challenge you to concentrate more on the value of your app rather than the execution of it. Collaboration is, in our opinion, the JS framework that offers the best potential return on investment. Because of their standardized user interface and methodologies, software engineers from different countries, such as Canada, the United States, and Brazil, are able to communicate with one another and collaborate effectively. When the time comes, you will be able to discover an experienced developer who can confidently step into the project codebase if you are creating an app using [insert your preferred framework]. This individual will be able to begin working on features without you having to spend time explaining every aspect of your software architecture to them. Practice is yet another important reason why frameworks should be used. They will make you practice on and off throughout the day. That’s fantastic news! Whatever it is that you’re working for, mastery can only be achieved via consistent practice.

Appendix I JavaScript Cheat Sheet

W

e must join the JavaScript file to the HTML file in order to utilize JavaScript on the website. Including comments in the coding ­process will help us produce better code overall. One may use either single-line or multi-line comments. • In order for the browser to recognize that your code is written in JavaScript and execute it, you must enclose the code in [delete] tags and paste it into your HTML page.

• An outside JavaScript report also can be written one after the other and blanketed inside our HTML report the usage of the script tag as:

• JavaScript comments are very useful for explaining JavaScript code, understanding what is happening in the code, and making it easier to read.

429

430   ◾    Appendix I

1. Single-line comments: It starts with “//”. 2. Multi-line comments: Enclose comments that span multiple lines with /* and */.

INSTANCES OF JAVASCRIPT VARIABLES JavaScript variables are merely the names of data storage areas. As such, we may utilize them as surrogate values in our JavaScript programs and still accomplish a wide range of tasks. You have three options when working with variables in JavaScript. • When it comes to JavaScript, var is by far the most used variable. Only inside the scope of a function may it be redeclared and its value transferred. Variables declared using var will rise to the top of the stack when the JavaScript code is executed. This is an example of a variable declared with the “var” keyword in JavaScript: var x = 140; // x may be redeclared and given a new value at any time • To avoid unexpected results, const variables in JavaScript must be declared in the body of the code before they may be utilized. They cannot be redeclared or have their values changed in any way over the course of the program’s execution. Listed below is an example of a JavaScript variable defined using the “const” keyword: const x = 5; // It’s not possible to change the value of the variable x • similar to the const variable, the let variable cannot be redeclared. However, their worth may be changed. The following is an example of a variable defined using the “let” keyword in JavaScript: let x = 202; // The variable x cannot be redeclared, although its value may be changed, as in let x = 202;

DATATYPES IN JAVASCRIPT JavaScript variables may hold a wide variety of data. The equals (=) sign operator is used to assign values to variables in JavaScript. JavaScript supports the following data types:

Appendix I   ◾    431

• Variables: The variable data type may take on a wide range of values since, well, it’s called a variable. Below is an example of a variable’s data type: var y • Strings: Multi-character sequences of varying lengths that make up JavaScript’s string data type. You can see how the string data type is used in the following code snippet: var demoString = “Hello World.” • Numbers: These are only figures. All integers and real numbers are equally acceptable. Here’s an example of the numeric data type in action: var id = 100 • Operations: You may also attach operations in JavaScript to variables. • Objects: Objects in JavaScript are storage locations for a set of named values known as properties. They are responsible for their own informational components and procedures. Below is an example of the objects data type: var name = “name:”Jon Snow”, id:”AS123” • Boolean value: A Boolean value is one that may be either true or false. Below is a code snippet demonstrating the use of the boolean data type: var booleanValue = true. • Constant numbers: Data types with a constant value are called “constant numbers.” The following is an instance of the constant data type: const g = 9.8

OPERATORS OF JAVASCRIPT You can use JavaScript operators on variables to perform a wide range of operations. These are the numerous kinds of operators that may be used in JavaScript: JavaScript’s fundamental operators allow for elementary arithmetic operations like addition and multiplication to be carried out. Here is an index of all JavaScript’s primitive operators: • To add two integers together, use the plus sign (+). • To do a subtraction operation, utilize the “Subtraction Operator (–).” • Multiple numbers may be multiplied with the help of the MultiplicationOperator (*).

432   ◾    Appendix I

• In order to do a division, we need to utilize the Division Operator (/). • By enclosing an expression or sub-expression in parenthesis with the (...) grouping operator, the order of evaluation of the operators is changed such that the ones with lower precedence are evaluated first. • When dividing by another integer, the residual may be found with the help of the Modulus operator (%). • To add one to an integer, use the Increment operator (++). • When using the Decrement operator (--), the value of a number is reduced by 1. Bitwise Operators Using JavaScript’s bitwise operators, you can execute any operation that involves a number’s bits. Here’s a rundown of all the bitwise operators available in JavaScript: • The bitwise AND operator, (&), produces a result of 1 for every bit location where the corresponding bits in both operands are 1. • Wherever bits in each or both operands are 1, the bitwise OR operator (|) delivers a 1. • Bitwise NOT is an operator (~) that flips the bits in the operand. Like other bitwise operators, it converts the operand to a signed 32-bit integer. • Each bit location in which the corresponding bits of both operands are 1s but not both is returned by the bitwise XOR operator (^). • The left shift operator (≪) moves the bits of the first operand to the left by the amount specified. • By providing a positive integer, the right shift operator (≫) will shift the first operand to the right by that many bits. Comparison Operators JavaScript has a number of comparison operators, all of which are listed below. • Whenever its two operands are equal, the equality operator (==) will return a true or false result.

Appendix I   ◾    433

• When its two operands are of the same type and equal in value, the equivalent operator (===) returns a Boolean. • The inequality operator (!=) returns a boolean if the two operands are not equal. • If the two operands are not the same type, or if they are not equal, the inequal operator (!==) will return a Boolean result. • In JavaScript, only the conditional (ternary) operator accepts three operands: a condition followed by a question mark (?), an expression to run if the condition is true followed by a colon (:), and a final expression to execute if the condition is false. • If the left operand has a smaller value than the right operand, then the Lesser than operator (=) operator evaluates to true if and only if the left operand is greater than or equal to the right operand. • Less-than-or-equal-to (=) is an equality operator ( { return ‘Happy birthday ${name}, you are now ${age} years old!’; }; const birthdayHero = “Jane User”; const age = 22; console.log(birthdayGreeter(birthdayHero, 22));

The above example shows how to construct a function with two arguments: name and age. We give the name field a type of string and the age field a type of number. The value that is returned by a function may also have types assigned to it. In this particular instance, our function is going to return a value of the string data type. const birthdayGreeter = (name: string, age: number): string => { };

If we sent in arguments of a type that was different from the type that Typescript anticipates, we would get an error.

Appendix II   ◾    453

TypeScript’s Support for Structural Typing The programming language TypeScript is a structurally typed language, which means that in order for two items to be deemed to be of the same type, they must have equivalent and similar properties. Inference of Type Utilizing TypeScript In the event that no explicit type is supplied, the TypeScript compiler may make an attempt, based on its own logic, to infer the type information. This suggests that TypeScript is able to give a type to a variable or function based on the initial values of the variable or the application of the function, respectively. When you create variables, set default values, or figure out the type of the result that a function should return, you are most likely engaging in some kind of type inference. const platform = ‘freeCodeCamp’; const add = (a: number, b: number) => a + b

In the example that was just shown, the variable platform is given the type string even though we did not do so explicitly. Additionally, the return value of the function add is assumed to have the type number. Deleted Characters in TypeScript During compilation, TypeScript eliminates the following constructs of the type system: Input let x: someType; Output let x;

WHY SHOULD YOU USE TYPESCRIPT? Checking for Typos and Doing Static Analysis of the Code Since of this, the total number of faults in your code will decrease overall because TS will alert you whenever you make an incorrect usage of a particular type.

454   ◾    Appendix II

Runtime errors are also reduced, and since TypeScript does static code analysis, you will get warnings if any typos or other issues are found in your code. Therefore, there will be fewer mistakes, which might lead to testing being reduced in scope. Annotations on Types May Serve in Place of Documentation for Code Because of annotations on types, we are able to comprehend, for instance, what kinds of inputs a function anticipates receiving and what kinds of outcomes it will return. In addition, we are able to comprehend what kinds of outputs the function will deliver. This makes the code easier to read, which in turn makes it simpler not just for ourselves but also for others to comprehend what the code is intended to do. Users of integrated development environments (IDEs) are able to get more accurate and insightful IntelliSense feedback while using TypeScript, which is another benefit of utilizing this programming language. This is made feasible by the fact that IDEs are aware of the particular kind of data that the user is currently processing, which enables this functionality.

STARTING OUT WITH TYPESCRIPT: A CRASH COURSE Installing the TypeScript package is where we should get started. In this situation, we have two choices: we can either install it globally so that we can use it on any project in the system, or we can install it locally so that we can use it just on the project that we are now working on. By executing the following command, you will be able to install TypeScript globally: npm install -g typescript

If you do not want to install anything worldwide, you need to perform this command: npm install --save-dev typescript

Because we find it useful throughout the development process, TypeScript was included in the local installation as a development dependency. First, it has to be compiled to JavaScript before it can be used in production. The TypeScript language cannot be executed in the browser.

Appendix II   ◾    455

After TypeScript has been installed, the first step in getting started is to create a new project. You are able to do this by using the following command: tsc --init

With the execution of this command, a brand-new tsconfig.json file will be created in the project’s parent directory. This configuration file includes all the configuration settings available to us when we use TypeScript in a project. You may provide all of the build settings for a given project in the tsconfig.json file under the compileOptions key. This file is located in the root directory of the project. There are certain config settings already included in the file, but you have the ability to add additional options to the project if necessary. You may comment out or eliminate unneeded compiler options. Establishing the Baselines for Your TypeScript Development Environment Setting Up Your Development Environment

Code Editor  You need an integrated development environment (IDE) that supports TypeScript to use all the capabilities that TypeScript has to offer. Although we suggest Visual Studio Code (which is also designed in TypeScript), you may use any integrated development environment (IDE) that supports TypeScript. Node.js and npm  Each of the projects described in this book calls on a functional Node.js development environment, in addition to using npm. When you install Node.js, a JavaScript package management called npm is automatically installed on your computer. Open a new terminal window and put in the following command to determine whether or not npm is compatible with your development environment. $ npm -v

If an error is shown or a version number is not written out, be sure you download a Node.js installation that contains npm.

456   ◾    Appendix II

Beginning the Process  Launch a terminal and go to the directory that will serve as the project’s storage location for its files. Moving forward, we will be putting new files into the directory containing our project. In the following instances, the root folder of our project will be referred to as FinanceMe since we will be utilizing that name throughout. Start with the package.json Initialization  Our project’s package.json file includes essential information, such as the list of dependencies that must be installed, and is located in the corresponding directory. Executing the following command will result in our package.json being initialized: $ npm init --yes

Install the TypeScript# Language Simply enter the following line into your terminal to install the most recent version of TypeScript: $ npm install --save-dev typescript

The tsc (TypeScript compiler) version number will be shown in the output of the following command if the installation was completed successfully: $ npx tsc -v

Install ts-node  ts-node is a tool that allows TypeScript applications to be executed straight from the terminal. This eliminates the need to compile. ts files to.js files and then execute the produced files, which is the procedure that would normally be required. Execute the following command in order to install the most recent version of ts-node: $ npm install --save-dev ts-node

The ts-node version number will be shown if the installation has completed successfully by using the following command: $ npx ts-node -v

The ts-node command operates in a manner that is similar to that of the node command. If the command is given the name of a file, then that file

Appendix II   ◾    457

will be executed, and the program will terminate after the file has completed its execution. We will be put in interactive mode if we do not provide the command with a file name. This mode allows us to import modules and perform TypeScript commands while they are being executed in real time. The interactive mode is very helpful for testing pieces of code that are just a few lines long. Execute the following command in order to begin the interactive mode: $ npx ts-node

Since we are now in the interactive mode, we will be able to execute code in real time. In the following example, we will do a straightforward computation, and the result will be printed: $ > $ $ >

10 + 30 + 2 42 const today = new Date() today.getFullYear() 2019

It is important to take note that we may define variables and utilize them throughout the session. Additionally, we do not need to report stuff directly by using the console.log() function since the result of the statement being run will be written automatically. You may enter editor mode to copy and paste a block of code or to alter code that spans numerous lines. When you do so, execution will be paused until you simultaneously click the CTRL and D keys. $ npx ts-node $.editor $ /* * code can span multiple lines * will run when you press CTRL+D */

You may quit interactive mode by using CTRL+C or by simply typing.exit followed by pressing enter on your keyboard. Initialize tsconfig.json  Our integrated development environment (IDE) and the ts-node will use the key compiler information stored in the tsconfig.json file.

458   ◾    Appendix II

In the directory of the project, create a file called tsconfig.json and include the following settings in it: { “compilerOptions”: { “target”: “es6”, “module”: “commonjs”, “typeRoots”: [“./node_modules/@types”], “esModuleInterop”: true, “forceConsistentCasingInFileNames”: true } }

Further discussion of each compiler option will be provided in the next chapter, titled “Compiler Options,” but in the meanwhile, here is a quick description of what each of the aforementioned settings does: • target: This option allows you to choose the version of ECMAScript the compiler will use when producing JavaScript files. We are able to use all of the capabilities that were added in ES6/ES2015 as a result of setting this to es6. • module: This option allows you to specify the module system being used in the code being created. We have confirmed that our code is capable of running in Node.js by setting this to the commonjs value. • typeRoots is an option that allows you to specify the directory in which TypeScript should look for global types. In order to avoid inadvertently inheriting types from parent directories, we configure it here to point to our own node modules/@types directory (which is the default behavior). • esModuleInterop: This option guarantees that CommonJS and ES Modules are compatible with one another and is referred to as esModuleInterop. • forceConsistentCasingInFileNames: We may use an option to guarantee that we do not bring defects into the system by inadvertently importing a module with the wrong case.

Appendix II   ◾    459

• Because VSCode and ts-node will automatically discover a tsconfig. json if it is there, there is no need to make any adjustments to any of these programs.

TYPESCRIPT FOR DEVELOPERS WORKING IN JAVASCRIPT The connection between TypeScript and JavaScript is not what one may expect. TypeScript provides all of the functionality that JavaScript does, in addition to an extra layer on top of these features called the type system for TypeScript. JavaScript, for instance, offers language primitives such as strings and numbers, but the programming language does not verify to ensure that you have consistently allocated them. TypeScript does. This indicates that the JavaScript code you have already written that is functioning properly is also valid TypeScript code. The primary advantage of using TypeScript is that it reduces the likelihood of errors by pointing out areas of your code that exhibit unexpected behavior. Types Deduced from Inference TypeScript is familiar with the JavaScript programming language and can, in many instances, automatically create types for you. For instance, when a variable is created in TypeScript and a specific value is assigned to it, TypeScript will utilize the value as the variable’s type. let helloWorld = “Hello World”; let helloWorld: string

TypeScript can construct a type system compatible with JavaScript code but also has types since it understands how JavaScript works. This provides a type system without requiring you to add more characters to your code in order to make the types obvious. That is how TypeScript is able to determine that the helloWorld variable represents a string in the example that was just shown. You could have used the editor auto-completion feature in Visual Studio Code while you were writing JavaScript. Under the hood, Visual Studio Code uses TypeScript, simplifying the process of working with JavaScript.

460   ◾    Appendix II

Defining Types JavaScript gives you access to a vast library of different design patterns to choose from. Nevertheless, design patterns make it more challenging for types to be inferred automatically (for example, patterns that use dynamic programming). TypeScript is an extension of the JavaScript programming language that enables locations for you to tell TypeScript what the appropriate types are. This was done to accommodate the scenarios described above. For instance, the following code may be written to construct an object with an inferred type that has the attributes name: string and id: number: const user = { name: “Hayes”, id: 0, };

You may provide a detailed description of the form of this object by using an interface declaration: interface User { name: string; id: number; } const user: User = { username: “Hayes”, Type ‘{ username: string; id: number; }’ is not assignable to type ‘User’. Object literal may only specify known properties, and ‘username’ does not exist in type ‘User’.Type ‘{ username: string; id: number; }’ is not assignable to type ‘User’. Object literal may only specify known properties, and ‘username’ does not exist in type ‘User’. id: 0, };

TypeScript supports classes and object-oriented programming in the same way as JavaScript does because of this. A declaration of an interface may be used while working with classes:

Appendix II   ◾    461 interface User { name: string; id: number; } class UserAccount { name: string; id: number; constructor(name: string, id: number) { this.name = name; this.id = id; } } const user: User = new UserAccount(“Murphy”, 1);

You can use interfaces to annotate parameters and return values to functions: function getAdminUser(): User { //... } function deleteUser(user: User) { //... }

An interface may use the following basic types currently accessible in JavaScript: Boolean, bigint, null, number, string, symbol, and undefined. TypeScript adds a few more to this list, such as any (which means ‘allow anything’), unknown (which means ‘ensure that someone using this type announces what the type is’), never (which means ‘it is not conceivable that this type might exist’), and void (which simply means ‘nothing’). Additionally, you have the option to build your own kinds. You are going to discover that there are two different syntaxes for constructing types: interfaces and types. You should give interface more weight. When you require characteristics that are quite particular, use the type.

462   ◾    Appendix II

Forms of Composition You may construct more complicated types by mixing TypeScript’s simpler ones using the language. There are two common approaches to accomplishing this goal: via the use of unions and generics. Unions You can define, when using a union, that a type may be any of a number of other types. You might, for instance, characterize a boolean type as having the property of either being true or false: type MyBool = true | false;

Note: If you move your cursor over the word “MyBool” in the sentence above, you’ll see that it has the boolean classification. That is one of the characteristics that the Structural Type System has. More about this may be found below. One of the most common applications of union types is to express the set of string literals or integer literals that a value is permitted to be: type WindowStates = “open” | “closed” | “minimized”; type LockStates = “locked” | “unlocked”; type PositiveOddNumbersUnderTen = 1 | 3 | 5 | 7 | 9;

Unions provide a solution to the problem of juggling several kinds. You may have a function that accepts either an array or a string, such as the following: function getLength(obj: string | string[]) { return obj.length; }

USER AND EXPENSE ARE TWO OF TYPESCRIPT’S CLASSES JavaScript that is object oriented is known as TypeScript. The objectoriented programming concepts like classes, interfaces, and other such things are supported by TypeScript. In object-oriented programming (OOP), a class functions as a template for the creation of objects. The data for the object is included inside the class. This idea, which is referred to as class, has built-in support provided by Typescript. Classes were not supported in JavaScript versions prior than ES5, though. This functionality is brought to Typescript by ES6.

Appendix II   ◾    463

Developing Classes To define a class in TypeScript, you will need to use the class keyword. The syntax for the same may be found down below: Syntax class class_name { //class scope }

The name of the class comes immediately after the class keyword. When naming a class, it is necessary to take into consideration the rules that govern identifiers. The following is an example of what may be included in a class definition: • Fields that are defined inside a class might be referred to as fields. The data associated with objects is represented via fields. • Constructors are in charge of allotting memory for the objects of that class. • Functions are a representation of the many activities that an object is capable of doing. Methods is another term that is sometimes used to refer to them. When taken as a whole, these components make up what are known as the data members of the class. Consider the typescript version of the class Person. class Person { } On compiling, it will generate following JavaScript code. //Generated by typescript 1.8.10 var Person = (function () { function Person() { } return Person; }());

464   ◾    Appendix II

A Class Declaration as an Example class Car { //field engine:string; //constructor constructor(engine:string) { this.engine = engine } //function disp():void { console.log(“Engine is : “+this.engine) } }

An instance of the class Car is declared in the example. The name of the field in this class is engine. In the process of defining a field, the var keyword is never utilized. The function Object() { [native code] } for the class has been declared in the preceding example. A class’s function Object() { [native code] } is a specialized function that is responsible for initializing the variables that belong to the class. It is called a function Object() { [native code] }. The function Object() { [native code] } keyword in TypeScript is what really specifies the function Object() { [native code] }. Since a function Object() { [native code] } is a function, it is possible to provide parameters into it. The “this” keyword refers to the instance of the class that is now being worked with. In this case, the name of the field in the class and the name of the argument are identical. As a result, in order to prevent confusion, the field of the class is prefixed with this keyword. disp() is an example of a straightforward function definition. It is important to take note that the function keyword is not utilized in this context. Following is an example of the code that will be generated when you compile it. //Generated by typescript 1.8.10 var Car = (function () { //constructor function Car(engine) {

Appendix II   ◾    465 this.engine = engine; } //function Car.prototype.disp = function () { console.log(“Engine is : “ + this.engine); }; return Car; }());

Creating Objects of Instance Use the new keyword, then follow it up with the name of the class to create a new instance of the class. The syntax for the same may be found down below: Syntax var object_name = new class_name([ arguments ])

An Example of Instantiating a Class  var obj = new Car(“Engine 1”)

CLASS INHERITANCE The idea of inheritance may be implemented using TypeScript. A computer program’s capacity to derive new classes from pre-existing classes is referred to as inheritance. The class that serves as the basis for the creation of subsequent classes is referred to as the parent class or the super class. The classes that have just been produced are referred to as the kid or sub classes. The ‘extends’ keyword allows one class to inherit properties and behaviors from another. Child classes take on all of the attributes and methods of their parent classes, with the exception of any private members and constructors. The term “inherited” may also be used to refer to: • Single—Each child class may only inherit from a single parent class at the most. • Multiple—A class may take inheritance from more than one other class. There is currently no support for multiple inheritance in TypeScript.

466   ◾    Appendix II

• Multi-level—Inheritance on Several Levels The following example demonstrates how inheritance may occur on multiple levels. Data Hiding A class has the ability to govern how other classes’ members see the data that is stored in its members. This functionality is sometimes referred to as data encapsulation or data hiding. The idea of encapsulation is realized in Object Oriented Programming via the use of the concepts of access modifiers and access specifiers. Access specifiers and modifiers determine whether or not a class’s data members are visible to classes other than the one that defines them. public Everyone may view the information contained in a public data member. The default access level for data members of a class is public. private Only other instances of the class that define a private data member’s definition may access that member’s data. An error is generated by the compiler whenever an external class member makes an attempt to access a private member. protected A protected data member is available not only to members of the same class as the member being protected, but also to members of any child classes that the parent class may have.

INTERFACES An Outline of TypeScript Interfaces Interfaces in TypeScript are what specify the agreements between different parts of your code. Furthermore, they provide granular names for use in type verification. First, let’s look at a straightforward illustration: function getFullName(person: { firstName: string; lastName: string

Appendix II   ◾    467 }) { return ‘${person.firstName} ${person.lastName}’; } let person = { firstName: ‘John’, lastName: ‘Wick’ }; console.log(getFullName(person)); Code language: TypeScript (typescript)

Output John Wick Code language: TypeScript (typescript) Here, the parameter to the getFullName() method is verified by the TypeScript compiler. The TypeScript compiler will allow the argument to proceed if it contains two properties of type string. In such case, it will throw an error. The code itself demonstrates how the type annotation of the function parameter complicates the code and makes it more difficult to comprehend. TypeScript’s idea of interfaces was designed with this problem in mind. In the following, a Person interface with two string attributes is used: interface Person { firstName: string; lastName: string; }

Format of code: CSS (css) The standard for naming interfaces is to use camel case. In their names, just the first letter of each word is capitalized. Such as FullName, UserProfile, and Person. The Person interface may be used as a type as soon as it is defined. The name of the interface may also be annotated on a function’s argument. function getFullName(person: Person) { return ‘${person.firstName} ${person.lastName}’; } let john = { firstName: ‘John’, lastName: ‘Doe’

468   ◾    Appendix II }; console.log(getFullName(john)); Code language: TypeScript (typescript)

The code is much more readable now. Function Types Interfaces enable you to specify the sorts of functions as well as the characteristics of an object. To specify a function type, you attach the interface to the function signature that includes the argument list with types and returned types. For instance: interface StringFormat { (str: string, isUpper: boolean): string } TypeScript, a programming language (typescript) It is now possible to use this interface for functions of a certain type. Assigning a value of the same type to a variable declared as a function is seen below. let format: StringFormat; format = function (str: string, isUpper: boolean) { return isUpper? str.toLocaleUpperCase() : str. toLocaleLowerCase(); }; console.log(format(‘hi’, true)); Code language: TypeScript (typescript)

Output HI

OBJECTS IN TYPESCRIPT A collection of key-value pairs that make up an object is called an instance. The values might be anything from simple numbers to functions or arrays of other things. Here is the syntax:

Appendix II   ◾    469 var object_name = { key1: “value1”, //scalar value key2: “value”, key3: function() { //functions }, key4:[“content1”, “content2”] //collection };

As was just shown, objects may store not just scalar values and functions, but also arrays and tuples and other structures.

TYPE TEMPLATE FOR TYPESCRIPT Suppose you wrote the following JavaScript object literal: var person = { firstname:”Tom”, lastname: “Hanks” };

In the event that you need to alter an object’s value, JavaScript provides the functionality you need. Let’s say we find later on that the Person object needs an extra feature. person.sayHello = function(){ return “hello”;}

The Typescript compiler returns a compilation error if you try to utilize the same code. Concrete objects in Typescript must have a corresponding type template. In Typescript, all objects must represent concrete examples of predefined classes. Duck-Typing If two objects have the same set of characteristics, then they are said to be of the same type in duck-typing. Instead of checking the exact type of an object, duck-typing instead ensures that particular attributes are present [2–13]. TypeScript’s compiler makes use of the duck-typing system, which permits dynamic object generation without compromising type safety. In the next example, we’ll see how to send objects to a method that don’t directly implement the interface but nevertheless have all the necessary members.

470   ◾    Appendix II

NAMESPACES IN TYPESCRIPT Using a namespace allows you to organize your code in a meaningful manner. TypeScript was designed with this feature in mind, unlike JavaScript, where variable declarations are placed in a global scope and might be overwritten or misunderstood if various JavaScript files are used inside the same project. Namespace Determination In order to define a namespace, you must first use the term “namespace,” followed by the actual namespace’s name, like in namespace SomeNameSpaceName { export interface ISomeInterfaceName { } export class SomeClassName { } }

The term export must be used to indicate which classes or interfaces should be exposed outside of the namespace. The syntax for using a class or interface that is defined in a different namespace is to use the form namespaceName.className. SomeNameSpaceName.SomeClassName; If the initial namespace is defined in a completely distinct TypeScript file, the triple slash reference syntax must be used to access it. ///

Nested Namespaces An nested namespace definition looks like this: namespace namespace_name1 { export namespace namespace_name2 { export class class_name { } } }

MODULES IN TYPESCRIPT The goal of this TypeScript module is to provide a means of encapsulating and reusing similar pieces of code. It is possible to categorize modules as follows:

Appendix II   ◾    471

• Internal Modules • External Modules Internal Modules Typescript’s internal modules debuted in a previous version. This was done so that classes, interfaces, and functions could be logically grouped together into a single unit that could be exported to another module. In TypeScript’s newest iteration, this logical classification is known as a namespace. As a result, namespace is superior than internal modules. While we currently allow internal modules, we strongly advise using namespaces instead. Syntax of Internal Module (Veteran) module TutorialPoint { export function add(x, y) { console.log(x+y); } }

External Module The purpose of TypeScript’s external modules is to allow developers to declare and load dependencies between numerous external js files. There is no need for external modules if just a single.js file is being utilized. Historically, browser script tags (script>/script>) were used for managing dependencies between JavaScript files. However, that can’t grow with your needs since module loading is so slow. This implies that loading modules asynchronously is not an option and files must be loaded sequentially. Script tags don’t even exist in server-side JS languages like NodeJs. Dependent js files may be loaded in one of two ways, both of which involve a single primary JavaScript file. • Server Side - NodeJs • Client Side - RequireJs

FUNCTIONS IN TYPESCRIPT Code that is understandable, easy to maintain, and versatile relies heavily on its functions as its fundamental building blocks. A collection of statements designed to carry out a certain activity is known as a function.

472   ◾    Appendix II

The functionality of the software is broken down into logical sections by the functions. When they have been defined, functions may be used to access code by calling them. This enables the code to be used in several places. In addition, functions simplify the process of reading and maintaining the code of a program. A function declaration provides the compiler with information about a function’s name, as well as its arguments and return type. The meat and potatoes of a function is its body, which is provided by the function specification. • Defining a Function: A function description describes both the specifics of a job and the manner in which it should be completed. • Invoking a Function: Before a function can be put into action, it must first be invoked. • Returning Functions: Functions may return control and value back to the person who called them in a process known as “returning functions.” • Parameterized Function: Parameters are a means through which values may be sent to functions. Parameters That Are Optional It is possible to utilize optional parameters in situations in which it is not necessary to supply arguments to a function in order for it to be executed. Putting a question mark in front of the name of a parameter is one way to indicate that it is optional. When calling a function, the optional parameter should be sent in as the very last argument. The declaration syntax for a function that may or may not take an optional argument looks like this: function function_name (param1[:type], param2[:type], param3[:type])

Rest Parameters Rest parameters are analogous to variable arguments in Java. The amount of different values that may be sent to a function is not limited in any way by rest parameters. However, all of the values that are handed in need to

Appendix II   ◾    473

have the same type. To put it another way, rest parameters serve the purpose of being placeholders for many arguments of the same type. The name of the parameter is given a prefix consisting of three periods when it is declared to be a rest parameter. Any parameter that is not involved in rest should appear before the rest parameter. Default Parameters It is also possible to set values by default to the arguments of a function. On the other hand, values for such parameters may also be provided in directly.

Syntax function function_name(param1[:type], param2[:type] = default_value) { }

NUMBERS IN TYPESCRIPT The Number class performs the function of a wrapper and makes it possible to manipulate numeric literals as if they were objects. Numeric values may be represented as Number objects in TypeScript, just way JavaScript does. A numeric literal may be converted into an instance of the number class by using a number object. Syntax var var_name = new Number(value)

In the event that the Number function Object() { [native code] } is given an argument that is not a number, it will return NaN. (Not–a–Number)

ARRAYS IN TYPESCRIPT Making use of variables to store values provides a number of issues, some of which are as follows:

474   ◾    Appendix II

• Variables are scalar in nature. To put it another way, a variable declaration can never contain more than one thing at a time regardless of the circumstances. This suggests that in order for a program to be able to hold n values, there will need to be n variable declarations made before the program can be run. When one has to retain a larger collection of data, the use of variables is not an option since it is not realistic. This means that one cannot use variables. • It may be difficult to retrieve or read the values in the order in which they were declared since the memory for the variables in a program is allocated in what seems to be an arbitrary sequence. In order to address this issue, the programming language TypeScript has a component called as arrays in its toolkit. When we speak about arrays, we refer to collections of things that all have the same data type. An item collection known as an array has elements that are all of the same kind. It is a sort that the user chooses for themselves to have. What Makes Up an Array The following is a list that outlines, in more depth, the qualities of an array: • Memory will be allotted in a sequential manner whenever a declaration of an array is made. • There is never any variation in arrays. This signifies that once an array has been started, its size cannot be altered in any way after it has been started. • Each memory block is a substitute for one of the array’s items. • The subscript or index of an array element is a single number that is used to identify that element inside the array specifically. This number may also be referred to as the array element’s index. • Just like variables, arrays need to have their definitions written down before they can be used in a program. This is a prerequisite for using arrays. Utilizing the var keyword is necessary before an array can be declared.

Appendix II   ◾    475

• The action of populating the elements of an array with data is referred to as “array initialization,” and it is a part of many programming languages. • While it is possible to update or edit the values of array items, it is not feasible to remove them. Array elements cannot be deleted. Object Contained Inside an Array An array may also be created from scratch with the help of the Array object if desired. • A numeric value indicates either the array’s dimensions or the array or the size of the array. • A group of values that are delineated from one another using commas.

TUPLES FOR THE TYPESCRIPT LANGUAGE It is possible that there may be circumstances in which it would be essential to keep a collection of values that belong to several categories. In this particular setting, the usage of arrays is not acceptable. TypeScript has made a data type known as tuple accessible to us, and it contributes to the success of such an endeavor by assisting in its completion. Tuples are one more kind of data that may be sent into functions in the role of an argument. It is representative of a wide variety of distinct principles, ideals, and principles all at once. To state it another way, tuples make it feasible to hold many fields of differing types. This may be done in a number of ways. Syntax var tuple_name = [value1,value2,value3,…value n] For Example: var mytuple = [10,” Hello”];

You also have the option in Typescript to declare an empty tuple and then decide at a later time whether or not to populate it.

476   ◾    Appendix II var mytuple = []; mytuple[0] = 120 mytuple[1] = 234

UNION IN TYPESCRIPT Programs now have the capability to mix one or two different types thanks to TypeScript 1.4. Union types are an extremely useful approach to describe a value that may be any one of a number of different kinds. When referring to a Union Type, the pipe symbol (|) is used to indicate the combination of two or more data types. In a nutshell, the syntax for a union type looks like a string of several types with vertical bars in between each one. Syntax Type1|Type2|Type3

Example: Union Type Variable var val:string|number val = 12 console.log(“numeric value of val “+val) val = “This is a string” console.log(“string value of val “+val)

The type of the variable is shown to be union in the preceding illustration. This specifies that the value of the variable may be either a number or a string. Either one is acceptable.

AMBIENTS IN TYPESCRIPT In TypeScript, ambient declarations are a method for alerting the TypeScript compiler that the actual source code is stored in another location. These declarations may be placed anywhere in a file. If it uses a variety of different third-party JS frameworks, such as jQuery, AngularJS, or NodeJS, you won’t be able to rebuild it in TypeScript. This is because TypeScript is not compatible with these frameworks. A TypeScript programmer may encounter challenges while trying to utilize these packages while preserving typesafety and intellisense at the same time. TypeScript

Appendix II   ◾    477

may be seamlessly connected to other JS libraries via the use of ambient declarations, which expand its functionality. Definition of Ambients By custom, declarations of ambients are stored in a type declaration file that has the following extension: (d.ts) Sample.d.ts

The file that is being shown above will not be transcompiled to JavaScript. It is going to be used for both type safety and intellisense. The following syntax will be used for defining ambient variables or modules: declare module Module_Name { }

The client TypeScript file ought to include a reference to the ambient files in the manner shown above. /// 1

NOTES 1 A Brief History/A Static Type Checker/ (2022, October 19)/ www.typescriptlang.org/docs/handbook/typescript-from-scratch.html 2 Main Pillars of Typescript/Features/How to Get Started/ (2022, October 19)/ www.freecodecamp.org/news/learn-typescript-basics/ 3 Setting Up Your TypeScript Development Environment/ (2022, October 19)/ www.newline.co/books/beginners-guide-to-typescript/setting-up-yourtypescript-development-environment 4 TypeScript for JavaScript Programmers 5 www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html 6 Classes in TypeScript: User and Expense 7 www.tutorialspoint.com/typescript/typescript_classes.htm 8 TypeScript - Objects 9 www.tutorialspoint.com/typescript/typescript_objects.htm 10 TypeScript - Namespaces 11 www.tutorialspoint.com/typescript/typescript_namespaces.htm 12 Modules 13 www.tutorialspoint.com/typescript/typescript_modules.htm

Appendix III Handy JavaScript Tools

IN THIS CHAPTER ➢ Gulp ➢ Grunt ➢ npm In the previous chapter, we covered a Brief Guide to TypeScript, and in this chapter, we will discuss the Handy JS Tools. Because JavaScript is such a popular language and is used in some form by all front-end web apps, many excellent tools help us effortlessly develop high-quality JavaScript applications. Every day, the tool ecosystem grows, and more tools for creating and debugging JavaScript applications are available.

OVERVIEW OF GULP We will talk about Gulp with its installation and advantages and disadvantages.1 What Exactly Is Gulp? Gulp is a task runner that runs on the Node.js platform. Gulp runs front-end tasks and large-scale web applications entirely in JavaScript code. It automates system tasks such as CSS and HTML minification, 479

480   ◾    Appendix III

concatenating library files, and compiling SASS files. These tasks can be carried out via the command line using Shell or Bash scripts. Why Should We Use Gulp? It is shorter, simpler, and faster than other task runners. CSS preprocessors are SASS and LESS. After editing the source files, the page automatically refreshes. Gulpfile.js is simple to understand and build because it uses pure JavaScript code to construct the task. History The CC0 license applies to all Gulp documentation. Gulp v1.0.0 was initially released on January 15, 2015, and the current version is v3.9.0. Features • Allows for minification and concatenation. • Pure JavaScript code is used. • Converts CSS compilation from LESS or SASS. • The Node.js platform manages file manipulation in memory and increases speed. Advantages • Significant time advantage over any other task runner. • Simple to code and comprehend. • It is simple to test web applications. • Plugins are simple to use and intended to do only one thing simultaneously. • Repeatedly performs repetitive tasks such as minifying stylesheets, compressing images, etc. Disadvantages • It has more dependencies than Grunt and is a newcomer. • We cannot perform multiple tasks with Gulp plugins. • Grunt’s configuration is not as clean.

Appendix III   ◾    481

INSTALLATION OF GULP This session walks us through the installation of Gulp step by step.2 Gulp System Requirements • Operating System Cross-platform • IE (Internet Explorer 8+), Firefox, Google Chrome, Safari, and Opera are all supported browsers. Installation of Gulp Step 1: To run Gulp examples, we need Node.js. To download Node.js, go to https://nodejs.org/en/, and we’ll see the screen below.

download gulp

Download the zip file with the most recent features. Step 2 Run the setup program to install NodeJs on your computer. Step 3: Configure the environment variables. User Variable Path

• Right-click My Computer and select Properties. • Choose Properties. • Select the Advanced tab and then click on ‘Environment Variables.’ • Double-click on the PATH as indicated on the screen in the Environment Variables box.

482   ◾    Appendix III

• An Edit User Variable box will appear. In the Variable Value field, enter C:\Program Files\nodejs\node modules\npm as the path of the Node.js folder. If the path has already been established for other files, we must add the Node.js path after the semicolon (;). • In the end, press the “Ok” button. System Variable

• Double-click on Path under System variables. • An Edit System Variable window will appear. In the Variable Value field, enter C:\Program Files\nodejs\ as the path of the Node.js folder, and then click “Ok.” Step 4: Open our system’s command prompt and type the following ­command. The installed Node.js version will show. Step 5: To show the version of npm (the Node.js package manager) that is used to install modules, type the following command into the ­command prompt. The installed Node.js version will display. npm -v

Step 6: Type the following command to install Gulp at the command prompt. The “-g” parameter guarantees that Gulp is available for any project worldwide. npm install gulp -g

Step 7: Type the following command to view the Gulp version to ensure it was installed correctly. gulp -v

BASICS OF GULP This section will introduce us to the fundamentals of Gulp.3 What Exactly Is a Build System? A Build System is a collection of tasks (collectively known as task runners) that automate repetitive work.

Appendix III   ◾    483

Some of the jobs that the build system is capable of doing are listed below: • Preprocess CSS and JavaScript compilation. • File compression to reduce file size. • Concatenation of multiple files into one. • Activating the server’s automatic reloading. • Create deployment builds to keep the resulting files in one place. • The build system in a modern front-end workflow consists of three components: • Managers of packages. • Preprocessors. • Task managers and build tools. Package Administrators It automates installation upgrades, dependency removal, library cleaning, and package cleanup in the development environment. Bower and npm are two examples of package managers. Preprocessors Preprocessors are particularly helpful for a productive modern workflow since they bring enhanced capabilities and optimized syntax that compile into the target language. A few of the well-liked preprocessors include • CSS − SASS, Stylus, and LESS. • JS − LiveScript, CoffeeScript, TypeScript, etc. • HTML − Markdown, Slim, HAML, Jade, etc. Task Executors Task runners automate various development activities, including minifying files, enhancing photos, and converting SASS to CSS. In the contemporary front-end work environment, Gulp is one of the task runners and runs on Node.

484   ◾    Appendix III

Setting Up Our Project Create a folder on our computer called, for instance, “work” to save our project there. The work folder has the following files and subfolders: • Src: Pre-processed HTML source files and directories are located in the Src directory. • Images: Uncompressed images are included. • Scripts: Contains several script files that have already been processed. • Styles: Consists of several pre-processed CSS files. • Build: The production files are located in this automatically generated folder. • Images: Comprised of compressed pictures. • Scripts: A single script file containing code that has been compressed. • Styles: A single CSS file containing code that has been compressed. • gulpfile.js: The configuration file used to specify our tasks is called gulpfile.js.

DEVELOPING AN APPLICATION USING GULP We learned about Gulp installation and the fundamentals of Gulp in the previous section, which covered topics like the Gulp build system, package management, task runner, and Gulp structure.4 The following are some of the fundamentals for creating applications that we will examine in this session: • Stating necessary dependencies • Task creation for the dependencies • Performing the task • Observing the task

Appendix III   ◾    485

Declaration of Dependencies We must indicate the plugins’ dependencies when installing them for the application. Package managers like bower and npm take care of the dependencies. Let’s define dependencies for the gulp-imagemin plugin in the configuration file. The following command line may use to install this plugin, which can use to compress the image file: npm install gulp-imagemin --save-dev

As seen in the following code, we may include dependencies in our configuration file. var imagemin = require(‘gulp-imagemin’);

Task Creation for Dependencies Task makes it possible to configure Gulp in a modular fashion. Each dependent must have its task, which we must add to as we locate and set up additional plugins. The Gulp job will be organized as follows: gulp.task(‘taskname’, function() { //here, do stuff });

Where “function()” carries out our task and “taskname” is a string name. Gulp.task defines the dependencies on other tasks and registers the function as a task with a name. As illustrated in the following code, we may build the task for the previously created dependency. gulp.task(‘imagemin’, function() { var imgsrc = ‘src/images/**/*’, imgdest = ‘build/ images’; gulp.src(imgsrc) .pipe(changed(imgdest)) .pipe(imagemin()) .pipe(gulp.dest(imgdest)); });

486   ◾    Appendix III

The images are saved in the img srcobject and may be found in the directory src/images/**/*. The imagemin constructor pipes it to further functions. By invoking the dest method with an argument that stands in for the destination directory, it compresses the pictures that were transferred from the src folder to the build folder. Running the Task The Gulp file is configured and prepared to run. To execute the task, enter the following command in our project directory. gulp imagemin

OVERVIEW OF GruntJS We will talk about GruntJS with its installation and its advantages and disadvantages. A JavaScript task manager is GruntJS. With no effort, it may use to automate various operations for our application, increasing developer productivity.5 GruntJS has plugins for many different tasks. One such instance is the nodemon plugin, which restarts the node server automatically anytime a JavaScript file changes in our application. Therefore, we don’t need to manually stop and restart the node server each time we change the JavaScript. We may use the grunt-contrib-cssmin plugin to compress CSS files. We may format, search, or rewrite the JavaScript in our application with the grunt-jsfmt plugin. Why Should We Use Grunt? Grunt can easily do repetitive operations like compilation, unit testing, file minification, test execution, etc.6 Grunt comes with built-in tasks that let our plugins and scripts do more. Grunt’s ecosystem is vast; we can automate almost anything with minimal effort. History GruntJS’s first lines of source code were added in 2011. On February 18, 2013, Grunt v0.4 was released. On May 12, 2014, Grunt v0.4.5 was released. Grunt’s current stable version is 1.0.0 rc1, published on February 11, 2016.

Appendix III   ◾    487

Advantages • We may quickly execute file minification, compilation, and testing with Grunt. • Grunt unifies web developers’ workflows. • Because it has the minimal infrastructure, Grunt makes it simple to work with a fresh codebase. • It improves project performance by speeding up the development workflow. Disadvantages • We must wait till the creator of the Grunt changes it whenever npm packages are updated. • Every job is intended to perform a specific function. • If we wish to extend a particular assignment, we must employ some methods to complete the work. • Grunt provides a plethora of configuration options for individual plugins. • Grunt configuration files are often lengthier in length.

FEATURES IN GRUNT Grunt is a JavaScript-based task runner that may use to automate repetitive operations in a workflow and as a command-line tool for JavaScript objects.7 The following are some of the most notable features of GruntJS: • Grunt makes the workflow as simple as writing a configuration file. • With no effort, we may automate repetitive operations. • Grunt is a famous NodeJS task runner. It is adaptable and frequently used. • It takes a fundamental approach, with tasks written in JS and configuration written in JSON.

488   ◾    Appendix III

• Grunt minifies JavaScript, CSS files, tests files, CSS preprocessor files (SASS, LESS), and other files. • Grunt comes with built-in tasks that let your plugins and scripts do more. • It improves project performance by speeding up the development workflow. • Because it has the minimal infrastructure, Grunt makes it simple to work with a fresh codebase. • Grunt’s ecosystem is vast; we can automate almost anything with minimal effort. • Grunt decreases the possibility of mistakes when doing repetitive activities. • Grunt now has almost 4,000 plugins. • It may be employed in large production facilities.

SETTING UP OF GRUNT This section walks us through installing Grunt on our system step by step.8 Grunt’s System Requirements • Cross-platform operating system • Support for Internet Explorer (version 8 and higher), Firefox, Google Chrome, Safari, and Opera Installation of Grunt Step 1: To execute Grunt, we require NodeJs. The screen below will show us when we click the link https://nodejs.org/en/ to download NodeJs.

Appendix III   ◾    489

download grunt

Download the zip file with the most recent features. Step 2: Run the setup program to install NodeJs on our machine. Step 3: The third step is to set environment variables. User Variable for Path • To right-click My Computer. • Choosing Properties. • Next, click Environment Variables under the Advanced tab. • Double-click the PATH entry in the Environment Variables box when it appears on the screen. • An Edit User Variable window will appear as displayed. C:\Program Files\nodejs\node_modules\npm should be added as the path of the NodeJs folder in the Variable Value box. If the path has already been established for other files, add the NodeJs path after the semicolon (;) in the format. Click the OK button when we’re done. System Variable • Double-click Path under System variables, as displayed on the screen. • A window to edit system variables will appear, as displayed. As illustrated below, enter C:\Program Files\nodejs\ as the path to the NodeJs folder and click OK.

490   ◾    Appendix III

Step 4: To complete the installation of Grunt on your system, install its command-line interface (CLI) globally, as seen below. npm install -g grunt-cli

By running the command above, the grunt command will be added to our system path and be available for use from any directory. Grunt task runner is not installed when grunt-cli is installed. The gruntfunction cli’s is to execute the Grunt version installed next to a Gruntfile. It enables a system to install numerous Grunt versions at once. Step 5: To use Grunt, we need to generate configuration files. package.json Alongside the Gruntfile, the package.json file is positioned in the project’s root directory. When we execute the command npm install in the same folder as package.json, it uses package.json to run each dependent indicated appropriately. We may generate the basic “package.json” file by using the following command at the command prompt: npm init

The ‘package.json’ file’s basic structure is seen below: { “name”: “tutorialsession”, “version”: “0.1.0”, “devDependencies”: { “grunt-contrib-jshint”: “~0.10.0”, “grunt-contrib-nodeunit”: “~0.4.1”, “grunt-contrib-uglify”: “~0.5.0” } }

The below command may use to add Grunt and Gruntplugins to an already-existing package.json file. npm install --save-dev

Appendix III   ◾    491

The module to be installed locally is indicated by the word “module” in the command above. The preceding command will also automatically add the to devDependencies. For example, the following command will add the most recent version of Grunt to our devDependencies and install it. npm install grunt --save-dev

Gruntfile.js We define our Grunt setup in the Gruntfile.js file. It will be here that we write the settings. As illustrated below, the fundamental Gruntfile.js file // (Required by Grunt and its plugins) our wrapper function // This function contains all configuration. module.exports = function(grunt) { // CONFIGURE GRUNT grunt.initConfig({ // get configuration info from package.json file // this way, we can use things such as name and version (pkg.name) pkg: grunt.file.readJSON(‘package.json’), // here, all of our configuration goes uglify: { // uglify task configuration options: {}, build: {} } }); // log something grunt.log.write(‘Hello world! Welcome to Tutorialspoint!!\n’); // Load plugin that provides “uglify” task. grunt.loadNpmTasks(‘grunt-contrib-uglify’); // Default task. grunt.registerTask(‘default’, [‘uglify’]); };

492   ◾    Appendix III

GETTING STARTED WITH GRUNT We require Node.js to utilize Grunt, so ensure it is set up. Using the Node. js package manager, we may install Grunt and its plugins.9 We may update the Node package management using the command line before installing Grunt on the machine. npm update -g npm

To provide administrator access on a Mac or Linux computer, use sudo word at the beginning of the command line, as seen below. sudo npm update -g npm

Installation of CLI The installed version of Grunt is launched using the CLI, or command-line interface. We must install Grunt’s command-line interface (CLI) globally to begin using it. npm install -g grunt-cli

By running the command above, the grunt command will be added to our system path and be available for use from any directory. By installing grunt-cli, we cannot install the Grunt task runner. It enables a system to install numerous Grunt versions at once. Working of CLI Every time Grunt is executed, the CLI uses the require() mechanism to check to see if Grunt is already installed on our system. We may launch Grunt from any directory in our project using grunt-cli. Grunt-cli utilizes the locally installed Grunt library and applies the configuration from the Grunt file if Grunt is being used locally. Working on a New and Current Project If we are working with a project that has already been configured and includes package.json and a Gruntfile, then follow the instructions listed below: • Discover the directory’s root path for the project. • The npm install command may use to install dependencies.

Appendix III   ◾    493

• Use the grunt command to launch Grunt. • Include the two files package.json and Gruntfile, in our project if we are starting a new one. • package.json: When we execute the command npm install in the same folder, the package.json file, which is located in the project’s root directory, is used to run each dependent that is indicated. • Gruntfile.js: The project’s configuration settings are written in the Gruntfile.js file. package.json When we execute the command npm install in the same folder, the package.json file is used to run each dependency mentioned and is located next to the Gruntfile in the project’s root directory. There are several ways to construct the “package.json,” as noted below:

• To generate the ‘package.json’ file, use grunt-init. • We may also use the npm-init command to build a “package.json” file. As demonstrated below, we may write specifications. { “name”: “tutorialsession”, “version”: “0.1.0”, “devDependencies”: { “grunt-contrib-jshint”: “~0.10.0”, “grunt-contrib-nodeunit”: “~0.4.1”, “grunt-contrib-uglify”: “~0.5.0” } }

The below command may use to add Grunt and gruntplugins to an existing “pacakge.json” file. npm install --save-dev

The local installation module is represented by in this instance. The requested module will be installed and immediately added to the devDependencies section by using the preceding command.

494   ◾    Appendix III

For example, the command below will update Grunt to the most recent version and add it to our devDependencies. npm install grunt --save-dev

Gruntfile By default, our Grunt configuration settings will be stored in the Gruntfile. js file. The following components are present in the Grunt file:

• The function of wrapping • Task and project setup • Grunt jobs and plugins are loading • Certain tasks The ‘Gruntfile.js’ basic file is shown as follows: // (Required by Grunt and its plugins) our wrapper function // This function contains all configuration. module.exports = function(grunt) { // configure the grunt grunt.initConfig({ // to obtain configuration information, see the package.json file // We may utilize elements like name and version in this way (pkg.name) pkg: grunt.file.readJSON(‘package.json’), // Everything we configure goes here }); // Load the plugin that performs the “uglify” function grunt.loadNpmTasks(‘grunt-contrib-uglify’); // Default task grunt.registerTask(‘default’, [‘uglify’]); };

Wrapper Function In the code above, module.exports is a wrapper function that receives the complete configuration. It is a method of showing configuration to other program users.

Appendix III   ◾    495 module.exports = function(grunt) { //here do grunt-related things }

Task and Project Configuration Once our Grunt configuration is ready, we may configure Grunt tasks. The grunt.initConfig() section is where the project configuration may enter. Take the configuration data from package.json and store it in pkg inside grunt.initConfig(). We may use pkg.name and pkg.version to call our project’s name and version, respectively. Loading the Grunt Plugins and Task Use the ‘grunt.loadNpmTasks’ function to load the tasks from a specific plugin. The plugin may be installed locally using npm; it must be relative to the Gruntfile. The plugin may be loaded using the straightforward command described below. grunt.task.loadNpmTasks(plugin_Name)

Custom Tasks Grunt will search for the default task when executed through the command line. The task uglify, which may be executed using gruntcommand, is used in the code above. This is equivalent to manually using the grunt uglify command, and we may provide the array’s job count. grunt.registerTask(‘default’, [‘uglify’]);

GULP VS GRUNT Before delving into the Grunt versus Gulp debate, we may ask what both tools accomplish and why you would want to use either. Both Grunt and Gulp, as previously noted, exist to assist automate operations and are popular tools among web developers and designers.10 A website designer’s regular duties include debugging code, concatenating and minifying CSS and JavaScript files, compressing images, and making modifications to a server or server files. Many of these chores are essential, but they can take a long time. This is especially true if the website is vast or requires regular revisions and updates.

496   ◾    Appendix III

Someone may appoint to perform these activities, but because they are relatively simple, the person doing them could be doing more productive things. This is when Grunt and Gulp come into play. We can build up a process that automates tasks using a piece of really easy code, plugins, and either Gulp or Grunt. Both of these programs enable you to check for new files or changes to files in specific folders and conduct operations that are relevant to them. In other words, after we’ve configured the processes we want and applied them to existing files, any new or updated files can have processes applied to them automatically. Assume we put up a procedure that compresses jpg files in the images directory. When we perform the procedure, all photographs have their EXIF data removed and are compressed. Once we’ve correctly installed and configured Gulp or Grunt, the image compression task code for each tool should look something like this: Gulp gulp.task(‘jpgs’, function() { return gulp.src(‘src/documents/*.jpg’) .pipe(imagemin({ progressive: true })) .pipe(gulp.dest(‘optimizedimages’)); });

Grunt imagemin: { jpgs: { options: { progressive: true }, files: [{ expand: true, cwd: ‘src/img’, src: [‘*.jpg’], dest: ‘documents/’ }] } }

Appendix III   ◾    497

If we’ve also configured Gulp or Grunt to check for new or updated files, any altered or new files saved to the directory will compress, and the EXIF data will immediately erase. Gulp or Grunt can conduct this job efficiently, and in the case of large amounts of files, they can do so in a fraction of the time it would take if it had been carried out manually. Gulp vs Grunt: What’s the Difference? Now that we know what Gulp and Grunt can accomplish let’s talk about how they do it. Both programs are task runners using Node.js, an opensource JavaScript runtime environment for developing tools and apps. Grunt and Gulp rely on plugins to do the tasks we want them to do for us. To build tasks, both tools utilize.js files; for Grunt, you use a gruntfile. js, and for Gulp, we use a gulpfile.js. Instead of utilizing a function, we may define flows with grunt.task and gulp.task. Some of the most frequent tasks that each tool can do and automate include the following: • Image file compression • Script debugger and console statements are removed • CSS and JavaScript minification, concatenation, and cleanup • Error-checking code • Less file compilation • Executing unit tests • Sending updates to a live server • Database updates Gulp vs Grunt: Which Is Faster? Regarding speed, Gulp has a significant edge, although the advantage may not be that significant, and changes to Grunt have done a lot to lessen the speed disparity. Gulp’s present speed advantage is because it uses streams and processes jobs in memory, resulting in only one file being written. Furthermore, Gulp can handle several jobs simultaneously, whereas Grunt typically only handles one task at a time.

498   ◾    Appendix III

TMWtech did a speed test to compare the time it takes to do a Sass compilation using Gulp and Grunt. The findings reveal that Gulp was substantially quicker, consuming only 1.27 seconds compared to Grunt’s 2.348 seconds. A temporary file is saved when a plugin executes a file in Grunt. A final destination file is written after a file has passed through all plugins. Writing data to the disc can significantly increase the amount of time required to execute activities; however, significantly is a relative phrase. Unless we’re working on a vast project, the output time for Gulp or Grunt will measure in seconds or milliseconds. Even if Grunt takes 500 ms to perform a job that Gulp can complete in 50 ms, a tenfold difference, we’re still talking about a half-second difference for the considerably longer Grunt time frame. When comparing Gulp versus Grunt, the scale of the project we’re working on will decide whether performance is a concern. Even if speed is an issue for us, Grunt gained pipe support earlier this year (as of version 0.5), so the speed disparities are likely lower than when most comparisons were performed. Gulp vs Grunt: Configuration vs Coding The crucial distinctions between Gulp and Grunt in terms of configuration versus code have been heavily debated. Gulp is intended to help us achieve our goals using single-purpose plugins and scripts. In most circumstances, this makes writing plugins for Gulp considerably easier than developing them for Grunt. Furthermore, because Gulp is more focused on code and single-task plugins, setting plugins in Gulp is a lot more standardized procedure than it is for Grunt plugins. However, the issue may be less about code and more about how comfortable we and, if applicable, our team are with node streams. Gulp largely relies on node streams, and unless we and everyone else who will be working with Gulp are familiar with them, as well as pipes, buffers, and asynchronous JavaScript, dealing with Gulp will be an uphill battle. While configuring Grunt takes longer than setting Gulp, Grunt is far more user-friendly since it relies on configuration rather than code. Furthermore, while Gulp code is easier to read, many people believe that Grunt code is simpler to write. If we’re working with a large group of individuals with diverse skill levels, Grunt could be a better option. To use it, read the manual, acquire and set up the necessary plugins, and produce some JavaScript code.

Appendix III   ◾    499

Gulp vs Grunt: Support, Community, and Plugins Both programs have a huge and helpful community, as well as a significant number of plugins to pick from. As previously stated, over 6,000 Grunt plugins are posted on the official site, and approximately 2,700 Gulp plugins are listed on the official site of Gulp. Gulp is the new kid on the block, so it’s not surprising that there are about twice as many plugins available for Grunt. In any case, both a program lacks plugins, and there is a Gulp plugin that, with principle, allows any Grunt plugin to operate in Gulp. As of 2016, Grunt had over 70% of the market, compared to Gulp’s 30% share. However, throughout the same period, the number of downloads for each tool was quite close. Grunt was downloaded approximately 1.85 million times a month, whereas Gulp was downloaded roughly 1.6 million times in the same time frame. Which Should We Go With? There is no right or wrong answer when deciding between Grunt and Gulp. Both automation technologies have a lot to offer, and none has a significant flaw. Our decision will be influenced by whether we prefer configuring (Grunt) or coding (Gulp) while setting up automation and our familiarity with node streams. There is a great deal of personal preference involved. Speed, how plugins function and the number and types of plugins available may all factor into our selection. While some people find that they can efficiently utilize either method, others may not. If we’re still undecided between Gulp and Grunt, we should experiment with both. Both programs are free and have active communities that may assist us in finding the right plugins and getting started with automation scripts. We can use both tools on separate tasks depending on how many projects we have.

OVERVIEW OF NPM We will talk about npm with its installation and advantages and disadvantages. What Exactly Is npm? The npm is an abbreviation for Node Package Manager, the world’s largest software registry.

500   ◾    Appendix III

It is used by open-source web project developers worldwide to share and borrow packages.11 The npm package manager also serves as a command-line utility for the Node.js project, allowing it to install packages, manage dependencies, and even manage versions. Components of npm The npm is made up of three distinct components, which are as follows: • Website: The official npm website www.npmjs.com/ is used to find packages for our project and create and configure profiles for managing and accessing private and public packages. • CLI (Command-Line Interface): The CLI interacts with npm packages and repositories from our computer’s terminal. • Registry: The registry is a large and open database of JavaScript projects and metadata. We can use any supported npm registry, including our own. We can even use someone else’s registry if we follow their terms of service. Setting Up npm (Node.js and npm) We must install Node.js for it to be automatically installed on our machine because npm already includes Node.js. The installation of npm on a computer may be done in one of two ways. • NVM use (Node Version Manager). • Installing Node.js using. It is strongly advised to install npm using Node Version Manager rather than the Node installer. When you attempt to execute npm packages globally, the Node installation process installs npm in the directory by granting local rights, producing an error message. 1. Setup Node.js and npm Using nvm Using Node version management to install npm and Node.js on our device is strongly advised by npm developers. We may install many Node.js versions on our computer by utilizing the nvm installation method, and we

Appendix III   ◾    501

can switch between them as needed to use any Node.js version for our project. They do not advise us to install npm and Node.js using the node installers. Open https://github.com/nvm-sh/nvm to download and install npm using nvm on our Linux operating system. • As we are utilizing a Windows OS device, we will download the nvm-setup.zip file for Windows from the Git link. • Run the setup program after downloading it, then follow the installation instructions on the screen. • Run the setup by either double-clicking it or selecting Run as administration from the context menu. • Clicking the Yes option will permit installation. • After carefully reading their licensing agreement, if we agree, click the Next option to accept it. • Click the Next button after selecting the area where NVM should install. It remains the default place that has been chosen. • Click the Next button after selecting the folder where the setup will build the symlink. • Now that our setup is prepared for installation click the Install button to begin the procedure. • The nvm setup has now begun to install on our computer, and we will need to wait a little while for it to finish. • Our installation of the nvm setup is complete; choose Finish to leave the setup. Verify the nvm Version Verify whether we are installed and which nvm version is installed once the nvm setup has been completed. Run the following command on our terminal to accomplish this: nvm v

502   ◾    Appendix III

Look through the List of Node.js That Can Install with nvm Use the following command to discover the supported Node.js version for nvm installation. It will show a limited list of Node.js versions that are currently available. npm list available

Installing npm and node.js We may install any version of Node.js; on our system, we have LTS 14.15.4 installed. To install Node.js, just run the following command: nvm install 14.15.4

Verify the Node.js and npm Versions Use the command nvm use 14.15.4 to launch Node.js (make sure to replace 14.15.4 with our installed version). nvm use 14.15.4

Then, use the commands node -v and npm -v to verify the Node.js and npm versions in our terminal. node -v npm -v

Verify the Installed Node.js Version List Using the command below, we can see how many different Node.js versions are currently installed and active on our machine. nvm list

On our system, Node.js version 14.15.4 is currently active. If necessary, we may also install other, distinct Node.js versions on a machine (while building another Node.js project based on a different version). Choose a different Node.js version from the list provided by nvm, then execute the command below to install it. nvm install 12.20.2

Here, we’ve chosen to install Node version 12.20.2; it also downloads and sets up a suitable version of npm on our smartphone.

Appendix III   ◾    503

Node.js and npm now come in two separate versions. Run the following command to see how many Node.js versions are currently installed: nvm list

2. Using the Node Installer, Install npm and Node.js Consider a situation where we cannot install npm on our device or are having trouble doing so. The Node.js installer is the alternative method for installing npm and Node.js on our computers. To install Node.js and npm simultaneously, go to the Node.js download area https://nodejs.org/en/download/ where we can locate Node.js installers for the various OS systems.

Download npm

Download any Node.js installation compatible with our operating system and its bits. 1. We are downloading a 64-bit Node.js installer for our device because we have Windows with the 64-bit operating system. 2. Run the setup program after downloading it, then follow the installation instructions on the screen. 3. To begin the installation procedure, click the Next button. 4. Click the Next button after reading and accepting the end-user licensing agreement.

504   ◾    Appendix III

5. Select a unique location for our Node.js installation and click Next to continue. It remains in its default position. 6. Click Next after selecting the Node.js functionality we want to install. We maintain it as a default functionality that is offered. 7. Check the box and select the Next option to install additional required tools (such as C/C++ and Chocolaty) together with our node.js and npm installation. 8. To install Node.js and npm on our device, click the Install button now. 9. To install Node.js, select Yes in the pop-up box. 10. To finish the installation, click the Finish button. The extra tools are prepared for installation, as indicated by the checkbox above for automated installation of extra tools. Press any key to move forward. To download the most recent version of npm, issue the command shown below on the command line. npm install -g npm

Features of npm • Package.json files, which are used to define all npm packages. • The package.json file’s content must write in JSON. • The name and version fields must both be included in the definition file. package.json When we use npm init to launch a JavaScript/Node.js project, a “package.json” file will create with the essential metadata details supplied by developers: • Name: This is the title of our JavaScript project or library. • version: This is the project’s version.

Appendix III   ◾    505

• description: Send details about the project’s description. • license: It is a license for a project. When to Employ npm • Use npm to modify code packages for our projects or use them exactly as-is. • When we need to download standalone tools immediately, we can utilize npm. • Utilize npx to run packages without downloading. • If we need to share code with any other npm user, use npm. • When you want to limit code to particular developers, we may use npm. • Create teams using npm to organize developers, coding, and package maintenance. • To handle various code versions and code dependencies, use npm. • Npm may use to update apps when the underlying code is modified quickly. • To locate additional developers working on related issues and projects, use npm. Command-Line Client The software package npm comes with a CLI (Command-Line Client) that may be used to obtain and install npm packages: Example on Windows OS C:\>npm install C:\>npm uninstall

Example on Mac OS >npm install >npm uninstall

506   ◾    Appendix III

Publishing a Package As long as a directory includes a “package.json,” we can publish it from our PC. Verify that npm is installed: C:\>npm

Verify our logged-in status: C:\>npm whoami

If not, login: C:\>npm login Username: Password:

Go to our project’s page and publish it: C:\Users\my_user>cd my_project C:\Users\my_user\my_project>npm publish

Global Mode Package Installation We have the npm package loaded globally, which is all we have now. So let’s alter it and install UglifyJS as a different package (a JavaScript minification tool). Although it may shorten to -g, we use the --global flag in this instance: npm install uglify-js -global C:\Users\JTP\AppData\Roaming\npm\uglifyjs -> C:\Users\ JTP\AppData\Roaming\npm\node_modules\uglify-js\bin\ uglifyjs + [email protected] added 1 package from 1 contributor in the 12.32s

Packet Installation in Local Mode A package.json file is typically used when installing any packages locally. Here is an illustration of how to make a project folder in our home directory:

Appendix III   ◾    507 mkdir project && cd project npm init package name: (project) version: (1.0.0) description: Instance of the package.json entry point: (indexs.js) test command: git repository: keywords: author: license: (ISC)

To generate “package.json” with default settings, press Enter. Then, type “yes” to confirm that the “.json” file is okay. By doing this, a “package.json” file will create in the project’s root: { “name”: “project”, “version”: “1.0.0”, “description”: “Instance of the package.json”, “main”: “indexs.js”, “scripts”: { “test”: “echo \”Error: no test is specified\” && exit 1” }, “author”: ““, “license”: “ISC” }

Removing Local Packages We can also uninstall a package because npm is package management that is always manipulable. Let’s say there is a compatibility issue with the package packageName that is currently installed. Consequently, we’ll uninstall this package and install an earlier version: npm uninstall packageName

Installing a Particular Package Version Now that we have the packageName package of the desired version, we may install it. The @ symbol can use to attach a version number. npm install [email protected]

508   ◾    Appendix III

As we’ve seen, there are several approaches to executing npm instructions. The lists of some of the most popular npm commands are provided below (or aliases). • npm i : Install the local package using npm i • npm i -g : Install the global package using npmiI -g • npm un : Uninstall a local package using npm un • npm up: packages updated by npm • npm t: run tests using npm • npm ls: List installed modules using npm ls • npm ll or npm la: Print more package details while listing modules using npm ll or npm la We discussed the introduction, installation, and functionality of Gulp, Grunt, and npm in this chapter.

NOTES 1 Gulp – Overview: www.tutorialspoint.com/gulp/gulp_overview.htm Accessed on: 20 October 2022. 2 Gulp – Installation: www.tutorialspoint.com/gulp/gulp_installation.htm Accessed on: 20 October 2022. 3 Gulp – Basics: www.tutorialspoint.com/gulp/gulp_basics.htm Accessed on: 20 October 2022. 4 Gulp – Developing an Application: www.tutorialspoint.com/gulp/gulp_ developing_application.htm Accessed on: 20 October 2022. 5 GruntJS: www.tutorialsteacher.com/nodejs/gruntjs Accessed on: 20 October 2022. 6 Grunt – Overview: www.tutorialspoint.com/grunt/grunt_overview.htm Accessed on: 20 October 2022. 7 Grunt – Features: www.tutorialspoint.com/grunt/grunt_features.htm Accessed on: 20 October 2022. 8 Grunt – Installing: www.tutorialspoint.com/grunt/grunt_installing.htm Accessed on: 20 October 2022. 9 Grunt – Getting Started: www.tutorialspoint.com/grunt/grunt_getting_ started.htm Accessed on: 21 October 2022. 10 Gulp vs Grunt – Comparing both Automation Tools: www.keycdn.com/blog/ gulp-vs-grunt#:~:text=Gulp%20vs%20Grunt%3A%20Speed&text=The%20 reason%20for%20Gulp%27s%20current,one%20task%20at%20a%20time. Accessed on: 22 October 2022. 11 What Is npm: www.javatpoint.com/what-is-npm Accessed on: 22 October 2022.

Index ActiveX Control program 267 aggregations 345 AJAX technology 10, 34–35, 153, 268 alert() method 442 algebra 444–445 Algolia Places 195–196 ambients, in TypeScript 476–477 Android apps, using NativeScript 397–399 Android SDK 380 Android Studio 379–380; see also Visual Studio (VS) Code AngularJS 17, 19–20, 46, 213, 217–219 characteristics of 295–296 frontend frameworks and libraries 272–273 vs. JavaScript 260–263 vs. React.js 295–298 VueJS vs. 316–318 Animate On Scroll (AOS) 197 Anime.js 196–197 Apache Cordova 235–236 API see Application Programming Interface (API) App.js 241, 291–292, 294 App.JSX 303 Application Programming Interface (API) 181–191, 367, 434; see also user interface (UI) GraphQL API 67 native Fetch API 162 applications cross-platform applications (see crossplatform applications) desktop applications (see desktop applications) dynamic web applications 279–280

full-stack online applications 358 Ghost Electron app 406–407 hybrid app 235 mobile applications (see mobile applications) Pexels Electron app 407 Playground app 390, 395–396 professional JavaScript app 375 server applications 4 Single-Page Applications (SPAs) 215 Skype app 385 standalone level vs. cross-platform app 239 Tesla app 386 web 4, 27, 425 Application user interface 359 arithmetic operators 82 arrays in JavaScript 98–101, 434–435 in TypeScript 473–475 assignment operators 83 assistances community assistance 301 offline assistance 373 asynchronous function 134–143; see also functions vs. deferred JavaScript 143–144 Node.js 131–133 Atom 39–40 audio/video, processing of 335 Aurelia 25–26 Axios methods 159–160 Babel JavaScript VSCode 69, 288 .babelrc file 292 Babylon.js 232

509

510   ◾    Index Backbone.js 224–226 backend frameworks 17–18, 227, 275; see also frameworks development 274, 333 Express.js 228, 361–363 Gatsby 229 languages 274 Meteor 230–231 Next.js 227–228 Node.js (see Node.js) tasks 372 web designer 425 Beaker Browser 407 Bideo.js 198 bitwise operators 83, 432 blur() function 443 Boolean object 113–114 Bootstrap frontend frameworks 273 libraries 217, 273 Brackets 43 browsers Beaker Browser 407 Netscape browser 9, 418, 420 objects 441–444 Brython 419 BSON data type 343 buffer 312 Build System 482–483 bundle process 293 C# 7–8, 255, 275, 317, 342, 404, 422 C++ 274, 335, 417; see also languages; programming languages callback method 439 Carbon Components Svelte 222 Carbon Design System 222 Cascading Style Sheets (CSS) language 33, 46, 72, 227, 272, 375, 479–480 case-sensitive programming language 77 CDN library 318 characters deleted character 453 escape character 435 semicolon character 76 special character 435 Chart.js 198–199

chocolaty setup program 378–379 Chreographer.js 199–200 class inheritance 465–466 clearInterval() method 442 clearTimeout() method 442 Cleave.js 199 CLI Command Line 320 client-optimized programming language 255 client-side JavaScript 3 client-side programming 256 close() function 443 Cocoon.js framework 233 Code Editor 455 Code Push SDK 382 coding 371 configuration vs. 498 integration with C++ 335 CoffeeScript 419 Command-Line Client 505 Command-Line Interface (CLI) 500 comments 77–78 community activity, on Google 296 community assistance 301; see also assistances comparison operators 82–83, 432–433 compiler for TypeScript 448–449 compiler-free programming 34; see also programming computation 444–445 computerized property 314 configurations vs. coding 498 environment configuration 373 Simple Environment Configuration 360 confirm() function 443 console.log() function 457 “const” keyword in JavaScript 430 contact() array 434 cookies 5, 164–165 in JavaScript 166–168 properties of 168–170 utilization of 165–166 varieties of 170–172 C programming language 420–421; see also programming languages

Index   ◾    511 ‘create-react-app’ function 293, 364 cross-compilers 421; see also applications; desktop applications; mobile applications cross-platform applications 239 framework 28, 389 program 238–239, 408–409 runtime environment 367 support 381 Cross-Platform Document-Oriented Database 358–359 CSS language see Cascading Style Sheets (CSS) language Dart platform 419 vs. JavaScript 254–260 databases as backend tier 367 Cross-Platform Document-Oriented Database 358–359 document-oriented database 350, 360 MongoDB database (see MongoDB database) Not Only SQL database 350 Not simply SQL database 342 schema-less database 345 data binding pattern 295 Data-Driven Documents (D3.js) 193–194 data hiding 466 data modeling, MongoDB 344 data types 5, 430–431 BSON data type 343 non-primitive in JavaScript 81 date objects 106–109, 440 Day.js package 212 Debian-based computers 54 Debugger for Chrome 67 default parameters 473; see also parameters deferred vs. asynchronous JavaScript 143–144 deleted characters, in TypeScript 453 desktop applications 238–239, 403–404; see also applications; crossplatform applications; mobile applications AppJS 241

Beaker Browser 407 cross-platform apps (see cross-platform applications) Electron (see Electron) Ghost 406–407 main vs. renderer processes 411–412 NodeGUI 240 Node.js 240 NW.js 241 Pexels 407 Proton Native 241 React.js 239–240 Slack 408 standalone application 239 use of 404–405 WebTorrent 405–406 WhatsApp 408 WordPress 406 developers programming languages suitable for 373 skilled, in JavaScript 425–428 software 381 TypeScript for 459–462 VS Code extensions for JavaScript 64–70 development community, for React Native vs. NativeScript 400 DevOps Engineer 426–427 directives, in VueJS 315 Django 275 document.getElementById() function 147, 151–152 document.getElementsByName() function 149 document.getElementsByTagName() function 149–151 Document Object Model (DOM) 31–32, 34, 145, 192, 212, 214, 224, 263, 273, 278, 279, 300, 436–439 document-oriented database 360; see also databases DOM see Document Object Model (DOM) domain property, cookies 169 do-while loop 91 duck-typing 469

512   ◾    Index dynamic HTML 273 dynamic programming language 417; see also programming languages dynamic web applications 279–280; see also applications Dynamic Websites 19, 251, 356, 418 Eclipse 41–42 ECMAScript 3, 12–13, 302, 447, 458 ECMAScript 5 9, 11 ECMAScript 6 11, 13 ECMA-262 Specification 2, 3, 6, 12 ecosystems 384 Eich, Brendan 14, 256, 261, 264, 418 Electron 39, 403–405, 409–410 alternatives for 410 applications using 405–408 benefits of 409–410 cross-platform desktop apps 408–409 drawbacks of 410–411 Hello Everyone Code in 412–413 program 240 significance of 411 UIs with 413–416 element methods 438–439 Ember JS 21–22, 213, 223–224 encodeURI() function 434 end-to-end tests 301 environment configuration 373; see also configurations environment setup, for VueJS 318–321 errors 114–122 escape character 435; see also characters ESLint 65 eval() function 434 events 122–128 exceptions 114–122 “Expires” and “Max-Age” parameters, cookies 169 Express.js 17–18, 275, 307–308, 367 backend framework 361–363 benefits of 308–309 ‘extends’ keyword 465 external modules, in TypeScript 471 Extract functionality 43 Facebook advertisements 385 Fetch function 156–158; see also functions

filter() method 439 first application of Node.js 340–342 first-party cookies 170; see also cookies Flexbox layout engine for mobile apps 384 Flexible Document Model 360 Flutter, frontend frameworks and libraries 255, 258, 259, 272, 273 flux pattern 278 focus() function 443 for-in loop 91–92 for loop 90 forms login form 174–175 overview 172–173 referencing form 173–174 SignUp form 175–176 submitting form 174 foundational elements of TypeScript 448–449 frameworks 15–16, 211–213 backend frameworks (see backend frameworks) benefits and drawbacks of 18–26 for desktop applications (see desktop applications) for developing mobile apps (see mobile applications) frontend frameworks (see frontend frameworks) jQuery and JS libraries 16 libraries and 16–17, 213 maturity 409 for project support 242–244 frontend development 271–272 frameworks (see frontend frameworks) languages 272 layer 366–367 libraries 272–273, 363–364 rich platform 372 frontend frameworks 17 Angular 217–219 Backbone.js 224–226 development 272–273 Ember 223–224 jQuery 219–221 React 214–215 Svelte 221–223 Vue.js 215–217

Index   ◾    513 Frontend Web Developer 424–425 fullPage.js 202 Full Stack Developer in JavaScript 427 full-stack online applications 358 functions asynchronous function (see asynchronous function) Fetch function 156–158 in JavaScript 92–95, 433, 434 in TypeScript 471–473 fundamental operators 431 fuzzy finder 40 “-g” parameter 482; see also parameters game creation 5–6 gameengines Babylon.js 232 GDevelop 233 Kiwi.js 233 Melon.js 232 Phaser 231–232 PixiJS 231 PlayCanvas WebGL 232 Three.js 233 Gatsby 228 GDevelop 233 getAttribute() method 438 getAttributeNode() method 438 getAttributeNodeNS() method 438 getAttributeNS() method 438 getDate() method 440 getDay() method 440 getElementsByClassName() function 147–148 getElementsByName() method 149 getElementsByTagName() method 149, 438 getElementsByTagNameNS() method 438 getFullYear() method 440 getMinutes() method 440 getTime() method 440 Ghost Electron app 406–407 Git control 40, 42 GitHub 2, 24, 40, 214, 217, 282, 381, 385, 400, 405 Glimmer 200–201 global mode package installation 506 global scope 313

global variable 80–81 Google Chrome JavaScript V8 engine 3 Google trends 381 Granim.js 201–202 GraphQL API 67 GruntJS 486–487 features in 487–488 getting started with 492–495 Gulp vs. 495–499 setting up of 488–491 Gulp 479–480 application of 484–486 basics of 482–484 vs. GruntJS 495–499 installation of 481–482 gulpfile.js 484 handy JavaScript tools GruntJS (see GruntJS) Gulp (see Gulp) Node Package Manager (see Node Package Manager) use of 280 hasAttribute() method 438 hasAttributeNS() method 439 Hello Everyone Code in Electron 412–413 ‘Hello, World!’ program 74 Hevery, Misko 295 HTML see Hypertext Markup Language (HTML) HtmlWeb-packPlugin plugin 291 HTTP cookies (see cookies) requests 153–164 HttpOnly property 171 hybrid app 235; see also applications Hypertext Markup Language (HTML) 11, 33, 46, 72, 144, 145, 227, 272, 374–375, 413, 417, 423, 425, 429, 441, 479 Hypertext Preprocessor 252 HyperText Transfer Protocol (HTTP) 367 ideal JavaScript framework 226–227 identifiers 78 IDEs see integrated development environments (IDEs) if-else statement 84–88

514   ◾    Index in-depth analysisvs. Node.js 268–269 indexOf() array 435 innerHTML property 151–152 innerText property 152–153 insertOne() method 356 instances of JavaScript variables 430 in Vue.js 325–327 integrated development environments (IDEs) 38–40, 42, 44, 46, 54, 455, 457 interactive website behavior 4–5 interfaces; see also user interface (UI) Application Programming Interface (API) 181–191, 367, 434 application user 359 in TypeScript 466–468 internal modules, in TypeScript 471 International Electrotechnical Commission (IEC) 12 International Organization for Standardization (ISO) 12 Internet of Things 268, 335, 405 Ionic framework 235, 373, 376 isNaN() function 434 Java 8, 422 backend language 274 vs. JavaScript 14, 244–247, 421–422 JavaFX 404 Java JDK 380 JavaScript (JS) 417–418; see also NativeScript; TypeScript Angular JS vs. 260–263 API (see Application Programming Interface (API)) applications of 4–6 array in 98–101, 434–435 asynchronous function in 134–144 benefits of 6 Boolean object 113–114 browser objects 441–444 client-side JavaScript 3 comment in 77–78 controls of 14–15 Dart vs. 254–260 data types in 5, 81, 430–431 date object in 106–109, 440

definition of 1 for desktop applications (see desktop applications) developer skilled in 425–428 development tools 8–9 editors (see JavaScript (JS) editors) errors and exceptions in 114–122 events in 122–128 evolution of 9–14 first code 75–77 flaws of 6–7 form in (see forms) frameworks (see frameworks) frontend language 272 functions in 92–95, 433, 434 gameengines (see gameengines) ‘Hello, World!’ program in 74 HTTP requests in 153–164 if-else statement in 84–88 innerHTML property in 151–152 innerText property in 152–153 install, in Visual Studio Code 46–54 vs. Java 14, 244–247 jQuery vs. 251–252 libraries (see libraries) loops in 89–92 math in 109–112 for mobile usage (see mobile usage) Node.js vs. 264–269 number object in 112–113 objects in 95–98 operators in 82–84, 431–433 opportunities for professional development 424–425 Oracle 12, 14, 15 past and future 418 PHP vs. 252–254 purpose of 3 Python vs. 247–250 qualities 418–424 standards 12 strings in 102–105, 435–436 switch statement in 88–89 syntax of 74–75 tendencies 11 transform data 439–441 unique among programming languages 7–8

Index   ◾    515 validation of forms (see validation of JavaScript forms) variables in 78–81, 430 Visual Studio Code extensions for 64–70 website 33–35 JavaScript Booster 69 JavaScript (ES6) code snippets 64–65 JavaScript (JS) editors Atom 39–40 Brackets 43 Eclipse 41–42 NetBeans 44 Sublime Text 42–43 Vim 44–45 Visual Studio (VS) Code 40–41, 45–46 JavaScript/React code.Preprocessors 302 JavaScript XML (JSX) 193, 278, 280, 297, 363 Java SE Development Kit (JDK) 378 Jest JavaScript testing framework 30 join() array 435 jQuery 2, 16, 191–192, 212, 219–221, 236–237, 374, 376 frontend frameworks and libraries 273 vs. JavaScript 251–252 UI 220 jQuery-based widget library 220 JS see JavaScript (JS) JSX see JavaScript XML (JSX) just-in-time (JIT) compilers 420–422 Kiwi.js 233 Kotlin 420 Ky 162–164 languages; see also programming languages backend JavaScript frameworks 274 C++ 274, 335, 417 CSS language 33, 46, 72, 227, 272, 375, 479–480 frontend development 272 Java (see Java) Non-Structured Query Language (NoSQL) 367 object-oriented programming (OOP) language 95, 462

PHP (see PHP) Python (see Python) of TypeScript 448 Laravel 275 lastIndexOf() array 435 Last In First Out (LIFO) principle 28 Lax value, cookies 170 Leaflet 202–203 learning curves 258 for NativeScript and React Native 399 libraries Algolia Places 195–196 Animate On Scroll (AOS) 197 Anime.js 196–197 Bideo.js 198 Chart.js 198–199 Chreographer.js 199–200 Cleave.js 199 D3.js 193–194 vs. frameworks 26, 213 frontend libraries 272–273 fullPage.js 202 Glimmer 200–201 Granim.js 201–202 in JavaScript 212 jQuery 191–192 Leaflet 202–203 Lodash 195 Masonry 204–205 Moment.js 204 Multiple.js 203–204 Omniscient.js 205 Parsley 206 Polymer 208 Popper.js 206–207 React.js 192–193 Screenfull.js 207–208 Three.js 207 Underscore.js 194–195 Voca 208–209 Linux installing Visual Studio Code on 54–55 Node.js installation on 61–62 LiveScript 256, 261, 264 Live Server 68 Live Share 68 Live updates for IOS 382 local variable 79–80

516   ◾    Index Lodash 195 logical errors 116 logical operators 83, 433 loops in JavaScript 89–92 Macromedia Dreamweaver MX 8 Macromedia’s HomeSite 5 9 Main.js 292 main vs. renderer processes 411–412 map() method 439 Masonry 204–205 match() function 434 Material UI 215 math, in JavaScript 109–112 MEAN vs. MERN Stack 368–369 Melon.js 232 MERN Stack 358–368 vs. MEAN Stack 368–369 structural makeup 365 Meteor 22–23, 238, 377 microservice design 335 Microsoft Debugger for Chrome 67 Microsoft FrontPage 8 Microsoft Internet Explorer 171 Microsoft’s JScript 9 Microsoft Word 404 Mithril 22 Mobile Angular UI 237 mobile applications 4, 233–234, 373–376; see also crossplatform applications; desktop applications Apache Cordova 235–236 benefits of 376–377 development of 372 Ionic 235 jQuery 236–237 Meteor 238 Mobile Angular UI 237 NativeScript 234–235 OnSen UI 236 React Native 234, 380–390 Sencha Touch 237 Titanium 238 use JavaScript 374–376 mobile usage

mobile app development (see mobile applications) NativeScript (see NativeScript) programming languages (see programming languages) React Native 377–390 mobility 242 Mocha 418 model view controller (MVC) 26 architectural concepts 221 design pattern 279 framework 295 paradigm 262 modern JavaScript 9–10 modules, in TypeScript 470–471 Moment.js 204 MongoDB database 342–346 advantages and disadvantages 346 data modeling 344 features 345–346 getting started with 346–349 installed on Windows 350–356 vs. RDBMS 344 “mongod” command 347 moveBy() function 443 moveTo() function 443 Mozilla Foundation 357 multiline comment in JavaScript 78 Multiple.js 203–204 Muuri 220 MVC see model view controller (MVC) namespaces, in TypeScript 470 NAN (not a number) 444 Native apps 397–398; see also applications native Fetch API 162 Native React 376 NativeScript 234–235; see also JavaScript (JS); TypeScript advantages of 391–392 Android apps 390–391, 397–399 cases usage 396–397 framework 374 learning curves for 399 limitations of 392–393 Playground app 390, 395–396

Index   ◾    517 with React Native 399–401 setups for 393–395 nested namespaces 470 .NET 405 NetBeans 44 Netscape browser 9, 418, 420; see also browsers new Date() operator 440 new React project 293–294 Next.js 18, 24–25 Ngx-bootstrap 218 NodeGUI 240 Node.js 2–4, 10, 22, 23, 40, 46, 240, 244, 256, 293, 307, 309–311, 333–334, 394, 409, 410, 420, 455, 479, 500 asynchronous function 131–133 backend language 274 buffer 312 defaults to local 312 development environment 55–60 downsides of 336–337 environment, setup of 338–340 first application of 340–342 functions 312 global scope 313 vs. JavaScript 264–269 JS Runtime Environment 365–367 Linux, installation on 61–62 loose typing 311 methods 437–438 object literal 311 primitive types 311 process object 312 project in Visual Studio Code 62–64 properties 436–437 use of 334–335, 338 Windows, installation on 55–60 Node Package Manager (NPM) 293, 365, 499–500 Command-Line Client 505 components of 500 download 503–505 features of 504 global mode package installation 506 package.json 506 packageName package 507–508

packet installation in local mode 506–507 removing local packages 507 Setting Up 500–504 NodeSource repository 61 Node Version Manager 500 non-blocking input/output architecture 336 None value, cookies 170 non-primitive data types in JavaScript 81 Non-Structured Query Language (NoSQL) 367 Not Only SQL database 350; see also databases Not simply SQL database 342; see also databases NPM see Node Package Manager (NPM) Number() function 434 numbers object in JavaScript 112–113 in TypeScript 473 NW.js 241 Object Creation 95–97 Object Methods 97–98 object-oriented programming (OOP) language 95, 462 objects in JavaScript 95–98 in TypeScript 468–469 offline assistance 373; see also assistances Omniscient.js 205 onclick Event Type 123 onerror() function 120–122 one-way data binding 297 onmouseout event 124–125 onmouseover event 124–125 OnSen UI 236 onsubmit Event Type 123–124 Oomph Project 41 open() function 443 open-source Flutter UI development SDK 273 open-source software 390 document-oriented database 350 framework 240

518   ◾    Index open-source software (cont.) Javascript library 251 projects 381–382 server environment 367 operators 82–84, 431–433 Oracle 12, 14, 15 packages administrators 483 Day.js package 212 global mode package installation 506 Node Package Manager (see Node Package Manager (NPM)) package.json 456, 504–506 packageName package 507–508 packet installation in local mode 506–507 parameters default parameters 473 “Expires” and “Max-Age” parameters 169 “-g” parameter 482 rest parameters 472–473 parseFloat() function 434 parseInt() function 434 parse() method 440 Parsley 206 path property, cookies 168 Pexels Electron app 407; see also applications Phaser 231–232 PhoneGap 373, 376 PHP 8, 423; see also languages; programming languages backend language 274 vs. JavaScript 252–254 PixiJS 231 Plain Old JavaScript (POJO) model 295 PlayCanvas WebGL 232 Playground app 390, 395–396; see also applications plugins 499 Polymer 24, 208 pop() array 434 Popper.js 206–207 preprocessors 483 Prettier 65–66 primitive operators 431–432 primitive types

data 5, 81 of Node.js 311 print() function 443 professional development designer and developer of web applications 425 frontend web developer 424–425 professional JavaScript app 375 programming client-side programming 256 compiler-free programming 34 languages (see languages; programming languages) Server-side JS 256 Server-Side Website Programming 356–358 traditional programming 34 programming languages 342, 371, 377; see also languages; programming case-sensitive programming language 77 client-optimized programming language 255 C programming language 420–421 development 372 dynamic programming language 417 extremely responsive 372 frameworks 373 frontend rich platform 372 Ionic framework 373 jQuery 374 native script framework 374 object-oriented programming (OOP) language 95, 462 offline assistance 373 PhoneGap 373 React Native 374 suitable for developers 373 Tabris.js 374 TypeScript 298 prompt() function 434, 443 Proton Native 241 Prototype.js 194 push() array 434 Python 378, 422–423; see also languages; programming languages backend language 274

Index   ◾    519 vs. JavaScript 247–250 libraries 62 querySelector() function 148 quick feature delivery 409 Quokka.js 66 React Developer Tools 280 React.js 17, 18, 20–21, 192–193, 213, 214–215, 239–240, 244, 276–277, 293, 296 AngularJS vs. 295–298 benefits of 279–281 characteristics of 297 drawbacks of 281–282 environment, setup of 286 features of 277–279 frontend frameworks and libraries 273, 363–364 installation methods 286–295 and Svelte 298–301 version of 282–285 React JSX 302; see also React.js attributes in 303–305 comments in 305–306 nested elements 303 styling in 306–307 use of 302–303 React Native 234, 374, 377–380; see also React.js; React JSX framework for mobile app 380–388 learning curves for 399 vs. NativeScript 399–401 React Semantic UI 215 React Virtual DOM 280 reduce() method 440 registry 500 removeAttribute() method 439 removeAttributeNS() method 439 Resign, John 191, 219 resizeBy() function 443 resizeTo() function 443 REST Client 67 rest parameters 472–473; see also parameters reusable program 398 reverse() array 434

robust framework 227; see also frameworks routing process 296 Ruby on Rails framework 8, 275, 423–424; see also frameworks rule of thumb 227 Runtime Environment 357 runtime errors 115–116 SameSite property, cookies 169–170 scalability 242, 345, 360 schema-less database 345; see also databases scope of cookies 168–170; see also cookies Screenfull.js 207–208 scrollBy() function 443 scrollTo() function 443 Search Engine Optimization (SEO) 359 secure cookies 171–172; see also cookies security 30–31 semicolon character 76; see also characters Sencha Touch 237 server applications, development of 4 serverless architecture 334–335 Server-side JS 357–358 development 333 processing 334 programming 256 Server-Side Website Programming 356–358 Server-Side Public License (SSPL) 342 Server-Side Rendering (SSR) 217 Server-Side Website Programming 356–358 session cookies 169, 171 setAttributeNode() method 439 setAttributeNodeNS() method 439 setDate() method 441 setInterval() method 442 setTime() method 441 setTimeout() method 442 Setting up Express 309–311 setup program chocolaty setup program 378–379 for NativeScript 393–395 for React.js 286 for Vue.js 318–321

520   ◾    Index Several.js 203 shift() array 434 SideBar Enhancements 42 Simform 214 Simple Environment Configuration 360 simple interpolation approach 327 single codebase 235, 409 single-line comment in JavaScript 77–78 Single-Page Applications (SPAs) 215 Skype app 385; see also applications Slack desktop app 407, 408; see also applications slice() array 435 software developers 381; see also developers sort() array 435 special character 435; see also characters special operators 84 SpiderMonkey 357–358 splice() array 434 Spring 275 stack data structure 28 standalone level vs. cross-platform app 239 standard HTML 5 events 125–128 standard server-oriented development approach 373 ‘static type checking,’ TypeScript 449–452 stop() function 443 strict value 170; see also cookies strings 102–105, 435–436 Sublime Text 42–43 substantial community support 398–399 Sun Microsystems 418 SuperAgent 161–162 superb JavaScript editor 46 Svelte 221–223 React.js and 298–301 testing library 301 Svelte-flow 222 Svelte Material UI (SMUI) 222 Svelte-written programs 299 switch statement 88–89 synchronous JavaScript 141–142 ‘syntactic sugar’ 419 syntax of JavaScript 74–75

errors 115 functions 93 Tabnine 70 Tabris.js 374 task executors 483 templates 314–315 in Vue.js 327–331 Tesla app 386; see also applications testing 30 text-based editor 44 third-party cookies 171; see also cookies “this” keyword 464 Three.js 207, 233 3-tier architecture system 366 throw Statement 119–120 Titanium 238 toString() array 435 Traditional Document Object Model 300 Traditional JavaScript frameworks 281; see also frameworks traditional programming 34; see also programming transform data, JavaScript 439–441 transpilers 302 tsconfig.json 457–458 tuples, for TypeScript language 475–476 two-way communication 322 TypeScript 318, 419, 447–448; see also JavaScript (JS); NativeScript ambients in 476–477 arrays in 473–475 classes 462–465 class inheritance 465–466 crash course 454–459 for developers 459–462 foundational elements of 448–449 functions in 471–473 interfaces 466–468 modules in 470–471 namespaces in 470 numbers in 473 objects in 468–469 primary attributes and functions 452–453 programming language 298

Index   ◾    521 static type checker 449–452 tuples for 475–476 type template for 469 union in 476 use of 453–454 TypeScript compiler (tsc) 449, 451, 453, 456–457 type template for TypeScript 469 typical cookie properties 168–170; see also cookies Ubuntu’s official repository 61 UI see user interface (UI) Underscore.js 194–195 Union, in TypeScript 476 unshift() array 435 user interface (UI) 72, 296, 321, 373; see also interfaces designer 426 with Electron 413–416 kit 217 performance 31 validate() method 124 validation of JavaScript forms 177; see also forms email validation 180–181 example 177–178 number validation 178–179 using an image 179–180 valueof() array 435 Vanilla JS 71–73, 428 Vanilla JS vs. React JS 27 applications 27 convenience for the developer 31–32 development cost 32–33 functionality 27 maintenance 32 performance 28–29 security 30–31 stack data structure 28 testing 30 UI/UX performance 31 variables 78–81, 430 “var” keyword in JavaScript 430 version of React 282–285

Vim 44–45 Virtual DOM 278, 280, 297, 300, 313, 315, 322, 363 Visual Studio (VS) Code 39, 40–41, 45–46, 455 extensions for JavaScript developers 64–70 JavaScript installation in 46–54 Linux, installing on 54–55 Node.js project in 62–64 V8 JavaScript engine 61 Voca 208–209 Vue CLI version 315, 324 Vue.js 17, 21, 212–213, 215–217, 313 advantages of 321–322 vs. AngularJS 316–318 companies 323–324 comparative assessment of frameworks 315–316 environment setup for 318–321 features 313–315 instances in 325–327 popularity 316 template-based method 316 template in 327–331 version 324 Walke, Jordan 192, 214, 296 watchers 315 web applications (see applications) cookies (see cookies) development framework 427 layer 366–367 vs. mobile 258 servers 4 website 33–35, 72 Webpack 289–291, 320–321 Webpack-dev-server 287 WebTorrent desktop app 405–406; see also mobile applications wget command 55 WhatsApp Electron app 408; see also applications while loop 89–91, 417

522   ◾    Index Windows MongoDB database installed on 350–356 Node.js installation on 55–60 WordPress desktop app 406; see also applications worker threads module 336

Xcode 395 XMLHttpObject 155–156 XMLHttpRequest 153–156 Zeit 228 zombie cookies 172; see also cookies