Conquering JavaScript
Conquering JavaScript
Conquering JavaScript: The Practical Handbook helps the reader master the
JavaScript (JS) programming language for faster and more robust develop-
ment. 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 cross-
platform 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
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
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.
DOI: 10.1201/9781003356578
Typeset in Minion
by codeMantra
For Dad
Contents
vii
viii ◾ 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’? 71
Why Should We Learn Pure JS? 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 78
VARIABLE IN JAVASCRIPT 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
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
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
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 <script> Tag in an HTML File 318
By Using the CDN 318
By Using the NPM 320
Contents ◾ xxvii
SERVER-SIDE JS 356
Server-Side Website Programming 356
Engines That Run JavaScript 357
Runtime Environment 357
Uses of Server-Side JavaScript 357
MERN STACK 358
Acquainting Oneself with MERN Stack Components 358
1. M
ongoDB: Cross-Platform Document-Oriented
Database358
Why Should We Create Mobile and Web Applications
with MERN Stack? 359
Why Employ MongoDB? 360
2. Express: Backend Framework 361
Why Use Express? 362
3. React: Frontend Library 363
Why Use React? 363
4. Node.js: JS Runtime Environment 365
Why Use Node.JS? 365
What Is the MERN Stack’s Structural Makeup and
How Does It Operate? 366
Web or Frontend Layer 366
Server or Middle Tier 367
Database as Backend Tier 367
MERN VS MEAN 368
What Are MERN Stack Developers’ Futures? 368
NOTES 369
INDEX, 509
About the Editor
Sufyan bin Uzayr is a writer, coder, and entrepreneur with over a
decade of experience in the industry. He has authored several books in
the past, pertaining to a diverse range of topics, ranging from History to
Computers/IT.
He is the Director of Parakozm, a multinational IT company special-
izing in EdTech solutions. He also runs Zeba Academy, an online learning
and teaching vertical with a focus on STEM fields.
He specializes in a wide variety of technologies, such as JavaScript,
Dart, WordPress, Drupal, Linux, and Python. He holds multiple degrees,
including ones in management, IT, literature, and political science.
He is a digital nomad, dividing his time between four countries. He
has lived and taught in numerous universities and educational institutions
around the globe. He takes a keen interest in technology, politics, litera-
ture, history, and sports, and in his spare time, he enjoys teaching coding
and English to young students.
Learn more at sufyanism.com.
xxxv
Acknowledgments
There are many people who deserve to be on this page, for this book would
not have come into existence without their support. That said, some names
deserve a special mention, and I am genuinely grateful to
xxxvii
Zeba Academy –
Conquering JavaScript
• Divya Sachdeva
• Jaskiran Kaur
• Simran Rao
• Aruqqa Khateib
• Suleymen Fez
• Ibbi Yasmin
• Alexander Izbassar
Zeba Academy is an EdTech venture that develops courses and content for
learners primarily in STEM fields, and offers educational consulting and
mentorship to learners and educators worldwide.
xxxix
Chapter 1
Introduction to
JavaScript
IN THIS CHAPTER
➢ What is JS?
➢ Advantages and Disadvantages
➢ Evolution of JS
➢ What are frameworks?
➢ Comparison with Vanilla JS
DOI: 10.1201/9781003356578-1 1
2 ◾ Conquering JavaScript
CLIENT-SIDE JAVASCRIPT
The most frequent version of the language is client-side JavaScript. For
the HTML code to be understood by the browser, the script must be inte-
grated into or utilized as a reference by an HTML page. It suggests that
a web page need not be static HTML, but rather might incorporate pro-
grams that communicate with users, manage browsers, and dynamically
create HTML content.
The JavaScript client-side technique outperforms classic CGI server-
side scripts in many ways. JavaScript might be used to validate user input
in a form field, such as an email address. The JavaScript code is called
when the user submits the form, and only if all of the inputs are accurate
are they transmitted to the web server.
JavaScript may be used to record explicitly or implicitly performed
actions by users, such as button clicks, link navigation, and other actions.
Primitive data types, which include all data types except object, may
only hold a single piece of data. Meanwhile, the object data type may
hold a set of values.
Cookies can also be used with JavaScript to improve the online
browsing experience of users. The document is required for creating,
reading, and removing cookies in JavaScript. cookie attribute, which
serves as a getter and setter of cookie values.
4. Game Creation
When used with HTML5 and an Application Programming
Interface (API) such as WebGL, JavaScript may assist us in creating
a game. There are several JavaScript-based game engines available,
6 ◾ Conquering JavaScript
JAVASCRIPT’S EVOLUTION
JavaScript continues its reign as the most popular programming language,
with 67.8% of developers using it in 2019.
Its rise to the world’s most popular programming language is inextrica-
bly linked to the rise of the internet itself.
It was developed out of necessity and is now used to build 95.2% (1.52
billion) of websites, including some of the world’s largest, such as Facebook
and YouTube.
We wouldn’t have popular and useful web apps like Google Maps and
eBay without it.
JS, which was originally intended to be part of Java, grew swiftly, and
eventually became a separate programming language with its own
ECMAScript definition.
In terms of frontend development, GBKSOFT employs the JavaScript
Programming Language, the Node.js environment, and the AngularJS
framework.
The final two are frameworks created in the JavaScript Programming
Language.
JavaScript Tendencies
HTML5: HTML5 is a new version of HTML that supports new tags and
browser capabilities such as
Standardizing JavaScript
JavaScript adheres to two standards:
Various Variations
The original JavaScript has been changed to conform to ECMA-262
Edition 5 and subsequent versions. Many engines support the JavaScript
Computer Language. This includes the following:
JAVASCRIPT FRAMEWORK
Consider constructing websites and web apps like building a house—we
could produce all of our own construction materials from scratch and
start building without any plans, but that method would be extremely
time-consuming and inefficient.7
It’s more likely that we’d buy pre-fabricated building components
(wood, bricks, countertops, etc.) and then assemble them to our specifica-
tions using a plan.
16 ◾ Conquering JavaScript
Frontend Frameworks
There are varied types of Frontend Frameworks, which we will discuss
below:
REACT
Facebook built React.js, an efficient and versatile JavaScript toolkit for
designing user interfaces.8
For all intents and purposes, React is a JS library; however, it is often
referred to as a web framework and compared to other open-source JavaScript
frameworks. Because it uses predictable JavaScript code that is simple to
debug, React makes it simple to construct interactive user interfaces.
It also has a REACT component system, which allows blocks of
JavaScript code to be created once and reused in other portions of the
program or even other apps.
ANGULAR
AngularJS is a famous enterprise-level JavaScript framework used for con-
structing big and complicated corporate applications.
It is an open-source web framework designed by Google and backed by
both Google and Microsoft.
VUE
Vue.js is a modern framework for designing user interfaces.
It is an up-and-coming framework that aids developers in interacting
with other libraries and current applications.
It contains an ecosystem of libraries that enable developers to construct
complicated and solid single-page apps.
Backend Frameworks
There are varied types of Backend Frameworks, which we will discuss
below:
EXPRESS
Express.js is a versatile, simple, lightweight, and very well platform for
Node.js applications.
18 ◾ Conquering JavaScript
NEXT.JS
Next.js is a basic framework that enables a JavaScript developer to use
React.js to construct server-side rendering and static web apps.
It is one of the most recent and popular frameworks, and it takes plea-
sure in its simplicity.
Next.js solves many of the issues that developers have while designing
apps using React.js.
It includes several crucial features ‘out of the box,’ making JavaScript
programming a breeze. React.js is the most popular JavaScript frame-
work/library in the present employment market. Because JavaScript has
so many frameworks, it might be difficult to determine which one to learn
first. We could start with any framework, but if our objective is to acquire
a job, learning React first will give us a higher chance.
The same can be said about Express.js, the most frequently used and
sought-after backend framework. JavaScript frameworks make it easy to
create online apps and deal with JavaScript.
This is why they are so popular among programmers. There are several
frameworks because they may be used to tackle various challenges.
Before opting to adopt any specific JavaScript framework, thor-
oughly analyze our project needs. Aside from the distinct technologi-
cal capabilities of JavaScript frameworks, each framework has its own
learning curve, community engagement/support, documentation, and
compatibility.
The libraries are compiling code for the particular application type
that we may work on. The framework will effectively define the program’s
structure on its own. Each JavaScript framework uses a distinct function.
JavaScript is a solid choice for web development, and many of its struc-
tures are built around it.
The following are the most popular JavaScript frameworks these days:
• Vue JS
• Angular
• React Native
• Ember JS
• Mithril
• Meteor
• Node JS
• Polymer
• Next JS
• Aurelia
Let’s compare the best JavaScript frameworks and see what makes each
one special.
Pros:
• Data synchronization between the model and the display.
• Model updates are immediately visible in the display.
• The application of guidelines: This enables developers to utilize
features and create change instructions.
20 ◾ Conquering JavaScript
Cons:
• It does not support JavaScript in many choices.
• A developer must be familiar with MVC in order to utilize
angular.
Pros:
• It converts the physical DOM into a virtual DOM.
• It helps developers write better code and generate better user
interfaces.
• It contains unidirectional data.
• Child elements have no effect on parent components.
• Use JSX to increase code reusability.
Cons:
• It is tough to learn and understand.
• It is a framework with inadequate documentation.
Introduction to JavaScript ◾ 21
Pros:
• Vue JS makes use of HTML templates.
• The DOM is used to collect data.
• Data is sent in both directions.
• Vue JS is more reactive than previous frameworks.
• It is straightforward to interface with different frameworks.
Cons:
• Its versatility overburdens the developer.
• It is the most recent library, and there are fewer developers.
Advantages:
• Powerful add-ons
• Ember CLI
• Convention over configuration
• Community
• Stability sans stagnation
• Ember Octane
22 ◾ Conquering JavaScript
Cons:
• Difficult to learn
• Sluggish Popularity Due to Strong Opinions
Pros:
• Lightweight
• React is faster
• It is compatible with ES6
• Development that is quite active
• Flux-compatible intelligent auto-redrawing system
• A Short Learning Curve
Cons:
• Virtual Dom
Pros:
• It is simple to get started and rapidly distribute a prototype to
end consumers
• Hot code deployment
Introduction to JavaScript ◾ 23
• Full-stack responsiveness
• This is useful for real-time applications
• Allows us to create an MVP
Cons:
• Auto-bundling
• Build system that optimizes itself
• There is a speed issue
• Development is unpredictable
Pros:
• Asynchronous event-driven IO facilitates concurrent request
processing
• It is simple to learn
• The identical piece of code should be used on both the server and
client sides
• NPM, or Node packaged modules, is massive and still expanding
• A vibrant and busy community
• Stream large files
Cons:
• There is no scalability
• A relational database is a must-have
• Callback that is nested
• CPU-intensive activities are not supported
24 ◾ Conquering JavaScript
Benefits:
• Web components
• Design of materials
• Backed by Google
• Data Binding
• Open-source
• Designer friendly. HTML concepts
Cons:
• We need to work harder to build components that work in all
browsers.
• Shadow DOM is used by several browsers.
• Mobile Performance is slow.
Pros:
• Automatic server rendering and code separation
• Setup is simple
• Generator of static websites
• Simple to set up
Introduction to JavaScript ◾ 25
Cons:
• The price of flexibility
• Management and development
• It has an opinion
• There is no built-in state manager
• There aren’t enough plugins
10. Aurelia: Aurelia creates sophisticated browsers, web apps, and desk-
top applications using a library of JavaScript components.
It, too, is open source and incorporates web standards.
Pros:
• Conventions made simple
• Extensible modern architecture
• Combines nicely with other components
• Simple to use
• Dependency
• Injection
• Excellent modular router
• Data Binding that is Adaptive
26 ◾ Conquering JavaScript
Cons:
• Limited documentation
• Small community
determining the adjustments required for the normal DOM. This whole
process may be so rapid that developers may believe there would be per-
formance difficulties with UI rendering.
However, React JS offers a set of workarounds that will overcome any
performance problem. We may be shocked to learn that Vanilla JS is much
quicker than other JavaScript frameworks. As a result, we may argue that
it outperforms leading frontend frameworks.
We will see that Vanilla JS initially produces the UI over 30 times
quicker than React JS, which is one of the key reasons why Vanilla Js out-
performs React JS.
Handling UI state changes in Vanilla Js is simpler and quicker than in
React JS.
Vanilla JS outperforms React JS in terms of performance.
Future Prospects
Future comparison of React vs Vanilla Js is crucial because it will show us
which JavaScript is best.
ReactJs is an important library that developers may use to create
JavaScript apps.
We will see that ReactJs is a framework for developing fast and scalable
online apps.
New plugins for future elements are continually being developed in this
framework.
Because the technology is utilized in a variety of industries, ReactJs
developers and ReactJs Development Companies that provide varied
React js development services have a promising future.
The ReactJs community will also expand over time, and the framework
will be updated.
Vanilla Js is also known as pure JavaScript since it does not include any
other libraries, such as jQuery.
Some developers may use it as a joke to educate younger devs that many
things can be done without the usage of extra JavaScript libraries.
It is possible to build web applications using JavaScript.
That is why we must grasp the fundamental concepts of JavaScript and
study Vanilla Js.
New JavaScript frameworks will be launched in the future.
However, before utilizing such frameworks, we must be familiar with
Vanilla Js.
30 ◾ Conquering JavaScript
Winner: Both ReactJs and Vanilla js are promising since they are both
needed by all JavaScript frameworks, although ReactJs has a somewhat
better future.
Testing
It will be difficult to determine the victor of a comparison of Vanilla JS vs
React JS for testing.
We may test ReactJs code just as we would any other simple JavaScript
code.
ReactJs has many testing libraries that may be used for testing.
The ReactJs testing library is a collection of helper libraries that allow
us to test ReactJs components without depending on their implementation
details.
We might claim that this way of evaluating ReactJs assures that it is the
best practice for ensuring code accessibility.
We must also set up the ideal testing environment for all ReactJs com-
ponents when testing the ReactJs code.
Many people are unaware that Vanilla js code may be readily tested.
Jest, a JavaScript testing framework that focuses on simplicity, must be
installed by the developers.
This Jest JavaScript testing framework is also compatible with AngularJS
and ReactJS.
With the aid of Jest, testing with Vanilla js is a breeze.
Installing npm or yarn on the device is necessary for developers who
want to test Vanilla js code in Jest.
Winner: Because testing in ReactJs and Vanilla JS is straightforward,
both are winners.
Security
We’ll see that ReactJs is a JavaScript framework for creating web apps.
ReactJs has fewer attacking points than other frameworks that are used
to construct various web apps. Because few security concerns have been
disclosed, ReactJs is not completely safe.
Because ReactJs is compatible with a variety of open-source compo-
nents, it lacks robust default security settings. As a result, ReactJs is exposed
to several security vulnerabilities. Because of weaknesses in the security
mechanism, ReactJs online apps are not completely safe. Vanilla js may
Introduction to JavaScript ◾ 31
Maintenance
ReactJs maintenance regularly analyses and monitors the online applica-
tion. It will ensure that the web applications’ security, speed, output, and
overall performance are satisfactory. If developers want to maintain their
applications up to date, quicker, and fresh, they should remember that
ReactJs offers a solid maintenance solution.
ReactJs offers three kinds of maintenance services: ReactJs startup
maintenance, ReactJs professional maintenance, and ReactJs business
maintenance.
We will notice that developers dislike using the Vanilla js framework
due to the expense of upkeep. If the developers code an eCommerce web-
site with Vanilla js, the maintenance and development time will be higher.
We will notice that it is one of the primary reasons why developers
choose to utilize numerous JavaScript frameworks available on the mar-
ket, such as AngularJS, ReactJS, Vue.js, and so on.
Winner: ReactJs is much superior to Vanilla js in terms of maintenance
since developers can easily maintain web apps.
Development Cost
Both are efficient JavaScript frameworks for creating web applications.
Introduction to JavaScript ◾ 33
We will see that ReactJs developers may charge between $20 and $40
per hour to create ReactJs web apps. Vanilla js developers may charge over
$1,000 to create vanilla js web apps.
However, due to the popularity of ReactJs web apps, many in the mar-
ket choose to engage ReactJs developers for web app development.
Winner: While developing a Vanilla JS application may be less expensive,
many prefer to employ a ReactJs developer, which may be pricey at times.
• Developing applications for end users: It’s unusual since it’s not
executed on the web server itself. As web designers, we understand
how crucial it is for our readers to have a quick website load time. The
longer something takes to load, the less enjoyable it is for the user.
When a JavaScript animation loads, it executes in the background on
the viewer’s device CPU. This drastically lessens the demand on the
web server and shortens the time it takes for pages to load.
• Small learning curve: JavaScript isn’t the sole online programming
language, and learning it isn’t particularly difficult. Some more are
34 ◾ Conquering JavaScript
Python, C++, and a few others. This makes it the most widely used
language, and it also makes it the simplest to master. JavaScript syn-
tax is quite close to the English language. It doesn’t take weeks for
developers to create a new site since they don’t have to spend time
figuring out the purpose of each line of code. A single second may
make or break a project in the frantic world of Toronto web develop-
ment. Our website will be live to the public quicker if the developer
employs JavaScript.
• Compatible with other languages: Web servers utilize a wide variety
of languages, and it’s important that they all work together smoothly.
The list of popular programming languages includes Python, PHP,
Ruby, Rails, ASP.NET, and Java, just to name a few. JavaScript’s com-
patibility with a wide variety of server languages ensures that our
audience will always enjoy a dynamic and engaging experience.
• Uses the DOM model: The DOM model is a way of organizing a
website’s structure so that its components may be styled as “objects”
with their own attributes. This makes it simple for JavaScript to
apply animations and transitions to any element. There is no spe-
cific programming language for working with the DOM (Document
Object Model). Using JavaScript, a developer may create a DOM for
a website.
• Compiler-free programming: Traditional programming makes
use of a compiler; compiler-free programming avoids this step. For
a browser to function, raw code must be compiled into understand-
able syntax by a compiler. The page takes longer to load as a result of
this. As a result, it will take longer for our site to be ready for launch.
On the other side, browsers have built-in support for JavaScript. In
the same manner that they can translate HTML, they can do so with
this. In other words, we can read it without a compiler.
via the use of JavaScript. We’ve probably seen this on many social media
and video sharing websites as well as the likes of Google.com and YouTube.
Consider what occurs when we play a video on YouTube. After the website
loaded, we may begin playing the video. If we leave a comment while the
video is playing, it will appear in the comments box once we scroll down
and post.
We covered what is JS, advantages and disadvantages, and the evolution
of JS in this chapter. Furthermore, we discussed what frameworks are and
how they differ from Vanilla JS.
NOTES
1 JavaScript – Overview: www.tutorialspoint.com/javascript/javascript_
overview.htm Accessed on: 20 September 2022.
2 What Is JavaScript? A Basic Introduction to JS for Beginners: www.
hostinger.in/tutorials/what-is-javascript Accessed on: 20 September 2022.
3 What Is Modern JavaScript and How to Use It?: www.altamira.ai/blog/what-
is-modern-javascript-and-how-to-use-it/#:~:text=Since%20JavaScript%20
does%20not%20have,via%20an%20tag. Accessed on: 21 September 2022.
4 History and Evolution of JavaScript: https://exploringjs.com/impatient-js/
ch_history.html Accessed on: 22 September 2022.
5 The History of JavaScript: Everything You Need to Know: www.spring-
board.com/blog/data-science/history-of-javascript/ Accessed on: 20
September 2022.
6 Who Owns JavaScript?: https://iq.opengenus.org/who-owns-javascript/
Accessed on: 20 September 2022.
7 Tech 101: What Is a JavaScript Framework? Here’s Everything You Need
to Know: https://skillcrush.com/blog/what-is-a-javascript-framework/
Accessed on: 20 September 2022.
8 What Is a JavaScript Framework?: https://generalassemb.ly/blog/what-is-a-
javascript-framework/ Accessed on: 20 September 2022.
9 What Are the Pros and Cons of JavaScript Frameworks?: www.geeks-
forgeeks.org/what-are-the-pros-and-cons-of-javascript-frameworks/
Accessed on: 21 September 2022.
10 Vanilla JS vs React JS: What to Choose for Your Development?: https://tag-
lineinfotech.com/react-js-vs-vanilla-js/ Accessed on: 21 September 2022.
11 5 Reasons Why You Need JavaScript in Your Website: https://vestrainet.
com/5-reasons-why-you-need-javascript-in-your-website.html Accessed
on: 22 September 2022.
Chapter 2
Getting Started
with JavaScript I
IN THIS CHAPTER
DOI: 10.1201/9781003356578-2 37
38 ◾ Conquering JavaScript
IDE Definition
IDE is an abbreviation for Integrated Development Environment. An IDE
is just an editor with a variety of handy programming tools. An IDE is a
specialist tool for software development as opposed to a simple text editor.
What exactly is the package that comes with an IDE? This may vary, but
some common additions are as follows:
• A debugger, compiler, and source code analyzer are all included.
• Highlighting syntax.
• Project scaffolding functionality based on pre-defined templates.
• Connection to the compiler and build tools.
• Auto-complete features that are advanced.
• Database connection wizards and assistance.
• GUI development functionality / Rapid Application Development.
Getting Started with JavaScript I ◾ 39
1. Atom
Before delving into Atom’s features, it’s important to first grasp
what Electron is. Electron is a JavaScript-based framework for creat-
ing cross-platform desktop programs. In a word, the electron is the
foundation of the atom.
Atom is one of the most popular JavaScript source code edi-
tors. Atom is completely free. The editor is available for a variety of
40 ◾ Conquering JavaScript
Pros:
• Git integration.
• Cross-platform compatibility.
• Support for multiple cursors.
Cons:
• It is sometimes unstable.
• Code execution failure.
• Slower than other top editors.
Pros:
• Memory use is minimal.
• Integration with the console.
• Task organization.
• Marketplace provides a large selection of extensions for extend-
ing functionality.
• WSL incorporation (Windows Subsystem for Linux).
Cons:
• Lag at times.
• Some widely used programming languages are not supported.
• Inadequate source control.
3. The eclipse
Eclipse is a well-known Java IDE. However, full-stack engineers
often utilize Eclipse for JavaScript development. However, for JS, we
must install certain more plugins. Of course, the flexible plugin sys-
tem facilitates use. A unified development environment promotes
peak performance. Along with speed, developers may expect reli-
ability and resilience. When we set up the Oomph Project, we can
also automate and replicate similar workspaces.
Eclipse’s highlight is the precise performance of JavaScript
Development Tools.
A new Docker UI aids in the creation of Docker images and con-
tainers using the Docker CLI.
42 ◾ Conquering JavaScript
Pros:
• Effective project management.
• Advanced troubleshooting.
• Excellent auto-complete.
Cons:
• To take effect, most modifications need a reboot.
• For beginners, it is difficult.
• Poor customer service.
4. Sublime Text
Sublime Text is another free and open-source JS editor. It’s cross-
platform, which means there’s plenty of space for customization.
There is no clutter on the UI.
As a result, the editor is more user-friendly. Some of its out-
standing features include a significant performance gain and
enhanced pane management. Other functions include Go to
Symbol and Go to Definition. We may also get packages like
SideBar Enhancements for copying, pasting, moving, and renam-
ing. Getting things set up might take some time at first. However,
once installed, Sublime Text will give a seamless experience.
Also, if we want to use Sublime Text, here are some plugins that
need to install: DocBlockr, SideBar Enhancements, JsFormat, and
SublimeLinter, which are all available.
The greatest thing is that you may check out all of the features
for free.
This JS editor also provides a trial version so that developers may
see how it works.
After the trial time expires, we must pay $80 for three years of use
to have access to all features.
Getting Started with JavaScript I ◾ 43
Pros:
• Editing mode with no distractions.
• Working on many projects is simple.
• Help with automation.
Cons:
• Awful library stack.
• Debugging is lacking.
• There is no default printing.
5. Brackets
Adobe developed the open-source coding editor Brackets. This
lightweight and quick JS editor includes JavaScript functional-
ity. Brackets are compatible with Mac, Windows, and Linux. Some
important capabilities are function searching and rapid project
switching. Users may utilize these tools to search for various project
files while typing in real time.
The Extract functionality turns PSD data into CSS. Live Preview is
one of the finest features of Brackets. We can observe how any changes to
the code are affecting the code in real time. The functionality is similar
to Adobe Dreamweaver. We may additionally improve the editor’s capa-
bilities by adding plugins. Some of these features include an autoprefixer,
code folding, a Markdown preview, smart highlighting, and snippets.
Pros:
• A straightforward user interface.
• Minimization of code.
• Browser preview in real time.
Cons:
• Long launch time.
• Project management is difficult.
• When dealing with huge files, performance suffers.
44 ◾ Conquering JavaScript
6. NetBeans
NetBeans is a multiplatform IDE for developing JavaScript
applications.
The nicest thing is that the time between installing NetBeans and
using it is less than with other editors. NetBeans has features like as
syntactic and semantic code highlighting, smart code completion,
and Subversion. Mercurial and built-in Git support is also available.
Here’s another useful feature for us!
NetBeans’ workspace may be easily customized.
Aside from that, we may simply drag and rearrange tabs in the
app frame.
And, as we all know, each developer has a unique development style.
We may edit the toolbar buttons in NetBeans to suit our needs
and preferences.
And do we know what else is useful?
Users may develop their own keyboard shortcuts!
Pros:
• Effective for automation.
• Excellent refactoring.
• Excellent service management.
Cons:
• More system resources are used.
• Support for integration is inadequate.
• Pop-ups are annoying.
7. Vim
We couldn’t say goodbye without acknowledging the legendary
Vim. Vim stands for VI Upgraded, and it is an improved version of
an older free text editor called vi, which was first designed for the
Unix system. Even though vim has long been associated with Linux
and the Unix community, it is now available for Windows.
Vim is perhaps the most basic of the editors on our list. Though
a graphical interface is available with vim, it is often a text-based
editor. This editor has a somewhat high learning curve. However, if
Getting Started with JavaScript I ◾ 45
we’ve overcome the first learning curve and become skilled with it,
vim may help us attain great levels of productivity, especially when
we consider its extensive ecosystem of plugins.
Pros:
• Lightweight and efficient.
• Cross-platform.
• Very adaptable.
• Plugin ecosystem to increase functionality.
Cons:
• The learning curve is steep.
• Flexibility.
• Help with integration.
• Excellent project management.
• Performance.
• Advanced troubleshooting.
However, when it comes to JS editors, Visual Studio Code is the clear win-
ner, regardless of our individual preferences.
Experienced programmers like ourselves have no other choice than
to use Visual Studio Code. The editor allows for quick and simple code
and file management and searching. Furthermore, we have shortcuts to
46 ◾ Conquering JavaScript
quickly access any icon or operation. We can type codes and navigate
between folders without putting down the keyboard.
If we’re just starting out in the world of computer programming, VS
Code’s capabilities will be a huge help. We had no trouble picking up the
keyboard shortcuts or any of the other features. Plus, the integrated com-
mand line interface is a great help to those who work with Angular or
Node. If you have Node.js installed, you can also use VS Code to debug
our code. Plus, we needn’t fret about getting help with VS Code since it’s
built by Microsoft. All of the features and how to’s are well documented
and shown in a plethora of written and video materials.
Installation of VScode
48 ◾ Conquering JavaScript
Accept Agreement
The following box that appears will allow us to pick more tasks. Select
all of the settings we need and then press the Next button:
Task Selections
50 ◾ Conquering JavaScript
When we click the Next button, the Ready to Install box appears, and
we must click the Install button:
Installation Box
Begin of Installation
Getting Started with JavaScript I ◾ 51
Once the setup is finished, click the Finish button to start Visual Studio
Code.
Setup Done
Setup of Editor
52 ◾ Conquering JavaScript
Search for the extension we wish to install after clicking the extension’s icon.
Search of Extensions
Install the LiveServer addon, which is quite handy due to its automated
live-reload capability.
We don’t need to save our file since it will save and display the result on
our browser every time we alter our code.
Search for the Live Server in the extension tab and click on the button
shown below:
Getting Started with JavaScript I ◾ 53
LiveServer Extensions
When we click on the Live Server, the install option will appear on the
right-hand side.
To install Live Server, click the install button.
Our Live Server will be installed when we click the install button:
54 ◾ Conquering JavaScript
Next, import Microsoft’s GPG key using the wget command to obtain the
repository:
Use the next command to install Visual Studio Code and update the sys-
tem after we’ve enabled the repository:
Downloading NodeJs
• Custom Configuration
“Next” should be selected.
NOTE:
“This step needs administrator rights,” a prompt will appear.
Authenticate as a “Administrator” to the prompt.
• Node.js installation
Do not close or cancel the installer until it has finished installing.
• Finish the Node.js Setup Wizard.
Click the “Finish” button.
60 ◾ Conquering JavaScript
C:\Users\Admin> node –v
If node.js was fully installed on our machine, the command prompt will
display the version of node.js that was installed.
Step 4: Update the Local npm version.
The last step in installing Node.js is to update our local npm version
(if necessary)—the package manager that comes with Node.js.
To fast update the npm, use the following command.
npm install npm –global // Updates ‘CLI’ client
NOTE:
We do not need to modify the system variables since the Windows
installer handles them automatically when installing using the.msi
installer.
If we use another format to install node.js on our PC, the system variable
path for node.js should be as follows:
PATH : C:\Users\[user-name]\AppData\Roaming\npm
C:\Program Files\nodejs (Path to nodejs folder)
Getting Started with JavaScript I ◾ 61
Step 3: Once installed, use the following command to check the installed
version:
Step 5: Once installed, use the following command to check the installed
version:
mkdir demo
cd demo
code .
Step 4: In the package.json file, add these two instructions that are required
for launching and dynamically executing the code once changes are made
in our Node.js app.
"start": "node app.js",
"dev": "nodemon app.js"
package.json File Configuration:
{
"name": "demo",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" &&
exit 1",
"start": "node app.js",
"dev": "nodemon app.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"nodemon": "^2.0.12"
}
}
• app.js
• package-lock.json
• package.json
// Require module
const express = require('express');
64 ◾ Conquering JavaScript
// Port-Number
const PORT = process.env.PORT ||5000;
// Server-Setup
app.listen(PORT,console.log(
`Server started on the port ${PORT}`));
Simply search for “VS Code code snippets” + our framework to locate a
collection that works for us.
Download from: https://marketplace.visualstudio.com/items?item
Name=xabikos.JavaScriptSnippets
ESLint
There is no doubt that ESList is one of the most widely used and beloved
add-ons in the JS community. The extension applies ESLint rules to our
code and displays the results in the editor. It enables us to find and rapidly
correct rule inconsistencies. It’s a must-have for all JS developers since it
boosts productivity and code quality.
Download from: https://marketplace.visualstudio.com/items?item
Name=dbaeumer.vscode-eslint
Prettier
With VS Code, Visual Studio, Atom, Vim, Sublime Text, and a number of
other programs, Prettier is an opinionated code formatter.
66 ◾ Conquering JavaScript
This useful little addon ensures that our scripts are uniformly
s tructured and indented, and it displays colored keywords for more
readable code.
It decreases formatting time and hence enhances productivity. It con-
tributes to great code readability.
Download from: https://marketplace.visualstudio.com/items?item
Name=esbenp.prettier-vscode
Quokka.js
Quokka.js allows us to quickly prototype JavaScript in our VS Code edi-
tor. It is a live JavaScript and TypeScript playground.
It is often referred to be the modern-day scratchpad for JS developers.
Have we ever wanted to test something quickly and found yourself in our
browser’s console, running some JS? Or do we launch the node process
and test it there? The major goal of this addon is to execute code quickly
and easily directly in our VS Code editor.
Download from: https://marketplace.visualstudio.com/items?item
Name=WallabyJs.quokka-vscode
REST Client
REST Client is a Visual Studio Code addon that lets us submit an HTTP
request and examine the result right in the editor. It’s Postman for VS
Code, with the added benefit of being incorporated inside the code editor.
REST Client is compatible with both REST and GraphQL APIs. It
is one of the greatest vscode extensions for API developers in terms of
productivity.
Download from: https://marketplace.visualstudio.com/items?item
Name=humao.rest-client
Live Server
We may use Live Server to launch a local development server with a live-
reload option for static and dynamic sites. This may not be very useful
for individuals working with frameworks that already have live-reload
enabled, such as React, but it is a lifesaver if we are working with other
web pages or static material.
Download from: https://marketplace.visualstudio.com/items?item
Name=ritwickdey.LiveServer
Live Share
This one is fantastic, and we’re not sure whether anything similar exists
for WebStorm, but it enables us to share our code editor with others.
It’s ideal for pair programming, particularly as working from home
becomes more popular.
Download from: https://marketplace.visualstudio.com/items?item
Name=MS-vsliveshare.vsliveshare
JavaScript Booster
One of our preferred WebStorm features is now accessible in VS Code.
By evaluating our code and its context, JavaScript booster automatically
proposes short methods to restructure or improve our code.
It supports a wide range of code activities, including refactoring condi-
tions, declarations, functions, typescript, promises, JSX, and many more.
Download from: https://marketplace.visualstudio.com/items?item
Name=sburg.vscode-javascript-booster
Tabnine
Another issue that arises while switching from Webstorm to VS Code is
the quality of auto-completions.
Code completion works great in VS Code, but it lags well below what
Webstorm or PyCharm can offer.
However, owing to the Tabnine, VS Code receives a significant
increase.
Tabnine use artificial intelligence to provide cutting-edge recommen-
dations and it has far surpassed my expectations.
It is such a great tool that we use it for VS Code as well as the whole
JetBrains product suite.
Let us look at some of their characteristics:
• Google
• Facebook
• Yahoo
• Wikipedia
• YouTube
• Twitter
• Apple
• Amazon
• LinkedIn
• MSN
• Windows Live
• eBay
• Microsoft
• Tumblr
• Pinterest
• Netflix
72 ◾ Conquering JavaScript
• PayPal
• Reddit
• Stack Overflow
Most people may also find it difficult to accept that the number of websites
that use vanilla JavaScript is much more than the number of websites that
utilize JQuery.
Website Performance
Because it is the most costly and critical portion of the frontend stack,
this is far better for web performance than many other frameworks
and tools. Unlike HTML and CSS files, which are only accessible when
downloaded, vanilla js code must be built and processed. A 50kb js file
has a considerably greater influence on web speed than the same size
HTML and CSS files.
User Interface
It offers a simple yet user-friendly development experience. A developer
may begin building an application or website using JavaScript by simply
opening a text editor. There is no need for the developer to undertake
time-consuming tasks such as npm install, compilation processes, and no
build, among others.
• console.log()
• alert()
• document.write()
1. Using console.log()
The console.log() function is used to debug the code.
Code:
2. Using alert()
The alert() function displays an alert box with the supplied message
over the current window.
Code:
3. Using document.write()
When we wish to print information to an HTML document, we use
document.write().
SYNTAX OF JAVASCRIPT
JavaScript may be applied by placing JavaScript statements inside <script>...
</script> HTML tags on a web page.
Getting Started with JavaScript I ◾ 75
<html>
<body>
76 ◾ Conquering JavaScript
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.
• Single-line comment
• Multiline comment
<script>
// It is the singleline comment
78 ◾ Conquering JavaScript
document.write("hello everyone");
</script>
<script>
var c=30;
var d=10;
var e=c+d;//It adds values of c and d variable
document.write(e);//prints sum of 30 and 10
</script>
/* code here */
<script>
/* It is the multiline comment.
It will not display */
document.write("instance of javascript multiline
comment");
</script>
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.
var d = 20;
var _value="sonoo";
var 321=20;
var *bb=310;
<script>
var c = 30;
var d = 10;
var e=c+d;
document.write(e);
</script>
<script>
function cde(){
var k=10;//local variable
}
</script>
OR
<script>
If(20<15){
var y=40;// local variable
80 ◾ Conquering JavaScript
}
</script>
It may now be defined within any function and accessed from any func-
tion. 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
}
var value=60;
function a(){
alert(window.value);//access global variable
}
OPERATORS IN JAVASCRIPT
Operators in JavaScript are symbols that are employed to perform actions
on operands. As an example14:
var sum=30+10;
• 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.
Comparison Operators
The comparison operator in JavaScript compares the two operands.
The following are the comparison operators:
Getting Started with JavaScript I ◾ 83
Bitwise Operators
Bitwise operators apply bitwise operations to operands. The following are
the bitwise operators:
Logical Operators
JavaScript logical operators include the basic operators.
Assignment Operators
JavaScript assignment operators include the following operators.
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 Statement
• If else statement
• If else if statement
If Statement
It only analyses the content if the expression is true. The JavaScript if state-
ment’s signature is shown below.
if(expression){
//content to evaluate
}
Getting Started with JavaScript I ◾ 85
Flowchart:
start
false
Cond
ition
if code
after if
exit
Statement of if
Let’s look at a basic if statement in JavaScript.
<script>
var a=40;
if(a>20){
document.write(“The value of a is greater than 20”);
}
</script>
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
false
Cond
ition
else code
true
if code
after if
exit
Statement of if-else
<script>
var d=40;
if(d%2==0){
document.write(“d is even number”);
}
else{
document.write(“d is odd number”);
}
</script>
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
Flowchart:
start
false
Condition 1
false
Condition 2
false
Condition n
true
true
true
next statement
Statement of if-else-if
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;
}
<script>
var grade=’B’;
var result;
switch(grade){
Getting Started with JavaScript I ◾ 89
case ‘A’:
result=”Grade A”;
break;
case ‘B’:
result=”Grade B”;
break;
case ‘C’:
result=”Grade C”;
break;
default:
result=”No Grade”;
}
document.write(result);
</script>
Let’s look at how the switch statement works in JavaScript.
<script>
var grade=’B’;
var result;
switch(grade){
case ‘A’:
result+=”Grade A”;
case ‘B’:
result+=”Grade B”;
case ‘C’:
result+=”Grade C”;
default:
result+=” No Grade”;
}
document.write(result);
</script>
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.
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
}
x++;
}
</script>
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);
for-in loop
The JavaScript for-in loop is used to iterate through an object’s attributes.
It consists of three crucial components:
<html>
<body>
<script type = “text/javascript”>
<!--
var count;
document.write(“Start Loop” + “<br />”);
FUNCTIONS IN JAVASCRIPT
JavaScript functions are used to do out tasks. To reuse the code, we may
call the JavaScript method many times.
<script>
function msg(){
alert(“hey this is my message”);
}
</script>
<input type=”button” onclick=”msg()” value=”call
function”/>
Function Arguments
Functions may be called by giving parameters. Let’s look at an example of
a function with just one parameter.
<script>
function getcube(numb){
alert(number*numb*numb);
}
</script>
<form>
<input type=”button” value=”click”
onclick=”getcube(4)”/>
</form>
<script>
94 ◾ Conquering JavaScript
function getInfo(){
return “hey everyone How are you?”;
}
</script>
<script>
document.write(getInfo());
</script>
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 dynami-
cally but in an insecure manner.
Syntax:
Parameter
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.
<script>
Getting Started with JavaScript I ◾ 95
Example 2
Let’s look at an example to demonstrate the strength of offered value.
<script>
var pow=new Function(“numb1”,”numb2”,”return Math.
pow(numb1,numb2)”);
document.writeln(pow(21,4));
</script>
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 class-
based.22 We don’t construct a class to retrieve the object here. However, we
guide the creation of things.
• 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
object={property1:value_1,property2:value_2.....
propertyN:value_N}
<script>
emp={id:113,name:”Shiva Kishan”,salary:45000}
document.write(emp.id+” “+emp.name+” “+emp.salary);
</script>
<script>
var emp=new Object();
emp.id=107;
emp.name=”Rita Kaur”;
emp.salary=52000;
document.write(emp.id+” “+emp.name+” “+emp.salary);
</script>
<script>
function emp(id,name,salary){
this.id=id;
Getting Started with JavaScript I ◾ 97
this.name=name;
this.salary=salary;
}
e=new emp(105,”Vinay Sharma”,33000);
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
this.change_Salary=change_Salary;
function change_Salary(other_Salary){
this.salary=other_Salary;
}
}
e=new emp(102,”Suraj Garewal”,39000);
document.write(e.id+” “+e.name+” “+e.salary);
e.changeSalary(41000);
document.write(“<br>”+e.id+” “+e.name+” “+e.salary);
</script>
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 array literal
By explicitly generating an
Array instance (using new
keyword)
Array in JavaScript
<script>
var emp=[“Simran”,”Vijay”,”Rajat”];
for (x=0;x<emp.length;x++){
document.write(emp[x] + “<br/>”);
}
</script>
<script>
var x;
var emp = new Array();
emp[0] = “Ajay”;
emp[1] = “Vinay”;
emp[2] = “Johny”;
for (x=0;x<emp.length;x++){
document.write(emp[x] + “<br>”);
}
</script>
<script>
var emp=new Array(“Jaya”,”Vinay”,”Simran”);
for (x=0;x<emp.length;x++){
document.write(emp[x] + “<br>”);
}
</script>
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.
entries() It generates an iterator object and a loop that loops through each key/
value pair.
every() It checks if all of the items of an array fulfill the function criteria.
flat() It generates a new array with sub-array entries concatenated recursively
until the desired depth is reached.
flatMap() It uses a mapping function to map all array items, then flattens the result
into a new array.
fill() It populates an array with static values.
(Continued)
Getting Started with JavaScript I ◾ 101
Methods Description
from() It generates a new array containing an identical duplicate of another
array element.
filter() It returns a new array containing the entries that satisfy the function’s
requirements.
find() It returns the value of the first array element that meets the provided
criterion.
findIndex() It returns the index of the first member in the provided array that meets
the criterion.
forEach() It calls the specified method once for each array element.
includes() It determines whether the provided element is present in the provided
array.
indexOf() It searches the provided array for the specified element and provides the
index of the first match.
isArray() It determines whether the provided value is an array.
join() It creates a string by joining the members in an array.
keys() It constructs an iterator object that just includes the array keys, then
loops through these keys.
lastIndexOf() 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.
var string_name=”string_value”;
<script>
var str=”This is the string literal”;
document.write(str);
</script>
<script>
var stringname=new String(“hey everyone”);
document.write(stringname);
</script>
Getting Started with JavaScript I ◾ 103
Methods Description
<script>
var str=”heyeveryone”;
104 ◾ Conquering JavaScript
document.write(str.charAt(2));
</script>
<script>
var st1=”heyeveryone “;
var st2=”concat example”;
var st3=st1.concat(st2);
document.write(st3);
</script>
<script>
var st1=”hey from eveyrone indexof”;
var n=st1.indexOf(“from”);
document.write(n);
</script>
<script>
var st1=”everybody from eveyrone indexof”;
var n=st1.lastIndexOf(“every”);
document.write(n);
</script>
document.write(st2);
</script>
<script>
var st1=”abcdefgh”;
var st2=st1.slice(3,6);
document.write(st2);
</script>
<script>
var st1=” javascript trim “;
var st2=st1.trim();
document.write(st2);
</script>
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)
Methods Description
It generates an integer number, ranging from 1 to 31, which
getDate() represents the day for the specified date and time in local time.
getDay() It produces an integer number between 0 and 6 that reflects the
weekday based on local time.
getFullYears() It returns the integer number representing the year in local time.
getHours() It produces an integer number between 0 and 23 representing the
hours in local time.
getMilliseconds() It returns an integer number between 0 and 999 representing
milliseconds in local time.
getMinutes() It produces an integer number between 0 and 59 representing the
minutes in local time.
getMonth() It actually gives an integer value between 0 and 11 that, based on
local time, reflects the month.
getSeconds() It produces an integer number between 0 and 60 representing the
seconds in local time.
getUTCDate() It produces an integer number between 1 and 31 representing the
day for the given date in universal time.
getUTCDay() 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 Description
getUTCFullYears() 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
Let’s look at another code to print the date, month, and year.
<script>
var date=new Date();
var day=date.getDate();
var month=date.getMonth()+1;
var year=date.getFullYear();
document.write("<br>The Date is:
“+day+”/”+month+”/”+year);
</script>
function getTime(){
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add zero in the front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById(‘text’).
innerHTML=h+”:”+m+”:”+s;
setTimeout(function(){getTime()},1200);
}
//setInterval(“getTime()”,1000);//another way
function checkTime(i){
if (x<10){
x=”0” + x;
}
return x;
}
</script>
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 Description
abs() It gives the absolute value of the number provided.
acos() The arccosine of the provided integer in radians is returned.
asin() It computes the arcsine of the provided number in radians and returns it.
atan() It returns the arc-tangent in radians of the provided integer.
cbrt() It returns the cube root of the integer supplied.
ceil() The function returns the smallest integer greater than or equal to the given
parameter.
cos() It returns the cosine of the number provided.
cosh() 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 pro-
vided integer.
</script>
Math.random()
The math.random() function in JavaScript provides a random integer
between 0 and 1.
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
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.
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.
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.
document.getElementById(‘p6’).innerHTML=Math.
round(5.2);
document.getElementById(‘p7’).innerHTML=Math.
round(5.6);
</script>
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.
Constant Description
Methods Description
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() con-
structor, as seen below.
Boolean bn=new Boolean(value);
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 Description
toSource() The source of the Boolean object is returned as a string.
toString() converts a Boolean to a String.
valueOf() converts another type to a Boolean value.
a. Syntax errors.
b. Runtime errors.
c. Logical errors.
Getting Started with JavaScript I ◾ 115
syntax
errors,
Types
of Erros
logical runtime
errors. 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.
//-->
</script>
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 deter-
mined 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:
catch ( e ) {
// Code run if an exception occurs
[break;]
}
[ finally {
// Code that is always run regardless of
// whether or not an exception occurs
}]
//-->
</script>
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−
<html>
<head>
<script type = “text/javascript”>
<!--
function myFunc() {
var k = 120;
alert(“The Value of variable k is : “ +
k );
}
//-->
</script>
</head>
<body>
<p>Click following to see the result:</p>
<form>
<input type = “button” value = “Click Here”
onclick = “myFunc();” />
</form>
</body>
</html>
Let us now utilize try...catch to capture this error and provide a user-
friendly message.
If we wish to conceal this problem from a user, we may also suppress
this message.
118 ◾ Conquering JavaScript
<html>
<head>
</head>
<body>
<p>Click following to see the result:</p>
<form>
<input type = “button” value = “Click Here”
onclick = “myFunc();” />
</form>
</body>
</html>
Finally, we may use a block that will always run unconditionally after the
try/catch.
Here’s an illustration.
<html>
<head>
try {
alert(“The Value of variable k is :
“ + k );
}
catch ( e ) {
alert(«Error: “ + e.description );
}
finally {
alert(“Finally block will execute
always!” );
}
}
//-->
</script>
</head>
<body>
<p>Click following to see the result:</p>
<form>
<input type = “button” value = “Click Here”
onclick = “myFunc();” />
</form>
</body>
</html>
Example
The example below shows how to utilize a throw statement.
<html>
<head>
function myFunc() {
var j = 120;
var k = 0;
try {
if ( k == 0 ) {
throw( “Divide by zero error.” );
} else {
var m = j / k;
}
}
catch ( e ) {
alert(“Error: “ + e );
}
}
//-->
</script>
</head>
<body>
<p>Click following to see the result:</p>
<form>
<input type = “button” value = “Click Here”
onclick = “myFunc();” />
</form>
</body>
</html>
<html>
<head>
Getting Started with JavaScript I ◾ 121
</head>
<body>
<p>Click following to see the result:</p>
<form>
<input type = “button” value = “Click Here”
onclick = “myFunc();” />
</form>
</body>
</html>
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.
Example
<html>
<head>
</head>
<body>
<p>Click following to see the result:</p>
<form>
<input type = “button” value = “Click Here”
onclick = “myFunc();” />
</form>
</body>
</html>
EVENTS IN JAVASCRIPT
We will discuss events in JavaScript below:
Example
Consider the following example.
<html>
<head>
<script type = “text/javascript”>
<!--
function sayHey() {
alert(“Hey Everyone”)
}
//-->
</script>
</head>
<body>
<p>Click following button and see result</p>
<form>
<input type = “button” onclick = “sayHey()”
value = “Say Hey” />
</form>
</body>
</html>
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.
<html>
<head>
<script type = “text/javascript”>
<!--
function validation() {
here all validation goes
.........
return either true or false
}
//-->
</script>
</head>
<body>
<form method = “POST” action = “t.cgi” onsubmit
= “return validate()”>
.......
<input type = “submit” value = “Submit” />
</form>
</body>
</html>
<html>
<head>
<script type = “text/javascript”>
<!--
Getting Started with JavaScript I ◾ 125
function over() {
document.write (“Mouse-Over”);
}
function out() {
document.write (“Mouse-Out”);
}
//-->
</script>
</head>
<body>
<p>Bring our mouse inside division to see the
outcome:</p>
<div onmouseover = “over()” onmouseout =
“out()”>
<h2> This is inside division </h2>
</div>
</body>
</html>
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/install-
visual-studio-code-on-linux/ Accessed on: 23 September 2022.
4 Installation of Node.js on Windows: www.geeksforgeeks.org/installation-
of-node-js-on-windows/ Accessed on: 22 September 2022.
5 Installation of Node.js on Linux: www.geeksforgeeks.org/installation-of-
node-js-on-linux/?ref=lbp Accessed on: 22 September 2022.
6 How to Create and Run Node.js Project in VS code editor?: www.geeks-
forgeeks.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://live-
codestream.dev/post/best-vscode-extensions-for-javascript/ Accessed on:
22 September 2022.
8 What Is “Vanilla JavaScript”?: www.javatpoint.com/what-is-vanilla-javas-
cript 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
Getting Started
with JavaScript II
IN THIS CHAPTER
➢ Asynchronous Development
➢ DOM Manipulation
➢ HTTP and Forms
➢ Working with APIs
npm i async
Example 1
Write an asynchronous function in Node.js to compute the square
of an integer.
npm init -y
npm i async
function square(k) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(Math.pow(k, 2));
}, 2000);
});
}
output(10);
var async = require("async");
function square(k) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(Math.pow(k, 2));
}, 2000);
});
}
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);
});
}
output(10, 20);
134 ◾ Conquering JavaScript
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="message"></div>
<script>
var msg = document.getElementById("message");
function fd1() {
setTimeout(function () {
msg.innerHTML += "
<p>fd1 is start</p>
";
msg.innerHTML += "
<p>fd1 is end</p>
";
}, 100);
}
function fd2() {
msg.innerHTML += "
<p>fd2 is start</p>
";
fd1();
msg.innerHTML += "
<p>fd2 is end</p>
";
}
fd2();
</script>
Getting Started with JavaScript II ◾ 135
</body>
</html>
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.
Syntax
async function Function_Name(){
...
}
Example
Let’s recreate the same example using the Asynchronous function.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
136 ◾ Conquering JavaScript
<title></title>
</head>
<body>
<div id="message"></div>
<script>
var msg = document.getElementById("message");
function fd1() {
return new Promise(function (resolve,
reject) {
setTimeout(function () {
msg.innerHTML += "
<p>fd1 is start</p>
";
msg.innerHTML += "
<p>fd1 is end</p>
";
resolve();
}, 100);
})
}
fd2();
</script>
</body>
</html>
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).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="message"></div>
<script>
var msg = document.getElementById("message");
function fd1() {
return new Promise(function (resolve,
reject) {
setTimeout(function () {
msg.innerHTML += "
<p>fd1 is start</p>
";
msg.innerHTML += "
<p>fd1 is end</p>
";
resolve(1);
}, 100);
})
}
138 ◾ Conquering JavaScript
fd2();
</script>
</body>
</html>
Example
We may write numerous await statements in a row.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="message"></div>
<script>
var msg = document.getElementById("message");
function fd1() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
Getting Started with JavaScript II ◾ 139
msg.innerHTML += "
<p>fd1 is start</p>
";
msg.innerHTML += "
<p>fd1 is end</p>
";
resolve();
}, 1000);
})
}
function fd3() {
return new Promise(function (resolve,
reject) {
setTimeout(function () {
msg.innerHTML += "
<p>fd3 is start</p>
";
msg.innerHTML += "
<p>fd3 is end</p>
";
resolve();
}, 1000);
})
}
fd2();
</script>
</body>
</html>
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);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="message"></div>
<script>
var msg = document.getElementById("message");
function fd1() {
return new Promise(function (resolve,
reject) {
setTimeout(function () {
msg.innerHTML += "
<p>fd1 is start</p>
";
msg.innerHTML += "
<p>fd1 is end</p>
";
resolve();
}, 1000);
})
}
function fd3() {
return new Promise(function (resolve,
reject) {
setTimeout(function () {
msg.innerHTML += "
<p>fd3 is start</p>
";
msg.innerHTML += "
<p>fd3 is end</p>
Getting Started with JavaScript II ◾ 141
";
resolve();
}, 1000);
})
}
fd2();
</script>
</body>
</html>
Example
<script>
document.write("Hey"); // First
document.write("<br>");
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 synchro-
nous code prevents continued execution of remaining code until the cur-
rent 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.
<script>
document.write("Hey"); // First
document.write("<br>");
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.
<script>
document.write("Hey");
document.write("<br>");
Getting Started with JavaScript II ◾ 143
setTimeout(() => {
document.write("Let's wait and see what
occurs");
}, 1000);
document.write("<br>");
document.write("End");
document.write("<br>");
</script>
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 setTime-
out 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.
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 pro-
cessing and to only run the script file once the HTML page has been com-
pletely 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 Deferred
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.
text
textarea
anchor
checkbox
document form
radio
link
select option
reset
button
Method Description
Let’s look at a basic example of a document object that displays the user’s
name along with a welcome message.
<script type=”text/javascript”>
function printvalue(){
var name=document.form11.name.value;
alert(“Welcome here: “+name);
}
</script>
<form name=”form11”>
Enter Name:<input type=”text” name=”name”/>
<input type=”button” onclick=”printvalue()”
value=”print name”/>
</form>
Getting Started with JavaScript II ◾ 147
<script type=”text/javascript”>
function getcube(){
var numb=document.getElementById(“numb”).value;
alert(numb*numb*numb);
}
</script>
<form>
Enter No:<input type=”text” id=”numb”
name=”numb”/><br/>
<input type=”button” value=”cube”
onclick=”getcube()”/>
</form>
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’);
Example
It is a basic class implementation that, when the variable k is invoked,
produces an array-like object.
<html>
<head> <h5>The DOM Methods </h5> </head>
<body>
<div class=”Class”>
This is a basic class implementation
</div>
<script type=”text/javascript”>
var k=document.getElementsByClassName(‘Class’);
document.write(“On calling k, it will return arrsy-
like object: <br>”+k);
</script>
</body>
</html>
METHOD DOCUMENT.GETELEMENTSBYNAME()
IN JAVASCRIPT
The function document.getElementsByName() retrieves all elements
with the given name.8 The following is the syntax for the getElements-
ByName() 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.
<script type=”text/javascript”>
function totalelements()
{
var allgenders=document.getElementsByName(“gender”);
alert(“Total Genders is:”+allgenders.length);
}
</script>
<form>
Male:<input type=”radio” name=”gender”
value=”male”>
Female:<input type=”radio” name=”gender”
value=”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.
<script type=”text/javascript”>
function countpara(){
var totalpara=document.getElementsByTagName(“p”);
alert(“The total p tags are: “+totalpara.length);
}
</script>
<p>This is the pragraph</p>
<p>We are going to count the total number of
paragraphs by getElementByTagName() method.</p>
<p> Let’s look at a basic example</p>
<button onclick=”countpara()”>count paragraph</
button>
Another Example
In this instance, we’ll count the total number of h2 and h3 tags in
the document.
<script type=”text/javascript”>
function counth2(){
var totalh2=document.getElementsByTagName(“h2”);
alert(“The total h2 tags are: “+totalh2.length);
}
function counth3(){
var totalh3=document.getElementsByTagName(“h3”);
alert(“The total h3 tags are: “+totalh3.length);
}
</script>
<h2>This is the h2 tag</h2>
<h2>This is the h2 tag</h2>
<h3>This is the h3 tag</h3>
<h3>This is the h3 tag</h3>
Getting Started with JavaScript II ◾ 151
</script>
<form name=”my_Form”>
<input type=”password” value=”” name=”userPass”
onkeyup=”validate()”>
Strength:<span id=”mylocation”>no strength</span>
</form>
• 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 com-
ponent 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 scenar-
ios 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
• 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 han-
dlers 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.
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 asyn-
chronous HTTP requests.
Disadvantages of XMLHttpRequest
Fetch
Fetch is a contemporary and streamlined native JavaScript API for mak-
ing 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))
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
Disadvantages of Fetch
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 inter-
cepting 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 cov-
ers 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
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)
}
}
}
Advantages Axios
Disadvantages Axios
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 callback-
based solutions are supported by the package.
When sending HTTP requests using SuperAgent, we may use its spe-
cialized methods to launch a certain sort of request. As seen in this exam-
ple, 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)
}
})
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
Disadvantages of SuperAgent
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
Advantages of Ky
Disadvantages of Ky
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 nec-
essary 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 trans-
mits cookies with the response, which are saved to the system’s local stor-
age. 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:
• Session Management:
The cookie’s principal function is to handle user logins, shop-
ping 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 con-
tinues 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 behav-
iors 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 sen-
sitive information, the user should be aware of the hazards of access-
ing 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 cen-
tral database to personalize things for users the first time they log in.
When the user signs in or restarts the program, the user customiza-
tion 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.
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 Set-
Cookie 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 docu-
ment.cookie property.
The syntax for creating a cookie is as follows:
document.cookie=”cookiename=value”;
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.
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8”>
<meta name=”viewport” content=”width=device-width,
initial-scale=2.0”>
<meta http-equiv=”X-UA-compatible” content
=”ie=edge”>
<title>Document</title>
</head>
<body>
<button id =’setcookie’>Set Cookie</button>
<script>
168 ◾ Conquering JavaScript
It will display a button component on our website page based on the pre-
ceding example. When we press the button, the requested cookie is cre-
ated 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 follow-
ing 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”
• 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.
• 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 trans-
mit 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 prop-
erty 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
• 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 prop-
erty 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 cook-
ies 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 exam-
ple 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 advertise-
ments 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 creden-
tials 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 exam-
ple 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 dif-
ficult 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 con-
tain 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 click-
ing on a malicious link that exploits cross-site scripting vulnerabilities.
172 ◾ Conquering JavaScript
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 activi-
ties and obtain personal information. Few states have prohibited the zom-
bie cookie, which is considered an illegal violation of privacy.
FORM IN JAVASCRIPT
We will learn, examine, and understand the JavaScript form in this ses-
sion. We will also learn how the JavaScript form is implemented for vari-
ous 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:
<html>
<head>
<title> Form of Login </title>
</head>
<body>
<h3> LOGIN </h3>
<formform =”Loginform” onsubmit=”submitform()”>
<h4> USERNAME</h4>
<input type=”text” placeholder=”Enter email id”/>
<h4> PASSWORD</h4>
<input type=”password” placeholder=”Enter
password”/></br></br>
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 prop-
erties 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.
Referencing Forms
Now that we’ve established the form element with HTML, we need to con-
nect it to JavaScript. To do this, we employ the getElementById () func-
tion, which refers to the HTML form element in the JavaScript code.
The following is the syntax for utilizing the getElementById() method:
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 com-
plete 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
<html>
<head>
<title> Form of Login </title>
</head>
<body>
<h3> LOGIN </h3>
<formform =”Loginform” onsubmit=”submitform()”>
<h4> USERNAME</h4>
<input type=”text” placeholder=”Enter email id”/>
<h4> PASSWORD</h4>
<input type=”password” placeholder=”Enter
password”/></br></br>
<input type=”submit” value=”Login”/>
<input type=”button” value=”SignUp”
onClick=”create()”/>
</form>
<script type=”text/javascript”>
function submitform(){
Getting Started with JavaScript II ◾ 175
SignUp Form
<html>
<head>
<title> SignUp Page</title>
</head>
<body align=”center” >
<h1> CREATE ACCOUNT</h1>
<table cellspacing=”2” align=”center” cellpadding=”9”
border=”0”>
<tr><td> Name</td>
<td><input type=”text” placeholder=”Enter name”
id=”n1”></td></tr>
<tr><td>Email </td>
<td><input type=”text” placeholder=”Enter email id”
id=”e1”></td></tr>
<tr><td> Set Password</td>
<td><input type=”password” placeholder=”Set password”
id=”p1”></td></tr>
<tr><td>Confirm Password</td>
<td><input type=”password” placeholder=”Confirm
password” id=”p2”></td></tr>
<tr><td>
<input type=”submit” value=”Create”
onClick=”createaccount()”/>
</table>
<script type=”text/javascript”>
function create_account(){
var n=document.getElementById(“n1”).value;
var e=document.getElementById(“e1”).value;
var p=document.getElementById(“p1”).value;
var cp=document.getElementById(“p2”).value;
176 ◾ Conquering JavaScript
<script>
function validateform(){
var name=document.my_form.name.value;
var password=document.my_form.password.value;
if (name==null || name==””){
alert(“Name cannot be blank”);
return false;
}else if(password.length<7){
alert(“Password must be atleast 7 characters
long.”);
return false;
}
}
</script>
<body>
<form name=”my_form” method=”post” action=”abcd.
jsp” onsubmit=”return validateform()” >
Name: <input type=”text” name=”name”><br/>
Password: <input type=”password”
name=”password”><br/>
<input type=”submit” value=”register”>
</form>
178 ◾ Conquering JavaScript
<script type=”text/javascript”>
function matchpass(){
var firstpassword=document.fm1.password.value;
var secondpassword=document.fm1.password2.value;
if(firstpassword==secondpassword){
return true;
}
else{
alert(“password must same!”);
return false;
}
}
</script>
<script>
function validate(){
var num=document.my_form.num.value;
if (isNaN(num)){
document.getElementById(“numloc”).
innerHTML=”Enter Numeric value only”;
return false;
}else{
return true;
}
}
Getting Started with JavaScript II ◾ 179
</script>
<form name=”my_form” onsubmit=”return validate()” >
Number: <input type=”text” name=”num”><span
id=”numloc”></span><br/>
<input type=”submit” value=”submit”>
</form>
<script>
function validate(){
var name=document.fm1.name.value;
var password=document.fm1.password.value;
var status=false;
if(name.length<1){
document.getElementById(“nameloc”).innerHTML=
“ <img src=’checked.gif’/> Please enter name”;
status=false;
}else{
document.getElementById(“nameloc”).innerHTML=”
<img src=’unchecked.gif’/>”;
status=true;
}
if(password.length<7){
document.getElementById(“passwordloc”).innerHTML=
“ <img src=’checked.gif’/> Password must be at
least 7 char long”;
status=false;
}else{
document.getElementById(“passwordloc”).innerHTML=”
<img src=’checked.gif’/>”;
}
return status;
}
</script>
180 ◾ Conquering JavaScript
<script>
function validateemail()
{
var x=document.my_form.email.value;
var atposition=x.indexOf(“@”);
var dotposition=x.lastIndexOf(“.”);
if (atposition<1 || dotposition<atposition+2 ||
dotposition+2>=x.length){
alert(“Enter the valid email address \n
atpostion:”+atposition+”\n dotposition:”+dotposition);
return false;
}
}
</script>
<body>
Getting Started with JavaScript II ◾ 181
{
“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.
<html lang=”en”>
<head>
<meta charset=”UTF-8” />
<meta name=”viewport” content=
“width=device-width, initial-scale=2.0” />
padding: 32px;
margin: 0px auto;
}
.details {
margin-left: auto;
margin-right: auto;
}
img {
border-radius: 6px;
box-shadow: black;
}
table,
td {
border-collapse: collapse;
margin-left: auto;
margin-right: auto;
text-align: center;
padding: 12px;
border: 2px solid black;
}
</style>
</head>
<body>
<div class=”content”>
<div class=”head”>
<h1 id=”head”></h1>
</div>
<div class=”email”>
<i class=”fa fa-envelope” style=
“font-size: 16px; color: red;”>
<a href=”” id=”email”> </a>
</div>
<div class=”phone”>
<i class=”fa fa-phone” style=
“font-size: 16px; color: red;”>
<a href=”” id=”phone”> </a>
</div>
<br />
Getting Started with JavaScript II ◾ 185
<div id=”user-img”></div>
<br />
<div class=”details”>
<table>
<tr>
<td>Age</td>
<td><span id=”age”></span></td>
</tr>
<tr>
<td>Gender</td>
<td><span id=”gender”></span></td>
</tr>
<tr>
<td>Location</td>
<td><span id=”location”></span></td>
</tr>
<tr>
<td>Country</td>
<td><span id=”country”></span></td>
</tr>
</table>
</div>
</div>
</body>
</html>
The script tag will have the code for making the API request and handling
the response.
This should be included in the body tag or as a separate file.
We utilize the async/await method to ensure that data is presented even
after the page has been loaded.
We may use the console.log(...) function to see if the user is obtaining
the proper information.
To see the output, open the console window in our internet browser
(Right Click -> Inspect -> Console or Ctrl+Shift+J in Chrome/Edge).
<script>
const api_url = “https://randomuser.me/api/”;
async function getUser() {
186 ◾ Conquering JavaScript
document.querySelector(“#location”).textContent
= city + “, “ + state;
document.querySelector(“#country”).textContent
= country;
Getting Started with JavaScript II ◾ 187
The final code is: It is the result of combining the preceding code parts.
<html lang=”en”>
<head>
<meta charset=”UTF-8” />
<meta name=”viewport” content=
“width=device-width, initial-scale=2.0” />
.details {
margin-left: auto;
188 ◾ Conquering JavaScript
margin-right: auto;
}
img {
border-radius: 6px;
box-shadow: black;
}
table,
td {
border-collapse: collapse;
margin-left: auto;
margin-right: auto;
text-align: center;
padding: 12px;
border: 2px solid black;
}
</style>
</head>
<body>
<div class=”content”>
<div class=”head”>
<h1 id=”head”></h1>
</div>
<div class=”email”>
<i class=”fa fa-envelope” style=
“font-size: 16px; color: red;”>
<a href=”” id=”email”> </a>
</div>
<div class=”phone”>
<i class=”fa fa-phone” style=
“font-size: 16px; color: red;”>
<a href=”” id=”phone”> </a>
</div>
<br />
<div id=”user-img”></div>
<br />
<div class=”details”>
<table>
Getting Started with JavaScript II ◾ 189
<tr>
<td>Age:</td>
<td><span id=”age”></span></td>
</tr>
<tr>
<td>Gender:</td>
<td><span id=”gender”></span></td>
</tr>
<tr>
<td>Location:</td>
<td><span id=”location”></span></td>
</tr>
<tr>
<td>Country:</td>
<td><span id=”country”></span></td>
</tr>
</table>
</div>
</div>
</body>
<script>
const api_url = “https://randomuser.me/api/”;
document.querySelector(“#location”).textContent
= city + “, “ + state;
document.querySelector(“#country”).textContent =
country;
</script>
</html>
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.
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 eas-
ier. According to W3Techs, jQuery is used on 77.6% of all websites (as of
23rd February 2021).
Features
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 fron-
tend 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 ren-
dered 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
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 inter-
active 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
Use Cases
Underscore.js
Underscore is a JavaScript utility package that includes a number of func-
tions for common programming tasks.
Jeremy Askenas produced it in 2009 and released it under an MIT
license.
Lodash has now surpassed it.
Features
• 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 func-
tions 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
Use Cases
Its modular approaches can assist us in
Algolia Places
Algolia Places is a JavaScript package that allows us to use address auto-
completion 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 outstand-
ing open-source database to cover international locations.
196 ◾ Conquering JavaScript
Features
Use Cases
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 straightfor-
ward API.
Features
Use Cases
Features
Use Cases
Bideo.js
Do we want to incorporate full-screen videos into the backdrop of our
website?
Try out Bideo.js.
Features
Use Cases
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 stun-
ning charts and graphs to their projects. It is open-source and licensed
under the MIT license.
Features
Use Cases
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
Use Cases
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
Use Cases
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
Use Cases
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
Use Cases
fullPage.js
fullPage.js, an open-source JS package, makes it simple to develop full-
screen scrolling webpages or one-page websites. It is simple to use and
allows us to include a landscape slider inside our site sections.
Features
Use Cases
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
Case Studies
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
Use Cases
Moment.js
Moment.js assists us in successfully managing time and date while work-
ing 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
Use Cases
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
• 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
Parsley
Do we want to include shapes into our projects? If so, Parsley may be ben-
eficial 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
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
Use Cases
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 capabili-
ties are supported.
• We may make a variety of geometrics, objects, lighting, shadows,
loaders, materials, arithmetic components, textures, and so on.
Use Cases
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
Use Cases
Polymer
Polymer, a Google open-source JavaScript toolkit, is used to create web
programs with components.
Features
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
Use Cases
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.geeksfor-
geeks.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
IN THIS CHAPTER
React and Vue.js are thus quicker for websites and programs that have
a lot of interactive elements.
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 popu-
lar 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
Real-life examples
Popular websites like Facebook, Netflix, Asana, Pinterest, Airbnb,
Reddit, UberEats, etc. have all been designed using React.
The Clearer Picture ◾ 215
Advantages
Disadvantages
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
How It Operates
Real-Life Examples
Popular businesses like Alibaba, 9gag, Xiaomi, and others have used Vue.
js for all of their frontend needs.
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, mobile-
first apps using bootstrap version 4. The kit is jam-packed with a grid
system, many UI elements, and themes.
Advantages
Disadvantages
3. Angular
Google created the TypeScript-based open-source web application frame-
work known as Angular. This framework’s version 2 included fundamen-
tal components including dependency injection, asynchronous compiles,
RxJS, etc.
218 ◾ Conquering JavaScript
How It Operates
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.
Advantages
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.
4. jQuery
Prior to the creation of contemporary JavaScript libraries and frame-
work, 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.
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
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 devel-
oper 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
• 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.
Advantages
Disadvantages
• A little ecosystem.
• There aren’t many Svelte tools on the market.
• Is difficult to scale.
The Clearer Picture ◾ 223
6. Ember
Ember is a free JavaScript framework that supports both MVVM and
MVC architectures. It was first released in 2011. By using the capabili-
ties 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
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
Advantages
Disadvantages
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
How It Operates
Real-Life Examples
Backbone.js has been used by a number of well-known companies,
including Uber, Pinterest, Reddit, Trello, and Tumblr, to fulfill applica-
tion needs.
Advantages
Disadvantages
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 back-
end 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 prob-
lems, compatibility problems, etc.
Complexity
Choose a framework based on MVC architecture if you’re creating a com-
plicated web application with several sub-pages and capabilities. We will
be able to divide your features into sections that can be developed concur-
rently by doing this. Our development time will be greatly shortened by
doing this.
The Clearer Picture ◾ 227
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
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 devel-
oped 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 real-
time applications, particularly those for communication, would be
the next justification.
A framework that makes software quickly responsive is essen-
tial 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 effi-
cient 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
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 frame-
works 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 reac-
tive 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 repeti-
tive 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 char-
acteristic of the data ‘just being there.’
This is ideal for any online application where users add to or mod-
ify 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 func-
tionality is important.
For user management and authentication, a developer often has
to choose two libraries—one for the frontend and one for the back-
end—and then figure out how to integrate them.
The Clearer Picture ◾ 231
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 sup-
port. Canvas is used for devices that don’t support WebGL.
232 ◾ Conquering JavaScript
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 ren-
dering engine for games, but you can still create strong games with
it.
Due to its active and supportive developers, it has great commu-
nity support.
It has a playground so that you may experiment before moving
further with development.
5. Melon.js
It is a highly effective, lightweight, and user-friendly HTML5
game engine that enables designers and developers to concen-
trate 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 guaran-
tee 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 lan-
guage, 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 open-
source game framework is very simple to utilize.
Given that WebGL rendering has been increased, speed is its pri-
mary 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.
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 indistin-
guishable 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 pro-
gramming approach, virtual DOM, and reusable components to develop
UI.
2. NativeScript
NativeScript is a free and open-source framework for developing cross-
platform 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
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 custom-
izable native plugins.
4. Apache Cordova
Apache Cordova (formerly PhoneGap) is a hybrid app development plat-
form that encapsulates HTML or JavaScript programs in a native container.
A plethora of technologies, frameworks, and cloud services are avail-
able to improve Cordova’s speed.
236 ◾ Conquering JavaScript
5. OnSenUI
OnSen UI is a JS framework that allows you to create hybrid mobile appli-
cations 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.
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.
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.
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.
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.
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 con-
trol over our application.
Desktop apps may also be cross-platform, but they need a unique meth-
odology to account for all of the quirks of desktop PC operating systems.
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 wid-
gets 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 com-
patible 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 open-
source 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 lan-
guage. 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 inter-
faces is now limited only by our creativity.
242 ◾ Conquering JavaScript
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.
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 interac-
tive online apps.
There is a considerable discussion regarding whether React.js is a ‘frame-
work’ 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 use-
ful, 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.
<script>
console.log(“Welcome to Home”);
</script>
• Encapsulation
• Abstraction
• Polymorphism
• Inheritance
Java VS JavaScript
Java JavaScript
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 technolo-
gies, 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 struc-
tures 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.
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 hard-
ware 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
JavaScript VS Python
JavaScript Python
JavaScript does not understand the terms Python supports both mutable and
mutable and immutable. immutable data types.
Because JavaScript lacks built-in Unless you provide an encoding format,
functionality for processing raw bytes, it Python source code is ASCII by default.
should be encoded as UTF-16.
JavaScript only supports floating-point There are several numeric types in
integers. Python, such as int and fixed-point
decimal.
Curly brackets are used in JavaScript. Python employs indentation.
JavaScript contains fewer modules such as Python has a large number of modules.
date, arithmetic, regexp, and JSON.
JavaScript objects contain properties that are Getter and setter functions are used to
made up of underlying attributes that allow define attributes in the Python
us to specify a property. programming language.
JavaScript employs an inheritance paradigm Python employs a paradigm of class-
based on prototypes. based inheritance.
JavaScript is a fantastic choice for mobile Python is unsuitable for creating mobile
development in addition to frontend and apps.
backend programming.
JavaScript may be used to create a website or Python is used for data analytics,
a native application. machine learning, and other math-
intensive activities.
TOBIE has a rating of 7. TOBIE has a rating of 3.
In the United States, the average annual The annual compensation for a python
income for a JavaScript developer is developer is $120,255.
$114,856.
The Clearer Picture ◾ 251
• 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:
jQuery VS JavaScript
jQuery JavaScript
JavaScript VS PHP
JavaScript PHP
JavaScript PHP
The code is enclosed by The program written inside <?php....?> tag.
<script>...<script> tags.
Previously, JavaScript could generate A PHP code may build dynamic pages,
interactive sites for clients. However, it transmit and receive cookies, collect form
can now create real-time games and input, and so on.
apps, as well as mobile applications.
It is a single-threaded programming It is a multi-threaded programming
language. As a result, each input–output language. As a result, it will block if
process is performed concurrently. numerous input–output procedures are
performed.
The.js suffix is used to store an external The ‘.php’ extension is used to store files.
JavaScript file.
The js code may be embedded in HTML, Only HTML allows us to embed PHP code.
XML, and AJAX.
It has fewer features. When compared to JavaScript, it provides
more sophisticated functionalities.
Popular JavaScript frameworks include PHP frameworks that are popular include
Angular, React, Vue.js, Meteor, and Laravel, Symfony, FuelPHP, CakePHP, and
more. many others.
Twitter, LinkedIn, Amazon, and other Wordpress, Tumblr, MailChimp,
websites created on JavaScript are iStockPhoto, and more websites created
examples. with PHP are examples.
Dart VS JavaScript
What Is JavaScript?
To create dynamic HTML sites with interactive effects, programmers turn
to JavaScript, a small, object-oriented programming language.
The creation of games and mobile apps both benefit greatly from the
usage of JavaScript.
As its name implies, it is a scripting language whose code is interpreted
and run only in a web browser. Node.js might be used to execute the code
outside of the browser.
Client-side and server-side programming are both possible with this
language, which is also known as the language of browsers. Brendan Eich
of Netscape created it, and in 1995 it was first made available to consum-
ers. Prior to being renamed JavaScript, the language went by the name
LiveScript. As a scripting language, JavaScript borrows extensively from C
in terms of syntax. JavaScript code is saved in a file with the.js extension.
The Benefits and Drawbacks of Using JavaScript
These are some of JavaScript’s benefits and drawbacks:
Advantages
Drawbacks
• There’s a risk that one mistake might take down the whole website.
• Because of the dynamic quality of the language, serious errors by
programmers are not uncommon.
• Only a single inheritance is supported, not numerous ones. This
characteristic of object-oriented languages may be necessary for cer-
tain applications.
Simplicity of Use
JavaScript has been around for a while and is a mature and powerful
language.
JavaScript is easy to use. It contains a number of frameworks and librar-
ies that are freely accessible online. Developers may save time and effort by
making use of these frameworks to create new software with little rework.
Dart, on the other hand, is a new language for most developers outside
of Google. Despite Google’s attempts to explain the Dart programming
language, finding answers to particular issues remains tough for develop-
ers. It features a writing style and grammar comparable to Java, so devel-
opers with OOPS knowledge should be able to learn and utilize Dart once
they understand the fundamentals.
Speed
Because JavaScript is an interpreted language, it is lighter and quicker
than other computer languages. It outperforms Java and other compiled
languages.
Dart, on the other side, is substantially quicker than JavaScript. Dart
can be compiled in both JIT and AOT modes, which aids app develop-
ment in a variety of ways. JIT compilation, for example, may be used to
accelerate development, while AOT compilation can be used to optimize
the release process.
Type Security
As an interpreted language, JavaScript offers both dynamic and
duck-typing.
258 ◾ Conquering JavaScript
Popularity
JavaScript may be found almost everywhere. JavaScript is supported by
almost every machine. JavaScript is now used to build code for the web,
mobile, and server side.
There are about 2.5 million questions regarding JavaScript on Stack
Overflow. Because of its ubiquity, the JavaScript ecosystem has grown
enormously, and it currently dominates the ‘market’ for reusable com-
ponents, thanks to the development of cloud component hubs. Frontend
developers would prefer an alternative option.
Dart, on the other side, is gaining traction, but it is no match for
JavaScript. Dart was nowhere to be seen until Google announced Flutter.
Dart has attracted developers who were previously averse to JavaScript.
Dart currently has around 45K Stack Overflow questions labeled.
Commercial Usage
JavaScript is widely utilized in industry, especially large-scale projects.
It is used in the creation of network and cross-platform applications.
In Facebook’s online and cross-platform applications, React and React
Native, JavaScript is utilized. The eBay, Airbnb, Slack, and more compa-
nies utilize JavaScript as well.
Dart, on the other side, was created at Google. As a consequence, it was
first used internally.
Following the launch of Flutter, major companies such as Alibaba
started adopting Flutter and Dart to develop cross-platform apps.
The following comparison table demonstrates the head-to-head com-
parison between Dart vs JavaScript:
Simplicity Dart features a Java-like syntax JavaScript is simple to use, and it has
of use and writing style, making it easy a variety of frameworks and libraries
to use for developers with available online, allowing developers
OOPS expertise. to reuse preexisting code to develop
apps more quickly.
Editor and Dart code may be written in It has several great editors and IDEs
IDE simple editors such as Sublime for developing apps. A full-fledged
support or VIM. The most popular IDEs IDE is not necessarily required;
for Dart application instead, developers can utilize
development are IntelliJ IDEA lightweight editors such as VIM,
and Android Studio, both of Sublime Text, Emacs, or Atom.
which include the Dart plugin. Some IDEs, such as WebStorm and
Visual Studio Code, may help us
create JavaScript applications.
(Continued)
260 ◾ Conquering JavaScript
Angular JS VS JavaScript
What Is JavaScript?
JavaScript is a tiny, object-oriented programming language that allows
developers to construct dynamic HTML pages with interactive effects.
Using JavaScript is very beneficial for the development of games and
mobile applications.
It is a scripting language whose code is only understood and executed
on a web browser, as its name suggests.
Code may be executed outside of the browser using Node.js. It is the
language browsers utilize. It is handy for developing client and server
applications.
Brendan Eich of Netscape designed and published it to the public for
the first time in 1995.
Before it was renamed JavaScript, the language was known as LiveScript.
JavaScript as a scripting language draws heavily from C in terms of
syntax.
A file with the.js extension is where JavaScript code is kept.
JavaScript Features
There are several JavaScript features. Among them are the following:
Node JS VS JavaScript
What Is JavaScript?
JavaScript is a compact, object-oriented programming language that lets
developers add interactivity to static HTML pages via scripting. When mak-
ing video games or mobile applications, JavaScript comes in quite handy.
Simply said, it is a scripting language whose code can only be read and
executed on a web browser. Node.js allows code to be executed in environ-
ments other than a web browser.
Browsers communicate using this language. It can help you build both
client and server applications. Brendan Eich of Netscape developed it and
made it available to the general public for the first time in 1995. In the
past, this language was known as LiveScript, but it has since been renamed
JavaScript. The syntax of the programming language JavaScript is heavily
inspired by C. JavaScript code is saved in a file with the extension.js.
Benefits
Drawbacks
What Is Node.js?
Node.js is a free and open-source server-side JavaScript runtime environ-
ment that may be used across several platforms. Node.js makes it possible
for JavaScript to be executed in environments outside of web browsers.
Node.js is mostly used for web development and comes with a wide
variety of modules. It’s possible to use it with Windows, Linux, Mac OS,
and other computers. For the development of scalable JavaServer Pages
(JSP) applications, it offers a cross-platform runtime environment that
features event-driven, non-blocking (asynchronous) I/O.
Ryan Dahl created and first released Node.js in 2009. Web apps, real-
time chat apps, command-line apps, and REST API servers are just some
of the many types of applications that may be built using Node.js. However,
its primary use is in the creation of server-side network applications like
web browsers. A common Node.js filename extension is.js.
266 ◾ Conquering JavaScript
Benefits
Drawbacks
with the file system, enabling the developer to access and modify
files on the disc.
• When developing a single web app, JavaScript is often utilized for all
client-side responsibilities. Business validation, the periodic display
of a dynamic page, or even a basic Ajax request might all be part of a
single action. These have a fixed lifetime in each given web applica-
tion. However, Node.js is often used to make any operating system
accessible or executable in a non-blocking manner. Non-blocking
operations on an OS include things like creating or running a shell
script, receiving specific hardware-related information with a sin-
gle call, retrieving data about certificates already installed on the
machine, and carrying out a huge number of predefined actions.
• The key benefits of using JavaScript are the flexibility it provides in
terms of interface and interaction, as well as the appropriate amount
of server connectivity and direct input for visitors. However, Node.
js can process several requests at once and features a node package
manager with more than 500 modules. Its unique abilities include
support for micro-service architecture and Internet of Things.
NOTES
1 The 5 Best JavaScript Frameworks of 2022 [+ How to Pick the Right One]:
https://blog.hubspot.com/website/javascript-frameworks Accessed on: 03
October 2022.
2 JavaScript Library vs JavaScript Frameworks – The Differences: www.
microverse.org/blog/javascript-library-vs-javascript-frameworks-the-dif-
ferences Accessed on: 03 October 2022.
3 7 Frontend JavaScript Frameworks Loved by Developers in 2022: www.simform.
com/blog/javascript-frontend-frameworks/ Accessed on: 03 October 2022.
4 5 Backend JavaScript Frameworks Experts Love: https://insights.dice.
com/2020/08/21/5-backend-javascript-frameworks-experts-love/ Accessed
on: 04 October 2022.
5 8 Best Javascript Game Engines: www.geeksforgeeks.org/8-best-javascript-
game-engines/ Accessed on: 04 October 2022.
6 10 Popular Javascript Frameworks for Mobile App Development: https://
insights.daffodilsw.com/blog/5-popular-javascript-frameworks-for-
mobile-app-development Accessed on: 04 October 2022.
270 ◾ Conquering JavaScript
7 One for All and All for One: JS Frameworks for Desktop Applications and
the Best of Them: https://luxnet.io/blog/the-best-of-js-frameworks-for-
desktop-applications Accessed on: 06 October 2022.
8 How to Choose the Best Javascript Framework: https://wiredelta.com/how-
to-choose-the-best-javascript-framework-2/ Accessed on: 06 October 2022.
9 How to Choose a Right JavaScript Framework for Your Project?: https://
dev.to/abdurrkhalid333/how-to-choose-a-right-javascript-framework-for-
your-project-2501 Accessed on: 06 October 2022.
10 How to Choose a JavaScript Framework for Beginners: www.codecad-
emy.com/resources/blog/what-javascript-framework-to-learn-beginner/
Accessed on: 06 October 2022.
11 Difference between Java and JavaScript: www.geeksforgeeks.org/difference-
between-java-and-javascript/ Accessed on: 06 October 2022.
12 Python vs JavaScript: Key Difference between Them: https://www.guru99.
com/python-vs-javascript.html#:~:text=KEY%20DIFFERENCES%3A-
,JavaScript%20is%20a%20scripting%20language%20that%20helps%20
you%20create%20interactive,choice%20for%20rapid%20application%20
development. Accessed on: 06 October 2022.
13 jQuery vs. JavaScript: www.javatpoint.com/jquery-vs-javascript Accessed
on: 07 October 2022.
14 jQuery vs. PHP: www.javatpoint.com/javascript-vs-php Accessed on: 07
October 2022.
15 Dart vs. JavaScript: www.javatpoint.com/dart-vs-javascript Accessed on: 07
October 2022.
16 JavaScript Vs. Angular Js: www.javatpoint.com/javascript-vs-angularjs
Accessed on: 07 October 2022.
17 JavaScript vs. Node.js: www.javatpoint.com/javascript-vs-nodejs Accessed
on: 08 October 2022.
Chapter 5
Frontend Development
IN THIS CHAPTER
➢ React
➢ Express
➢ Vue.js
FRONTEND VS BACKEND
Frontend and backend are the two terms used in web development most
frequently.
These words are crucial for web development even if they are very differ-
ent from one another.1 Each side must work together and communicate with
one another as a single unit in order to improve the website’s functionality.
FRONTEND DEVELOPMENT
The part of a website that users engage with directly is referred to as the
frontend.
It is frequently referred to as the ‘client side’ of the program. It encom-
passes all of the elements that consumers view and utilize right away,
including button colors, text styles, images, graphs, and tables.
HTML, CSS, and JavaScript are the three languages used for frontend
programming.
The structure, design, behavior, and content of everything seen on
browser displays when websites, online applications, or mobile apps are
viewed are all put into practice by frontend developers. Performance and
responsiveness are the main objectives of the frontend.
Frontend Languages
The languages listed below are used to build the frontend portion:
BACKEND DEVELOPMENT
The server side of a website is called the backend.
It also ensures that everything on the client side of the website func-
tions properly while storing and organizing data. It is the portion of the
website that you are unable to see and use.
It is the part of the program that consumers do not directly interact
with.
Users indirectly access the components and features created by back-
end designers via a frontend application. The backend also includes
tasks like developing APIs, building libraries, and interacting with
system elements devoid of user interfaces or even systems of scientific
programming.
Backend Languages
The following list of languages is used to build the backend portion:
Backend Frameworks
REACTJS
We will about ReactJS below with its definition, installation, and syntax.
• It’s useful for creating both online and mobile applications: Although
it is common knowledge that web apps are built using React, it is
far from its only purpose. React Native is a popular framework for
developing high-quality mobile apps; it is based on the original React
library. To that end, it’s important to note that React is as at home
when developing for the web as it is for mobile devices.
• Facebook has created a Chrome plugin that can be used to debug
React apps, providing dedicated tools for simple debugging. Because
of this, fixing bugs in React web apps is a breeze.
React Features
It’s no secret that ReactJS is quickly becoming the preferred JavaScript
framework among today’s most cutting-edge websites.3
It’s doing some very important work for the frontend ecosystem right now.
Some of ReactJS’s most notable characteristics are listed here.
• JSX
• Components
• One-way Data Binding
• Virtual DOM
• Simplicity
• Performance
JSX
Performance Components
One-way
Simplicity Data
Binding
Virtual
DOM
Features of React
278 ◾ Conquering JavaScript
JSX
JavaScript XML is what JSX refers to. It’s a new addition to the JavaScript
syntax.
ReactJS employs a syntax that’s similar to XML or HTML.
Calls to the React Framework’s Java API are generated from this
syntax. By enhancing ES6, it allows HTML-like text to coexist with
JavaScript react code. In ReactJS, JSX is not required but is highly
encouraged.
Components
Components are the backbone of ReactJS. Each individual ‘component’ in
a ReactJS program has its own set of rules and data processing capabili-
ties. Because of their modular nature, these parts may be reused, making
it easier to manage the codebase of large-scale projects.
Virtual DOM
A DOM object that exists only in a computer’s memory is called a ‘virtual
DOM object.’
The effect is similar to a one-way data binding.
If there are any changes made to the web app, the complete user interface
will be re-rendered in a virtual DOM representation. Then, it compares
the old DOM representation to the new one. Afterward, just the modified
elements will be reflected in the true DOM. This eliminates memory waste
and speeds up the program.
Simplicity
Because it is written in JSX files, ReactJS is easy to learn and implement.
Frontend Development ◾ 279
Performance
There is widespread agreement that ReactJS is a speed demon. As a
result of this improvement, it is now the best framework available.
Because it controls a DOM that exists only in the computer’s mem-
ory, this is the case. HTML, XML, and XHTML are all supported by
the Document Object Model (DOM), a programming API that works
across platforms.
The DOM is purely virtual. This is why we avoid explicitly altering the
DOM whenever we build new components. Instead, we’re focusing on
developing virtual components that can be easily transformed into DOM
for improved speed.
Benefits
1. ReactJS is simple to learn and use
As opposed to other similar frameworks, ReactJS is far less com-
plicated to learn and use. There is a tonne of help material like guides
and videos included. Any developer with a JavaScript experience may
quickly grasp and begin designing web applications using React.
It’s a JavaScript framework that represents the view in the Model-
View-Controller (MVC) design pattern. It is not fully featured, but
it has the benefit of an open-source JavaScript User Interface (UI)
library, which aids in job execution.
4. Improving Performance
ReactJS is quicker because of the virtual DOM. The DOM provides
a consistent API for developing applications that work with HTML,
XML, and XHTML regardless of the platform. This bug slowed
down development time for most programmers when the DOM was
updated. Virtual DOM is how ReactJS dealt with this problem.
The React Virtual DOM is a version of the web browser’s DOM
that resides completely in memory. As a result, we did not write
directly to the DOM while creating a React component.
Instead, we’re creating virtual components that will respond to
the DOM, resulting in smoother and quicker performance.
Drawbacks
2. Inadequate documentation
It is just another drawback of rapidly evolving technology. The
rate of advancement and expansion of React technologies makes it
impossible to offer thorough documentation. To solve this, develop-
ers create their own instructions when new versions and tools are
added to their present projects.
282 ◾ Conquering JavaScript
3. View Part
ReactJS just covers the app’s UI layers and nothing more. As a
result, we will still need to choose some additional technologies
in order to have a comprehensive tools set for development in the
project.
4. SX as a barrier
ReactJS makes use of JSX. Because of this syntactic extension,
HTML and JavaScript may cohabit. Although this method has ben-
efits of its own, some members of the development community con-
sider JSX to be a barrier, especially for novice developers.
Developers complain about the complexity of the learning curve.
Version of React
A detailed React release history is shown here. On GitHub, we may also
get complete documentation for latest versions.5
$ node -v
$ npm -v
$ mkdir reactApp
$ cd reactApp
We must install react and its DOM packages using the npm command
below in the terminal window after generating a package.json file.
Install Webpack
Automation of the development and production pipelines is accomplished
using Webpack.
Webpack-dev-server will be used for development, Webpack will be
used to produce builds, and Webpack CLI offers a number of commands.
These are combined by Webpack into a single file (bundle). Utilize the
command described below to install Webpack.
Install Babel
Babel is a JavaScript transpiler and compiler used to translate different
source code.
React JSX and ES6 are converted into ES5 JavaScript, which may be
used with any browser.
Babel-preset-react enables our browser to immediately update when-
ever any changes are made to our code without losing the state of the app.
We require babel-loader for JSX file types.
Babel preset babel-preset-env is necessary for ES6 functionality. Use the
command as indicated in the below code to install Webpack.
Creation of Files
To finish the installation procedure, the following files must be added to
our project folder.
Frontend Development ◾ 289
javatpoint@root:~/Desktop/reactApp>touch indexs.html
javatpoint@root:~/Desktop/reactApp>touch Appl.js
javatpoint@root:~/Desktop/reactApp>touch main.js
javatpoint@root:~/Desktop/reactApp>touch webpack.
config.js
javatpoint@root:~/Desktop/reactApp>touch .babelrc
webpack.config.json
module.exports = {
entry: ‘./main.js’,
output: {
path: path.join(__dirname, ‘/bundle’),
filename: ‘indexsbundle.js’
},
devServer: {
inline: true,
port: 8080
},
module: {
rules: [
290 ◾ Conquering JavaScript
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: «babel-loader»,
}
}
]
},
plugins:[
new HtmlWebpackPlugin({
template: ‘./indexs.html’
})
]
}
Now, open the package.json file, remove “test” “echo\ “Error: no test speci-
fied\” && exit” from the “scripts” object, and replace it with the start and
build commands. Because we will not do any testing on this application.
{
“name”: “reactApp”,
“version”: “1.0.0”,
“description”: “”,
“main”: “indexs.js”,
“scripts”: {
“start”: “webpack-dev-server --mode development
--open --hot”,
“build”: “webpack --mode production”
},
“keywords”: [],
“author”: “”,
“license”: “ISC”,
“dependencies”: {
“react”: “^16.8.6”,
“react-dom”: “^16.8.6”,
“webpack-cli”: “^3.3.2”,
“webpack-dev-server”: “^3.3.2”
},
“devDependencies”: {
“@babel/core”: “^7.4.3”,
Frontend Development ◾ 291
“@babel/preset-env”: “^7.4.3”,
“@babel/preset-react”: “^7.0.0”,
“babel-core”: “^6.26.3”,
“babel-loader”: “^8.0.5”,
“babel-preset-env”: “^1.7.0”,
“babel-preset-react”: “^6.24.1”,
“html-webpack-plugin”: “^3.2.0”,
“webpack»: “^4.30.0”
}
}
<!DOCTYPE html>
<html lang = “en”>
<head>
<meta charset = “UTF-8”>
<title>React App</title>
</head>
<body>
<div id = “app”></div>
<script src = ‘indexsbundle.js’></script>
</body>
</html>
App.js
render(){
return(
<div>
<h1>Hello Everyone</h1>
</div>
);
}
}
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
.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
This command creates the bundle in the current folder (to which our
application belongs) and displays it.
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:~/>create-react-app jtp-reactapp
294 ◾ Conquering JavaScript
The above code will install react and generate a new project called jtp-
reactapp. 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
function App() {
return (
<div className=”App”>
<header className=”App-header”>
<img src={logo} className=”App-logo”
alt=”logo” />
<p>
Welcome Everyone.
Running Server
After installation is complete, we may start the server by using the follow-
ing code:
javatpoint@root:~/Desktop>cd jtp-reactapp
javatpoint@root:~/Desktop/jtp-reactapp>npm start
AngularJS
The open-source JavaScript framework AngularJS is used to create
dynamic web applications. In 2009, Misko Hevery and Adam Abrons cre-
ated 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 <script>
tag. It enhances HTML by adding built-in attributes using directives and
connects data to HTML using Expressions.
Characteristics of AngularJS
ReactJS
User interfaces for single-page applications are created using the free and
open-source JavaScript package ReactJS. It is exclusively responsible for
the application’s view layer.
It enables developers to assemble complicated user interfaces using
tiny, isolated pieces of code known as ‘components.’ ReactJS consists of
two parts: components, which are the elements that include HTML code
and what we want to see in the user interface, and an HTML page where
all your components are presented.
It is developed by Jordan Walke, a former software developer at
Facebook. Initially created and managed by Facebook, it was eventually
included in major products like WhatsApp and Instagram. ReactJS was
created by Facebook in 2011 for the newsfeed area, although it was not
made available to the public until May 2013.
Frontend Development ◾ 297
Characteristics of ReactJS
AngularJS ReactJS
What Is React?
React is a frontend JavaScript library that developers use to create user
interfaces.
The UI elements are maintained by the Meta (Facebook), and a group
of organizations and developers collaborate to create updated versions.
The foundation for creating webpages, mobile applications, and server-
rendered apps is React. React is helpful for managing state and rendering
it onto the DOM.
React application development necessitates the use of extra libraries.
To create React components, you need to be familiar with design patterns,
client-side code, and routing.
Performance
Traditional Document Object Model (DOM) necessitates an update for
each code change, which degrades the efficiency of the application. Virtual
DOM accelerates the process by functioning as temporary memory stor-
age for user interface modifications.
A procedure called as diffusion or reconciliation delays updates until
they can be successfully updated and rendered.
React utilizes virtual DOM to decompose an application’s code as the
code is run.
VDOM improves React’s performance over conventional JavaScript
languages. However, Svelte improves efficiency by avoiding the VDOM
diffing procedure. Svelte is a compiler that renders DOM documents using
reactive programming. The DOM is updated whenever an assignment
causes a change in the component stage. As a serverless-first framework,
Svelte is therefore seen as more reactive than React.
Bundle Size
The.gzip version of Svelte has a size of 1.6 kilobytes. When paired with
ReactDOM, React.gzip has a total size of 42.2 kilobytes. Svelte’s decreased
Frontend Development ◾ 301
Testing
End-to-end tests are able to be performed on React code. The application’s
React code is tested in a realistic browser environment. This decreases
the time to market (TTM) and increases the value of your software. The
Svelte testing library is available for unit testing. The Svelte testing library
is more compact than React and provides straightforward calculations.
Thus, Svelte can assist developers in maintaining code that is clean, func-
tional, and compact.
Community Assistance
React has a large developer community since it is one of the most popu-
lar JavaScript platforms in the world. The community of React develop-
ers contributes tutorials, guidelines, updates, components, and more in
order to maintain the library’s usefulness. The fact that a huge corpora-
tion like Facebook (Meta) maintains React increases the need for React
engineers. Svelte is uncommon, but developers that employ it report
high levels of satisfaction. Svelte’s enterprise-level support is relatively
new, as Sveltekit 1.0 has not yet been published. Compared to the more
than 287k active React developers, the Svelte community consists of just
11k developers.
Who Succeeds?
The Svelte vs. React debate is simple when the project needs are well-
defined. Utilize Svelte in our applications to obtain a lower bundle size,
manageable code, and outstanding performance without the VDOM. Due
to the framework’s simplicity, Svelte helps developers to prepare websites
more quickly.
Utilizing React for our projects will facilitate the recruitment of soft-
ware professionals.
React facilitates the maintenance of application stability. An active
community of React developers assists in resolving development-related
questions and issues.
Using React with Svelte to produce robust software solutions necessi-
tates the hiring of seasoned software engineers.
302 ◾ Conquering JavaScript
REACT JSX
All React components have a render method, as we have previously seen.
A React component’s HTML output is defined by the render function.
A React plugin called JSX (JavaScript Extension) enables the creation of
JavaScript code that resembles HTML.9
To put it another way, JSX is an extension of ECMAScript utilized by
React to allow HTML-like syntax to coexist alongside JavaScript/React
code. Preprocessors (also known as transpilers, such as babel) employ the
syntax to convert HTML-like syntax into typical JavaScript objects that a
JavaScript engine can interpret.
In the same file where we write JavaScript code, JSX enables us to write
HTML/XML-like structures (such as DOM-style tree structures). A pre-
processor will subsequently convert these expressions into JavaScript
code. JSX tags contain a tag name, attributes, and children much as XML/
HTML tags do.
Example
In this section, we’ll put JSX syntax in a JSX file and examine the
associated JavaScript code that a preprocessor converts (babel).
JSX File
<div>Hello Everyone</div>
Output
React.createElement(“div”, null, “Hello Everyone”);
The code above creates a react element with three arguments, the first of
which is the element’s name, “div,” the second of which is the attributes
supplied in the div tag, and the third of which is the content we supply,
“Hello Everyone.”
App.JSX
Attributes in JSX
Like standard HTML, JSX uses attributes with HTML components.
Because class is a reserved term in JavaScript, JSX employs camelcase
naming conventions for attributes rather than the conventional naming
convention of HTML. For example, a class in HTML becomes className
in JSX.
In JSX, we may also utilize our own unique custom characteristics.
Data- prefix must be used for custom attributes.
304 ◾ Conquering JavaScript
Example
import React, { Component } from ‘react’;
class App extends Component{
render(){
return(
<div>
<h1>Everyone</h1>
<h2>Training Institutes</h2>
<p data-demoAttribute = “demo”> The
greatest CS lessons may be found on this website.</p>
</div>
);
}
}
export default App;
Example
import React, { Component } from ‘react’;
class App extends Component{
render(){
return(
<div>
<h1 className = “hello” >Everyone</h1>
<p data-demoAttribute = “demo”> The
greatest CS lessons may be found on this website.</p>
</div>
Frontend Development ◾ 305
);
}
}
export default App;
Example
import React, { Component } from ‘react’;
class App extends Component{
render(){
return(
<div>
<h1 className = “hello” >{45+10}</h1>
</div>
);
}
}
export default App;
Comments in JSX
Similar to how JSX expressions are used, JSX enables us to utilize com-
ments that start with /* and conclude with */ and enclose them in curly
brackets. The JSX sample below demonstrates how to utilize comments.
Example
import React, { Component } from ‘react’;
class App extends Component{
render(){
return(
<div>
<h1 className = “hello” >Hello
Everyone</h1>
306 ◾ Conquering JavaScript
Styling in JSX
React consistently advises using inline styles. We must use camelCase
syntax to set inline styles. On some elements, React automatically permits
appending px after the number value. The element’s style may be seen in
use in the instance below.
Example
import React, { Component } from ‘react’;
class App extends Component{
render(){
var myStyle = {
fontSize: 50,
fontFamily: ‹Courier›,
color: ‹#004400›
}
return (
<div>
<h1 style = {myStyle}>www.example.com</h1>
</div>
);
}
}
export default App;
Example
import React, { Component } from ‘react’;
class App extends Component{
render(){
var x = 6;
return (
<div>
Frontend Development ◾ 307
EXPRESS.JS
We will about Express.js below with its definition, installation, and
syntax.10
WHAT IS EXPRESS.JS?
Express is a Node.js web framework that is quick, forceful, necessary, and
modest. We might imagine express as a layer added to Node.js that assists
in managing a server and routes. It offers a complete collection of tools for
creating online and mobile apps.
Here are a few of the key components of the Express framework:
basic_express.js
var express = require(‘express’);
var app = express();
app.get(‘/’, function (req, res) {
res.send(‹Welcome to Everyone›);
});
var server = app.listen(8000, function () {
var host = server.address().address;
var port = server.address().port;
console.log(‹Instance app listening at
http://%s:%s›, host, port);
});
Prerequisite
We must have a working grasp of JavaScript and Node.js before studying
Express.js.
Audience
Both learners and experts may benefit from the information in our
Express.js lesson.
Problem
We guarantee that there won’t be any issues with this Express.js lesson.
However, if there is a mistake, please report it using the contact form.
Benefits of Express.js
SETTING UP EXPRESS
Using npm, we can put it in. Inspect our installation of npm and Node.js.12
Step 1: The first step is creating a directory for our project and making
that directory our working directory.
$ mkdir pfp
$ cd pfp
Step 2: Making a package using the npm init command. For our project,
a json file.
$ npm init
This command lists all of our project’s dependencies. The document will
be updated as more Setting up Express
Step 3: Type the below command line in our pfp(name of our folder)
folder:
Example
In app.js, enter the following code.
Run the program by entering the following code in the run window.
node app.js
Its Evolution
JavaScript engines improved a lot as browsers vied to provide consumers
with the greatest performance.
Major browsers put a lot of effort into figuring out how to make
JavaScript run more quickly and provide better support.
Node.js was thus created at the appropriate time and location.
Numerous methods for JavaScript server-side programming were estab-
lished, as well as creative thinking that has benefited many developers.
The fact that Node.js supports hundreds of open-source libraries, the
bulk of which are available on the npm website, is one of the main reasons
for its popularity among developers.
Frontend Development ◾ 311
BASICS OF NODE.JS
JavaScript is supported by Node.js. Thus, JavaScript syntax in Node.js is
comparable to JavaScript syntax in browsers.14
Types of Primitive
These basic types are available in Node.js:
• String
• Boolean
• Number
• Undefined
• Null
• RegExp
Loose Typing
Like JavaScript in browsers, Node.js JavaScript enables loose typing. To
define a variable of any type, use the var keyword.
Object Literal
The object literal syntax is the same as JavaScript in browsers.
var obj = {
authorName: ‘Shiya Sham’,
language: ‘Node.js’
}
312 ◾ Conquering JavaScript
Functions
Similar to JavaScript in browsers, Node’s JavaScript treats functions as
first-class citizens.
Additionally, a function may have characteristics and attributes. In
JavaScript, it is comparable to a class.
function Display(k) {
console.log(k);
}
Display(200);
Buffer
Buffer is an extra data type in Node.js that is not offered by JavaScript in
browsers.
When reading from a file or receiving packets over the network, buffer
is mostly utilized to hold binary data.
Process Object
A process is used to execute each Node.js script. To get all the details about
the Node.js application’s current process, it contains a process object. The
example that follows demonstrates how to use a process object to get pro-
cess information in REPL.
> process.execPath
‘C:\\Program Files\\nodejs\\node.exe’
> process.pid
1234
> process.cwd()
‘C:\\’
Defaults to Local
When it comes to global scope, Node’s JavaScript differs from JavaScript
in browsers.
Variables defined without the var keyword become global in the brows-
er’s JavaScript. Everything becomes local by default with Node.js.
Frontend Development ◾ 313
exports.log = {
console: function(msg) {
console.log(msg);
},
file: function(msg) {
// here log to file
}
}
We can now use the log object anywhere in our Node.js project by import-
ing it using the require() method.
VUEJS
We will about VueJS below with its definition, installation, and syntax.
WHAT IS VUEJS?
An open-source, progressive JavaScript framework called VueJS is used to cre-
ate dynamic web interfaces. One of the well-known frameworks for stream-
lining web development is this one. The view layer is where VueJS focuses.15
It may be seamlessly incorporated into large frontend development proj-
ects. VueJS installation is pretty simple to begin with. Interactive web inter-
faces are simple to comprehend and quick to construct for any developer.
Former Google employee Evan You is the creator of VueJS. VueJS’s first
version was published in February 2014. It is now rated 64,828 stars on
GitHub, making it highly well-liked.
Features
The characteristics of VueJS are listed below.
• DOM virtual
Virtual DOM is a technique utilized by VueJS and other frame-
works such as React and Ember.
314 ◾ Conquering JavaScript
• Binding of data
With the aid of a binding directive called v-bind that is included
with VueJS, the data binding functionality assists in manipulating or
assigning values to HTML attributes, changing the style, and assign-
ing classes.
• Components
One of VueJS’s key features, components enable the creation of
unique elements that may be reused throughout HTML.
• Event handling
In VueJS, the DOM elements include a property called v-on that
makes it possible to listen to events.
• Animation/Transition
When HTML elements are added, changed, or deleted from the
DOM, VueJS offers a variety of techniques to apply transition. For
the transition effect, an element must be wrapped in the built-in
transition component of VueJS. The interface may be made more
interactive and third-party animation libraries are simple to add.
• Computerized Property
One of VueJS’s key characteristics is this. It’s critical to pay atten-
tion to UI element changes and perform the necessary computations.
Additional code is not required for this.
• Templates
The DOM is bound to the Vue instance data through HTML-based
templates that are provided by VueJS. The templates are converted
by Vue into simulated DOM Render functions. We may utilize the
Frontend Development ◾ 315
render function template, but we must swap out the template with
the render function in order to do so.
• Directives
The built-in directives in VueJS may be used to carry out a vari-
ety of frontend tasks, including v-if, v-else, v-show, v-on, v-bind, and
v-model.
• Watchers
Data that changes is given watchers. For instance, form input
components.
We don’t need to add any further events in this case. The code is
made easy and quick by the watcher, which takes care of processing
any data changes.
• Routing
With the aid of vue-router, pages may be navigated between.
• Lightweight
The performance and weight of the VueJS script are both quite
quick.
• Vue-CLI
Using the vue-cli command line interface, VueJS may be installed
via the command line. Using vue-cli makes it simple to build and
compile the project.
VueJS vs React
DOM Virtual The DOM tree is represented virtually by virtual DOM. A
JavaScript object that is identical to the actual DOM is constructed using
virtual DOM. Every time a modification to the DOM is required, a new
JavaScript object is formed and the modifications are made. Later, the
final modifications are updated in the actual DOM after a comparison of
316 ◾ Conquering JavaScript
the two JavaScript objects. Both VueJS and React employ virtual DOM,
which speeds things up.
JSX vs. a Template Separate html, js, and css are used by vuejs. The
VueJS style is relatively simple for a novice to comprehend and adapt.
The VueJS template-based method is fairly simple. React uses the jsx
method. For ReactJS, everything is JavaScript. JavaScript includes both
HTML and CSS.
Tools for Installation VueJS utilizes vue-cli, the CDN, and npm, whereas
React uses build react app.
Both are quite simple to use, and the project has been set up to meet all
the prerequisites. VueJS does not need webpack for the build, but React
requires. Using the CDN library, we may begin writing VueJS code any-
where in jsfiddle or codepen.
Popularity
More people use React than VueJS. React offers more employment oppor-
tunities than VueJS.
React is more well-known since it is backed by a well-known company,
namely Facebook.
React employs the finest JavaScript practices since it exploits the lan-
guage’s fundamental idea. Anyone who uses React will undoubtedly be
quite knowledgeable about all the JavaScript fundamentals.
The framework VueJS is under development. Currently, compared
to React, VueJS has less career possibilities. A poll indicates that many
individuals are adjusting to VueJS, which might increase its popularity
relative to React and Angular. A strong community is developing VueJS’s
many features. This community updates the vue-router on a regular basis.
VueJS is a strong library that was created by combining the best elements
of Angular and React. Due to its lightweight library, VueJS is considerably
quicker than React/Angular.
VueJS vs Angular
Similarities
Angular and VueJS are quite similar to one another. V-if and V-for
directives are nearly identical to Angular’s ngIf and ngFor. Both of
Frontend Development ◾ 317
them offer a command line interface that is used to install and build
the project.
Both Angular and VueJS require angular-cli. Both provide server side
rendering, two-way data coupling, etc.
Complexity
Vuejs is really simple to use and learn. As was previously said, a newbie
may use the VueJS CDN package to get started with codepen and jsfiddle.
For Angular, we must follow a set of procedures for installation, and get-
ting started with Angular might be a bit challenging for novices. It employs
TypeScript for coding, which is challenging for anyone with a background
in JavaScript’s fundamentals. However, users with a background in Java
and C# find it simpler to learn.
Performance
The users will determine the performance. Compared to Angular, VueJS is
substantially less in file size. The following URL: http://stefankrause.net/
js-frameworks-benchmark4/webdriver-ts/table.html compares the per-
formance of the frameworks.
Popularity
Currently, Angular is more widely used than VueJS. Angular is widely used
by many businesses, making it quite well-known. For those with Angular
expertise, job prospects are also more plentiful. VueJS, on the other hand, is
gaining ground and may be seen as an excellent rival to Angular and React.
Dependencies
Many functionalities are included by default with Angular.
To begin, we must import the necessary modules, such as @angular/
animations and @angular/form.
VueJS relies on third-party libraries to function since it lacks several of
Angular’s built-in functionality.
Flexibility
Any other large project may be seamlessly combined with VueJS without
any problems.
It won’t be simple to start using Angular with any other project that
already exists.
318 ◾ Conquering JavaScript
Reverse Compatibility
AngularJS, Angular2, and Angular4 have all been around. The two
Angular frameworks, JS and v2, vary greatly.
Due to fundamental incompatibilities, project applications created in
AngularJS cannot be transferred to Angular2. VueJS 2.0 is the most cur-
rent version, and it has strong backward compatibility. It has excellent
documentation that is extremely simple to read.
Typescript
For its coding, Angular uses TypeScript. To use Angular, users need to be
familiar with TypeScript. But with the CDN library, we may begin writing
VueJS code anywhere in jsfiddle or codepen. Standard JavaScript is avail-
able for use and is a great place to start.
<html>
<head>
<script type = “text/javascript” src = “vue.min.
js”></script>
</head>
<body>
</body>
</html>
Example 1
<!DOCTYPE html>
<html>
<head>
<title>Out first Vue app</title>
<script src=”https://unpkg.com/vue”></script>
</head>
<body>
<div id=”app”>
{{ message }}
</div>
<script>
var app = new Vue({
el: ‘#app’,
data: {
message: ‘Vue.js instance with the CDN’
}
})
</script>
</body>
</html>
Example 2
<!DOCTYPE html>
<html>
<head>
<title>Our first Vue app</title>
<script src=”https://cdn.jsdelivr.net/npm/vue/dist/
vue.js”> </script>
</head>
<body>
<div id=”app”>
{{ message }}
</div>
<script>
var app = new Vue({
320 ◾ Conquering JavaScript
el: ‘#app’,
data: {
message: ‘Vue.js second instance with the CDN’
}
})
</script>
</body>
</html>
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
cd myproject
We can see that the Server is launched after executing the npm run dev
command. Open Google Chrome or any suitable browser and execute loc-
alhost 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
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.
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
• Grammarly
• Laracast
• Behance
• Netflix
• Codeship
• Livestorm
• Gitlab
• Euronews
• Wizzair, etc.
324 ◾ Conquering JavaScript
vue --version
Syntax:
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:
Indexs.html file:
<html>
<head>
<link rel=”stylesheet” href=”indexs.css”>
<script src=”https://cdn.jsdelivr.net/npm/vue/
dist/vue.js”></script>
</head>
<body>
<div id = “app”>
<h1>Firstname is: {{firstname}}</h1>
<h1>Lastname is: {{lastname}}</h1>
<h1>{{mydetails()}}</h1>
</div>
<script src=”indexs.js”></script>
</body>
</html>
326 ◾ Conquering JavaScript
Indexs.js file:
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.
<div id = “app”></div>
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 <div> element contains a definition for this as well. For
instance,
Frontend Development ◾ 327
<div id = “app”>
<h1>Firstname : {{firstname}}</h1>
<h1>Lastname : {{lastname}}</h1>
</div>
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 <div> element as
<h1>{{mydetails()}}</h1>
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:
<html>
<head>
328 ◾ Conquering JavaScript
<title>Vue.js Template</title>
<link rel=”stylesheet” href=”indexs.css”>
<script src=”https://cdn.jsdelivr.net/npm/
vue/dist/vue.js”></script>
</head>
<body>
<div id = “app”>
<h1>Firstname is: {{firstname}}</h1>
<h1>Lastname is: {{lastname}}</h1>
<div>{{htmlcontent}}</div>
</div>
<script src=”indexs.js”></script>
</body>
</html>
Indexs.js file:
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
Syntax:
Example 2
Indexs.html file:
<html>
<head>
<title>Vue.js Template</title>
<link rel=”stylesheet” href=”indexs.css”>
<script src=”https://cdn.jsdelivr.net/npm/
vue/dist/vue.js”></script>
</head>
<body>
<div id = “app”>
<h1>Firstname : {{firstname}}</h1>
<h1>Lastname : {{lastname}}</h1>
<div v-html = “htmlcontent”></div>
</div>
<script src=”indexs.js”></script>
</body>
</html>
Indexs.js file:
var vm = new Vue({
el: ‘#app’,
data: {
firstname : “Alisha”,
lastname : “Singla”,
htmlcontent : "<div><h1>This is the Vue.js
Template instance</h1></div>”
}
})
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:
<html>
<head>
<title>Vue.js Template</title>
<link rel=”stylesheet” href=”indexs.css”>
<script src=”https://cdn.jsdelivr.net/npm/
vue/dist/vue.js”></script>
</head>
<body>
<div id = “app”>
<h1>Firstname : {{firstname}}</h1>
<h1>Lastname : {{lastname}}</h1>
<div v-html = “htmlcontent”></div>
<img src = “” width = “310” height = “280” />
</div>
<script src=”indexs.js”></script>
</body>
</html>
Indexs.js file:
var vm = new Vue({
el: ‘#app’,
data: {
firstname : “Alisha”,
lastname : “singla”,
htmlcontent : "<div><h1>This is the Vue.js
Template instance</h1></div>”,
imgsrc : “https://www.fiordalisa.ch/
wp-content/uploads/2017/12/IMG_40.jpg”
}
})
Frontend Development ◾ 331
Example 3
Indexs.html:
<html>
<head>
<title>Vue.js Template</title>
<link rel=”stylesheet” href=”indexs.css”>
<script src=”https://cdn.jsdelivr.net/npm/
vue/dist/vue.js”></script>
</head>
<body>
<div id = “app”>
<h1>Firstname : {{firstname}}</h1>
<h1>Lastname : {{lastname}}</h1>
<div v-html = “htmlcontent”></div>
<img v-bind:src = “imgsrc” width = “310”
height = “280” />
</div>
<script src=”indexs.js”></script>
</body>
</html>
Indexs.js:
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/reactjs-
vs-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-in-
2022/#:~: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-of-
nodejs/ 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-with-
vue-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
NODE.JS
We will discuss introduction to node.js and its installation process below:
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.
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.
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 pro-
gram 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
OS Archive Name
Windows node-v6.3.1-x64.msi
Mac node-v6.3.1-darwin-x86.tar.gz
Linux node-v6.3.1-linux-x86.tar.gz
SunOS node-v6.3.1-sunos-x86.tar.gz
$ cd /tmp
$ wget http://nodejs.org/dist/v6.3.1/node-v6.3.1-
linux-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
OS Output
Mac export PATH=$PATH:/usr/local/nodejs/bin
Linux export PATH=$PATH:/usr/local/nodejs/bin
FreeBSD export PATH=$PATH:/usr/local/nodejs/bin
To view the outcome, run the main.js file using the Node.js interpreter
now.
$ node main.js
• Import required modules: Use the need directive to load the neces-
sary 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 previ-
ous stage will read the HTTP request sent by the client, which can be
a browser or a console, and deliver the response.
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 lan-
guages 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.
Documents Documents
Collection
Collection
Databases Documents Documents
Documents Documents
Working of MongoDB
MongoDB RDBMS
It is a document-oriented, non-relational
database. The database is a relational one.
It is appropriate for storing hierarchical It is not appropriate for storing hierarchical
data. data.
Its schema is dynamic. It already has a schema.
The CAP theorem is at its core It focuses on the characteristics of ACID
(Consistency, Availability, and Partition (Atomicity, Consistency, Isolation, and
tolerance). Durability).
It performs significantly better than It performs worse than MongoDB in terms
RDBMS in terms of speed. of speed.
Backend Development ◾ 345
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.
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 typ-
ing “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 discov-
ered. 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” com-
mand with the switch –dbpath <path>.
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 com-
mands 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
<dbname>,” and you can examine the databases by typing “see dbs.”
There are no collections currently in existence. By entering the com-
mand “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
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 docu-
ment 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 uti-
lize 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
print ( femaleEmp[i].name)
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
Installation Step 4
Step 5: Choose “Run service as Network Service user” and note the direc-
tory’s location. Select Next.
Step 10: Next, open System Properties, << Environment Variable << System
variable << path << Edit Environment variable paste the copied URL into
Backend Development ◾ 353
Installation Step 5
Installation Step 6
354 ◾ Conquering JavaScript
Installation Step 7
Installation Step 8
Backend Development ◾ 355
Step 11: Following the setup of the environment variable, mongod, the
MongoDB server, will be started. Run the following command after start-
ing the command prompt:
mongod
mongod
Now, the MongoDB server (also known as mongod) will operate correctly.
Example
In our shell, we may now create new databases, collections, and docu-
ments. An illustration of creating a new database is shown below.
The use Databasename creates a new database in the system if one
doesn’t already exist and utilizes an existing database if one does.
use pfp
db.student.insertOne({Ankita:400})
SERVER-SIDE JS
We will discuss introduction to Server-side JS and its installation process
below:
Server-Side Website Programming
The Dynamic Websites—Server-side programming subject is comprised
of a set of modules that demonstrate how to develop dynamic websites, or
websites that serve personalized content in response to HTTP requests.11
The majority of significant websites employ server-side technologies to
dynamically display data on demand. Consider, for instance, how many
things are accessible on Amazon and how many Facebook postings have
been published. It would be extremely inefficient to display all of these on
separate static pages; so instead, these sites display static templates (built
using HTML, CSS, and JavaScript) and dynamically update the data dis-
played within those templates when necessary, such as when we want to
view a different product on Amazon.
In the present world of web development, it is strongly suggested to
have knowledge in server-side development.
Server-side programming is typically less daunting than client-side
development for new developers because most dynamic websites use web
frameworks that simplify common web server operations like retrieving
data from a database and displaying it in a page, validating user-entered
data and saving it to a database, checking user permissions and logging
users in, etc. The ability to program (or familiarity with a certain pro-
gramming language) is helpful but not required.
To the same extent, we don’t need to be a coding pro to work effectively
with the team building our website’s frontend.
Web browsers run JavaScript, a Web programming language that is
largely used on webpages and web apps. But because JavaScript is a gen-
eral-purpose language, it may also be used for other kinds of program-
ming. It may be utilized on the server side, which in this context refers to
all locations other than the web browser.
Backend Development ◾ 357
Runtime Environment
To put it simply, a JavaScript Runtime Environment is a container that
houses the JavaScript engine and executes scripts. Because of its embedded
nature, JavaScript often requires extra libraries.12 These further objects and
capabilities are made available by the Runtime Environment. Web brows-
ers include a number of other things, such as the window and the page.
MERN STACK
Full-stack online applications may be deployed more quickly and with
less effort with MERN Stack, a JavaScript stack. There are four technolo-
gies that make up the MERN Stack: MongoDB, Express, React, and Node.
js. The whole point of it is to streamline and simplify the development
procedure.13
Each of these four potent technologies plays a significant role in the cre-
ation of web apps and offers a comprehensive environment for program-
mers to use.
As a jumping off point, consider: Make a new folder for the project first.
Next, open a command prompt or terminal and go to the project’s folder;
then, run the following command to create a package.json file. (Ensure
that npm is set up)
npm init
use databasename;
db.createCollection(“collectionname”);
db.collectionname.insert
“id” : 101,
“Name” : “Karan”,
“Department”: “Tech”,
);
• A document’s query:
db.collectionname.find({Name : “Karan”}).
forEach(printjson);
excellent web applications and APIs. Because Express offers so many mid-
dlewares, writing code is quicker and simpler.
npm init
});
const sampleserver = http.createServer(app);
npm start
• Now that the server is operating, we may access the output by open-
ing the browser.
OR
create-react-app appname
ReactDOM.render(
<h1>Hello EVERYONE!!</h1>,
document.getElementById(‘root’)
);
npm start
OR
yarn start
Backend Development ◾ 365
npm init
var rectangle = {
perimeter: (j, Ky) => (2*(j+k)),
area: (j, k) => (j*k)
};
function Rectangle(l, b) {
console.log(“A rectangle with l = “ + l + “
and b = “ + b);
if (l <= 0 || b <= 0) {
console.log(“Error! Rectangle’s length &
breadth should be greater than 0: l = “
+ l + “, and b = “ + b);
}
else {
366 ◾ Conquering JavaScript
Rectangle(2, 6);
Rectangle(5, 14);
Rectangle(-7, 2);
npm start
It allows users to develop massive web apps that can quickly modify
page data without requiring a page refresh.
MEAN MERN
The stack technology includes Angular.js, Stack technology includes MongoDB,
Express.js, Node.js, and MongoDB.15 React.js, Express.js, and Node.js.
The JavaScript framework Angular.js is part JavaScript library React.js is part of the
of the MEAN stack. MERN stack.
Typescript is used by Angular.js in the React.js uses JSX and JavaScript in the
MEAN stack. MERN stack.
It boosts productivity. It is not very productive.
Compared to the MERN stack, it is more It is significantly easier to learn because
challenging to master. of the superior documentation.
It helps with code management and The virtual DOM makes it possible for
rendering. fluid rendering.
The data flow is bidirectional. It only allows one way data transmission.
It is incompatible with apps for mobile devices. With mobile apps, it is compatible.
MERN VS MEAN
1. Open source: The best aspect of MERN is that the four technologies
that comprise the stack are open source (open-source). This makes it
simpler for developers to obtain quick answers from the accessible
open portals and successfully resolve any problems that may emerge
throughout the development process.
2. Cost-Effective: MERN stack developers are in high demand since
this stack utilizes just one language, JavaScript. It is considerably
more advantageous for businesses to invest in MERN-savvy person-
nel. This is a more efficient approach, both financially and in terms
of time, than recruiting experts for each technology.
3. Simple to switch between client and server: With MERN Stack, every-
thing is written in a single language, which makes it much easier for
developers to know the language (within 4–6 months with dedicated
learning). It is also simple to switch between client and server, pro-
viding developers with additional expansion opportunities.
Backend Development ◾ 369
NOTES
1 What Is Backend Developer? Skills Need for Web Development: www.
guru99.com/what-is-backend-developer.html Accessed on: 13 October
2022.
2 Using Node.js for Backend Web Development in 2022: https://mobidev.biz/
blog/node-js-for-backend-development Accessed on: 13 October 2022.
3 The Good and the Bad of Node.js Web App Development: www.altexsoft.
com/blog/engineering/the-good-and-the-bad-of-node-js-web-app-devel-
opment/ Accessed on: 13 October 2022.
4 Node.js – Introduction: www.tutorialspoint.com/nodejs/nodejs_introduc-
tion.htm Accessed on: 14 October 2022.
5 Node.js - Environment Setup: www.tutorialspoint.com/nodejs/nodejs_
environment_setup.htm Accessed on: 14 October 2022.
6 Node.js - First Application: www.tutorialspoint.com/nodejs/nodejs_first_
application.htm Accessed on: 14 October 2022.
7 What Is MongoDB – Working and Features: www.geeksforgeeks.org/what-
is-mongodb-working-and-features/ Accessed on: 14 October 2022.
8 What Is MongoDB? Introduction, Architecture, Features & Example: www.
guru99.com/what-is-mongodb.html Accessed on: 14 October 2022.
9 MongoDB: Getting Started: www.geeksforgeeks.org/mongodb-getting-
started/?ref=lbp Accessed on: 14 October 2022.
10 How to Install MongoDB on Windows?: www.geeksforgeeks.org/how-to-
install-mongodb-on-windows/ Accessed on: 14 October 2022.
11 Server-Side Website Programming: https://developer.mozilla.org/en-US/
docs/Learn/Server-side Accessed on: 15 October 2022.
12 Server-Side Javascript: www.javascriptinstitute.org/javascript-tutorial/
server-side-javascript/ Accessed on: 15 October 2022.
13 MERN Stack: www.geeksforgeeks.org/mern-stack/ Accessed on: 15
October 2022.
14 MERN Stack: www.javatpoint.com/mern-stack Accessed on: 15 October
2022.
15 What Is the MERN Stack and Why It Is the Best to Fit for Web Development:
www.groovyweb.co/blog/what-is-the-mern-stack-and-why-it-is-the-best-
to-fit-for-web-development/ Accessed on: 15 October 2022.
370 ◾ Conquering JavaScript
16 Future of MERN Stack Developers in 2022: Fewer Risks, More Rewards: www.
cybersuccess.biz/future-of-mern-stack-developers/#:~:text=MERN%20
is%20a%20free%20and,end%20or%20server%2Dside%20development.
Accessed on: 15 October 2022.
Chapter 7
JavaScript for
Mobile Usage
IN THIS CHAPTER
➢ React Native
➢ NativeScript
Extremely Responsive
One of the bothersome problems in the development sector is the net-
work’s slowness.
The problem becomes more serious when a slow network is combined
with the time it takes to send server queries, which results in delayed page
loads.
If an app can function better with fewer server bytes, users will benefit
from a faster-acting app.
JavaScript can greatly enhance the scenario by pushing XML or
JSON data instead of other sorts of data. There will be little interac-
tion with the server, quick output, and full HTML rendering in the
browser.
Consequently, using Java Script in the development has additional ben-
efits. Without further server connectivity, any modifications to the UI that
do not affect the data can be made. As a result, our app will be very user-
responsive and provide the finest experience.
Offline Assistance
The hard requirement of communicating with the server following each user
interaction is present in server-related programming. As the server is down,
the software becomes unusable. But even in the absence of the internet,
JavaScript development is still quick and responsive. Compared to the stan-
dard server-oriented development approach, it offers a significant advantage.
In JavaScript development, the frontend uses locally cached data to update
the application until connectivity is restored. This will facilitate local change
tracking and force modifications to one side after connectivity is restored.
It differs from other apps in that it carries out the essential activities
without the need for ongoing server connections. A user interface (UI)
built using Java Script loads and runs on a screen without the use of a net-
work connection. JavaScript can provide options that conventional server-
side frontend programming cannot.
PhoneGap
This makes it easier to construct a variety of platforms with a single
JavaScript code base that can serve a variety of target clients.
Ionic
The Ionic framework can be used by programmers to create, test, monitor,
and publish high-performance mobile apps. It is among the most widely
used JavaScript frameworks available, out of all of them.
374 ◾ Conquering JavaScript
React Native
With its navigable design features, this well-known open-source frame-
work makes it easier for developers to create mobile apps.
jQuery
It is never easy for developers to create apps for all kinds of mobile devices.
As there are many different topics that need to be covered, this is not an
easy job for app engineers. However, jQuery enables us to create quick,
highly responsive software that works with a variety of mobile and desk-
top platforms.
Native Language
Native script framework is a vital tool for effectively creating apps for both
iOS and Android.
The native script framework codes help to get improved user interface
functionalities in the finished product, as the name implies.
Tabris.js
Even this framework enables the creation of native iOS or Android apps
by just a single JavaScript piece of code. It is also mentioned as one of
the most popular frameworks used by programmers to create native
apps.
three coding systems work well together. HTML is the markup that
instructs the browser how to display a website’s text and images. CSS
is the style sheet, which means it gives the entire website a consistent
appearance. JavaScript improves the user experience by generating an
interactive and dynamic interface that enables web pages to respond
to a variety of variables, including events, variables, the user’s browser,
effects, and so on.
Despite what was just stated, JavaScript is not generally used for cre-
ating apps because it is the language used to create and maintain web-
sites. Additionally, even though there are ways to create apps solely using
JavaScript, there are other, more effective ways to do so.
Nevertheless, JavaScript (JS) has one significant benefit that can help us
save time: we can reuse your code for both the frontend and the backend
(Node.js).
Another benefit of JS is that it works well across all browsers, which
makes the development process simpler.
The popularity of the JS framework is growing daily. Even large corpo-
rations like Apple and IBM use JS. The angularJS team now collaborates
with Google and Microsoft, continuing the trend. JavaScript makes it sim-
ple to create apps because we only need to develop them once to release
them across all platforms (Android, iOS, and Windows).
While jQuery and other JavaScript libraries can be used to add more
sophisticated dynamic features to webpages, plain JavaScript is still fre-
quently recommended for basic client-side operations. A professional
JavaScript app can be made using a variety of frameworks, including
PhoneGap, jQuery Mobile, and Ionic.
376 ◾ Conquering JavaScript
Native React
This framework was created recently, primarily by Facebook. It is a
viable alternative for those looking to develop a single program that
works on both Android and iOS gadgets. It provides excellent perfor-
mance, perhaps even better than some of the other frameworks dis-
cussed above.
JQuery
The ‘write less, do more’ maxim is taken to a new level by the jQuery
Mobile framework, which enables us to create a single, highly branded
responsive website or application that will run on all widely used smart-
phone, tablet, and desktop platforms.
PhoneGap
By using PhoneGap, we can ‘easily create hybrid applications built with
HTML, CSS, and JavaScript using existing web development expertise.’
Create cross-platform experiences from a single codebase to connect
with our audience on any device.
Ionic
Ionic ‘helps us design, deploy, test, and monitor apps easier than ever
before, from open source to professional services.’ Although there are
many more frameworks for creating mobile apps using JavaScript, JQuery
and React Native are the most popular ones among developers.
REACT NATIVE
We will discuss about the setup, scope, benefits of React Native below:
Installation of chocolatey
2. Run the chocolaty setup program, and then copy the code under the
Install using cmd.exe section.
@"%SystemRoot%\System32\WindowsPowerShell\v1.0\
powershell.exe" -NoProfile -InputFormat None
-ExecutionPolicy Bypass -Command "iex ((New-Object
System.Net.WebClient).DownloadString('https://
chocolatey.org/install.ps1'))" && SET
"PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"
JavaScript for Mobile Usage ◾ 379
2. Run the Android Studio Set (.exe) file we downloaded and follow the
instructions.
3. Decide which functionality to install.
380 ◾ Conquering JavaScript
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-spe-
cific 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 mod-
ule’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
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’ inde-
pendence from the user interface.
JavaScript for Mobile Usage ◾ 383
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 updat-
ing and upgrading the mobile app are greatly facilitated.
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.
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
1. Insufficient Framework
Every new update or release, as we all know, brings with it a num-
ber of significant changes that might eventually be difficult for the
developers to handle.
React Native is the speedier and newer alternative in this situa-
tion, 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.
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++.
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 cross-
platform frameworks that use CPU. This is a key factor in the better per-
formance of React Native apps.
390 ◾ Conquering JavaScript
Over-the-Air Updates
React Native’s ground-breaking OTA update capability enables develop-
ers 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.
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 user-
friendly working interface, straightforward project management, hot
reloading, and device debugging. NativeScript enables programmers to
build native, cross-platform applications fast and effectively while reduc-
ing 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.
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 pre-
cisely 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.
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 develop-
ers. 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 uti-
lize 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.
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 build-
ing 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.
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.
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
tns doctor
like Kotlin or Java, can enable fast app performance and a completely plat-
form-specific user experience without compromising the code’s reusabil-
ity. 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, includ-
ing React, Angular, Vue, and others. While preserving the platform-spe-
cific user experience, Native Script can assist with platform-specific code
reuse.
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 inter-
faces, we don’t require webViews.
• Avoid performance problems at all costs.
NOTES
1. Why Is JavaScript Considered One of the Best in Mobile App Development
for 2022?: www.linkedin.com/pulse/why-javascript-considered-one-
best-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
JavaScript for
Desktop Apps
IN THIS CHAPTER
➢ Electron.js
In the previous chapter, we covered JS for mobile usage, and in this chap-
ter, 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 cutting-
edge 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.
1. Java
Java is an object-oriented, class-based programming language
that was created with the goal of requiring as little from the underly-
ing 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, next-
generation 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 desk-
top, and Slack, were developed using Electron.
Installation
Use the NPM package manager to add Electron to our project.
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 trans-
mission. WebTorrent connects the user to a decentralized browser-to-
browser network that provides efficient file sharing without the need for
plugins, extensions, or installs.
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-plat-
form application, which will work on the majority of popular platforms.
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.
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 sys-
tem, 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 tera-
bytes of memory space, the huge number of electron applications isn’t a
major concern.
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.
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>Hello Everyone!</title>
</head>
JavaScript for Desktop Apps ◾ 413
<body>
<h1>Hello Everyone!</h1>
We are using the node <script>document.
write(process.versions.node)</script>,
Chrome <script>document.write(process.versions.
chrome)</script>,
and Electron <script>document.write(process.
versions.electron)</script>.
</body>
</html>
Bower now provides access to all available JS and CSS frameworks, librar-
ies, plugins, and so forth.
For example, to get the most recent stable version of bootstrap, use the
following command:
This will also be needed in our ‘view.js’ file. We already have a’main.js’ file
as seen below.
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
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>Hello Everyone!</title>
<link rel = "stylesheet"
href = "./bower_components/bootstrap/dist/
css/bootstrap.min.css" />
</head>
<body>
<div class = "container">
<h1>This page use Bootstrap and jQuery!</h1>
<h3 id = "click-counter"></h3>
<button class = "btn btn-success" id =
"countbtn">Click</button>
<script src = "./view.js" ></script>
</div>
</body>
</html>
Create a view.js file and add the click counter logic to it.
$ 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.smashingmaga-
zine.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-advantages-
and-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_build-
ing_uis.htm Accessed on: 20 October 2022.
Chapter 9
Appraisal
JavaScript is the only technology available for browsers that combines all
three of these features.
Appraisal ◾ 419
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.
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 improve-
ments 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 devel-
opers. In addition to that, they are investigating things like server soft-
ware, 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
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 lan-
guage that does not impose any restrictions or guidelines on the develop-
ers 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 pro-
vide 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.
W e must join the JavaScript file to the HTML file in order to uti-
lize JavaScript on the website. Including comments in the coding
process will help us produce better code overall. One may use either sin-
gle-line or multi-line comments.
<script type=“text/javascript”>
// Your js code goes here
</script>
• 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:
<script src=“filename.js”></script>
429
430 ◾ Appendix I
var x = 140; // x may be redeclared and given a new value at any time
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 infor-
mational 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:
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 expres-
sion 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 (<) will return true.
• The (>=) 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 (<=) that evalu-
ates to true if the left operand is less than or equal to the right
operand.
Logical Operators
The whole set of JavaScript logical operators is as follows:
JAVASCRIPT FUNCTION
A function in JavaScript is a predefined piece of code that may be used to
accomplish a certain goal. As soon as it is called or invoked, it begins run-
ning. To save retyping the same code again and over, you may save it as a
function and call it as necessary. The functions keyword in JavaScript is used
to define new functions. JavaScript is capable of many things, including:
434 ◾ Appendix I
ARRAY IN JAVASCRIPT
It’s common practice in many languages to store data in arrays. They
may be used to classify things like variables and characteristics. An
array is a sequence of items all of the same kind. A collection of auto
mobiles, written in JavaScript:
var cars = [“Tesla”, “Toyota”, “Honda”];
With our newfound knowledge of array construction, we can apply
various transformations to the resulting data. Check out the many APIs in
JavaScript for manipulating arrays:
STRINGS IN JAVASCRIPT
Strings, as we’ve already established, are just sequences of characters that
may be put to various uses. Since Strings are so versatile in JavaScript,
we’ve decided to devote their own section to them in this reference guide.
Let’s have a look at JavaScript’s string functions and the numerous escape
sequences it supports.
In the fields of computers and communications, a ‘special character’
known as a ‘escape character’ is a character that, when followed by other
characters in a string, alters the meaning of those characters. Escape
characters make up a subset of the metacharacters that are available. The
surrounding context of a character will determine whether or not that
character may be used as an escape character. To encapsulate strings,
JavaScript may use either single quotes or double quotes. You will need
to make use of special characters in order to include quote marks into a
string. For instance, the following is a selection of escape sequences that
might be used in JavaScript:
• \\—Backslash
• \”—Double quotes
436 ◾ Appendix I
• \’—Single quotes
• \t—Horizontal tab
• \n—Newline
• \v—Vertical tab
• \r—Carriage return
• \b—Backspace
• \f—Form feed
Node Properties
Let’s start with an examination of some of the attributes of a node in the
JavaScript DOM:
Node Methods
Let’s look at some of the Node Methods supplied by JavaScript to work
with these DOM nodes:
Element Methods
This function substitutes a child node of an element with another.
Here are a few examples of the element methods available in JavaScript:
map() Method
A function is applied to each array element using the map() method. The
array’s contents are passed one by one to the callback method, which
then generates a new array with the same dimensions. This function can
be used to apply a uniform operation or transformation to each array
element and return a new array of the same length containing the resul-
tant updated values.
filter() Method
The filter() method is used to delete data from an array if it does not match
a certain condition. Each item in the array is passed along to the callback
function. The element will be added to the new array if and only if the
callback function returns true after each iteration.
440 ◾ Appendix I
reduce() Method
It is possible to combine the results of many members of an array into
a single value by using the reduce() function. Prior to making a call to
reduce, the starting value of the accumulator is required to be supplied
(final result). In the course of each cycle, we carry out an operation
in the callback, and the results of that operation are accumulated in a
variable.
Date Objects
In JavaScript, the date object is a built-in datatype. Dates and times can
be managed and modified with its help. The new Date() operator is used
to construct date objects, which can be declared in 1 of the 4 possible
ways.
Syntax
new Date()
new Date(milliseconds)
new Date(dataString)
new Date(year, month, date, hour, minute, second, millisecond)
The following are some examples of JavaScript methods that can be used
in the user’s browser:
• To warn the user and provide them the option to dismiss the warn-
ing, the alert() method presents a dialogue box.
• You may often test out an expression or run a function with the help
of the setInterval() method.
• setTimeout(): After a given amount of time has elapsed, a function
or expression is executed.
• To stop a timer that was set with setInterval(), use clearInterval().
• When called, clearTimeout() will cancel any timers that were previ-
ously created using setTimeout() ().
Appendix I ◾ 443
• To get the square root of an input value, use the function sqrt(x).
• The result of calling pow(x, y) is x raised to the yth power.
• round(x): It adjusts x to the next whole number.
• When you type sin(x), you get x’s sine value back (x is in radians).
• the tangent of an angle is given by tan(x), which in this case would
be x.
Appendix II
Brief Guide to TypeScript
Language of TypeScript
• The TypeScript code must first be compiled into JavaScript before the
compiler may begin its work.
• In fact, what takes place is not exactly compilation but rather
transpilation.
Appendix II ◾ 449
In JavaScript, types are not regarded as genuine features since they are not
used. Because TypeScript has to be changed into regular JavaScript first,
everything that has to do with types has to be removed before the code can
be regarded genuine JavaScript and submitted to the browser to be executed.
This is because TypeScript has to be converted into normal JavaScript.
In addition to this, the Typescript compiler is responsible for doing
code analysis. Errors and warnings will be generated if there is a sufficient
foundation for the system to do so.
Language Department
The task of extracting type information from the source code is within the
purview of the language service.
The development tools may use this information to give IntelliSense
type suggestions, and alternative refactorings once they have processed it.
Property ‘height’ does not exist on type ‘{ width: number; height: number;
}’. Did you mean ‘height’?Property ‘height’ does not exist on type ‘{ width:
number; height: number; }’. Did you mean ‘height’?
450 ◾ Appendix II
let a = (4
‘)’ expected.’)’ expected.
Types
TypeScript, on the other hand, is a typed superset that extends the rules
that control how different kinds of values may be applied. It does this by
extending the rules that govern how values are applied. The issue that
had been occurring before with obj.height was not due to a syntax error;
rather, it was an error that happened as a result of the incorrect application
of some sort of value (a type).
Another example of this would be the piece of JavaScript code that fol-
lows, which, when run in a web browser, would record a value as follows:
console.log(4 / []);
console.log(4 / []);
On the right side of an arithmetic operation, you are free to use any type
that is numeric, bigint, or enum. On the right hand side of an arithme-
tic operation, you may use a type that begins with “any,” “number,” or
“bigint,” or you can use an enum type.
Appendix II ◾ 451
Erased Types
When the TypeScript compiler has completed checking your code and is
ready to build the “compiled” version of the code, it will often erase all of
the types. This is done in preparation for the next step in the process. This
indicates that the simple JS code that is created when your code is com-
piled does not contain any type information.
452 ◾ Appendix II
Since of this, TypeScript will never change the way your program
works based on the types it has derived from the data you supply because
it can’t access that information. The most important thing to remember
is that even while you may see type difficulties during the compilation
process, the type system does not in and of itself have any bearing on
how your program functions when it is being run. This is the bottom line.
In conclusion, the package that contains TypeScript does not include
any additional runtime libraries. Because your apps will utilize the same
standard library (or more libraries) as JavaScript programs, there is no
additional TypeScript-specific framework that you will need to learn how
to use. This is because your applications will use the same libraries.
The above example shows how to construct a function with two argu-
ments: 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.
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
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.
Input
let x: someType;
Output
let x;
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.
If you do not want to install anything worldwide, you need to perform this
command:
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
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
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
The ts-node version number will be shown if the installation has com-
pleted successfully by using the following command:
$ npx ts-node -v
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 com-
putation, 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 state-
ment 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
*/
{
“compilerOptions”: {
“target”: “es6”,
“module”: “commonjs”,
“typeRoots”: [“./node_modules/@types”],
“esModuleInterop”: true,
“forceConsistentCasingInFileNames”: true
}
}
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 appro-
priate 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;
}
interface User {
name: string;
id: number;
}
class UserAccount {
name: string;
id: number;
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:
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:
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:
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
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 key-
word 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 impor-
tant 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.
this.engine = engine;
}
//function
Car.prototype.disp = function () {
console.log(“Engine is : “ + this.engine);
};
return Car;
}());
Syntax
var object_name = new class_name([ arguments ])
CLASS INHERITANCE
The idea of inheritance may be implemented using TypeScript. A com-
puter 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 behav-
iors 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
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 defi-
nition may access that member’s data. An error is generated by the com-
piler 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 con-
tains 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)
Function Types
Interfaces enable you to specify the sorts of functions as well as the char-
acteristics of an object.
To specify a function type, you attach the interface to the function sig-
nature that includes the argument list with types and returned types. For
instance:
interface StringFormat {
(str: string, isUpper: boolean): string
}
TypeScript, a programming language (typescript)
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.
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.
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 per-
mits 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 meaning-
ful 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 { }
}
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.
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.
FUNCTIONS IN TYPESCRIPT
Code that is understandable, easy to maintain, and versatile relies heav-
ily 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
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 pur-
pose of being placeholders for many arguments of the same type.
The name of the parameter is given a prefix consisting of three peri-
ods 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
NUMBERS IN TYPESCRIPT
The Number class performs the function of a wrapper and makes it pos-
sible 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
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
Syntax
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
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
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)
AMBIENTS IN TYPESCRIPT
In TypeScript, ambient declarations are a method for alerting the
TypeScript compiler that the actual source code is stored in another loca-
tion. These declarations may be placed anywhere in a file. If it uses a vari-
ety 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 pro-
grammer may encounter challenges while trying to utilize these packages
while preserving typesafety and intellisense at the same time. TypeScript
Appendix II ◾ 477
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:
The client TypeScript file ought to include a reference to the ambient files
in the manner shown above.
NOTES
1 A Brief History/A Static Type Checker/ (2022, October 19)/ www.type-
scriptlang.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-your-
typescript-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
OVERVIEW OF GULP
We will talk about Gulp with its installation and advantages and
disadvantages.1
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.
History
The CC0 license applies to all Gulp documentation. Gulp v1.0.0 was ini-
tially released on January 15, 2015, and the current version is v3.9.0.
Features
Advantages
Disadvantages
INSTALLATION OF GULP
This session walks us through the installation of Gulp step by step.2
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
• 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
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 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
Some of the jobs that the build system is capable of doing are listed below:
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
Task Executors
Task runners automate various development activities, including minify-
ing files, enhancing photos, and converting SASS to CSS. In the contem-
porary front-end work environment, Gulp is one of the task runners and
runs on Node.
484 ◾ Appendix III
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 configu-
ration file. The following command line may use to install this plugin,
which can use to compress the image file:
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 func-
tion as a task with a name.
As illustrated in the following code, we may build the task for the previ-
ously 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 direc-
tory src/images/**/*. The imagemin constructor pipes it to further func-
tions. 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.
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 man-
ually 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.
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
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 repeti-
tive 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 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
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
• 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.
System Variable
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 grunt-
function 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 indi-
cated appropriately.
We may generate the basic “package.json” file by using the following
command at the command prompt:
npm init
{
“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”
}
}
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
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.
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.
package.json
When we execute the command npm install in the same folder, the pack-
age.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:
{
“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 exist-
ing “pacakge.json” file.
For example, the command below will update Grunt to the most recent
version and add it to our devDependencies.
Gruntfile
By default, our Grunt configuration settings will be stored in the Gruntfile.
js file. The following components are present in the Grunt file:
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
}
grunt.task.loadNpmTasks(plugin_Name)
Custom Tasks
Grunt will search for the default task when executed through the com-
mand 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, concate-
nating 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.
OVERVIEW OF NPM
We will talk about npm with its installation and advantages and
disadvantages.
Components of npm
The npm is made up of three distinct components, which are as follows:
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.
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.
Then, use the commands node -v and npm -v to verify the Node.js and
npm versions in our terminal.
node -v
npm -v
nvm list
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
Download npm
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 check-
box 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.
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 “pack-
age.json” file will create with the essential metadata details supplied by
developers:
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
Example on Mac OS
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
C:\>npm whoami
If not, login:
C:\>npm login
Username: <our username>
Password: <our password>
C:\Users\my_user>cd my_project
C:\Users\my_user\my_project>npm publish
{
“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”
}
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
509
510 ◾ Index